You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset.go 16 kB

5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "code.gitea.io/gitea/modules/setting"
  8. "code.gitea.io/gitea/modules/log"
  9. "code.gitea.io/gitea/modules/timeutil"
  10. "xorm.io/builder"
  11. )
  12. const (
  13. DatasetStatusPrivate int32 = iota
  14. DatasetStatusPublic
  15. DatasetStatusDeleted
  16. )
  17. type Dataset struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. Title string `xorm:"INDEX NOT NULL"`
  20. Status int32 `xorm:"INDEX"` // normal_private: 0, pulbic: 1, is_delete: 2
  21. Category string
  22. Description string `xorm:"TEXT"`
  23. DownloadTimes int64
  24. UseCount int64 `xorm:"DEFAULT 0"`
  25. NumStars int `xorm:"INDEX NOT NULL DEFAULT 0"`
  26. Recommend bool `xorm:"INDEX NOT NULL DEFAULT false"`
  27. License string
  28. Task string
  29. ReleaseID int64 `xorm:"INDEX"`
  30. UserID int64 `xorm:"INDEX"`
  31. RepoID int64 `xorm:"INDEX"`
  32. Repo *Repository `xorm:"-"`
  33. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  34. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  35. User *User `xorm:"-"`
  36. Attachments []*Attachment `xorm:"-"`
  37. }
  38. type DatasetWithStar struct {
  39. Dataset
  40. IsStaring bool
  41. }
  42. func (d *Dataset) IsPrivate() bool {
  43. switch d.Status {
  44. case DatasetStatusPrivate:
  45. return true
  46. case DatasetStatusPublic:
  47. return false
  48. case DatasetStatusDeleted:
  49. return false
  50. default:
  51. return false
  52. }
  53. }
  54. type DatasetList []*Dataset
  55. func (datasets DatasetList) loadAttributes(e Engine) error {
  56. if len(datasets) == 0 {
  57. return nil
  58. }
  59. set := make(map[int64]struct{})
  60. userIdSet := make(map[int64]struct{})
  61. datasetIDs := make([]int64, len(datasets))
  62. for i := range datasets {
  63. userIdSet[datasets[i].UserID] = struct{}{}
  64. set[datasets[i].RepoID] = struct{}{}
  65. datasetIDs[i] = datasets[i].ID
  66. }
  67. // Load owners.
  68. users := make(map[int64]*User, len(userIdSet))
  69. repos := make(map[int64]*Repository, len(set))
  70. if err := e.
  71. Where("id > 0").
  72. In("id", keysInt64(userIdSet)).
  73. Cols("id", "lower_name", "name", "full_name", "email").
  74. Find(&users); err != nil {
  75. return fmt.Errorf("find users: %v", err)
  76. }
  77. if err := e.
  78. Where("id > 0").
  79. In("id", keysInt64(set)).
  80. Cols("id", "owner_id", "owner_name", "lower_name", "name", "description", "alias", "lower_alias", "is_private").
  81. Find(&repos); err != nil {
  82. return fmt.Errorf("find repos: %v", err)
  83. }
  84. for i := range datasets {
  85. datasets[i].User = users[datasets[i].UserID]
  86. datasets[i].Repo = repos[datasets[i].RepoID]
  87. }
  88. return nil
  89. }
  90. func (datasets DatasetList) loadAttachmentAttributes(opts *SearchDatasetOptions) error {
  91. if len(datasets) == 0 {
  92. return nil
  93. }
  94. datasetIDs := make([]int64, len(datasets))
  95. for i := range datasets {
  96. datasetIDs[i] = datasets[i].ID
  97. }
  98. attachments, err := AttachmentsByDatasetOption(datasetIDs, opts)
  99. if err != nil {
  100. return fmt.Errorf("GetAttachmentsByDatasetIds failed error: %v", err)
  101. }
  102. permissionMap := make(map[int64]bool, len(datasets))
  103. for _, attachment := range attachments {
  104. for i := range datasets {
  105. if attachment.DatasetID == datasets[i].ID {
  106. if !attachment.IsPrivate{
  107. datasets[i].Attachments = append(datasets[i].Attachments, attachment)
  108. }else{
  109. permission, ok := permissionMap[datasets[i].ID]
  110. if !ok {
  111. permission = false
  112. datasets[i].Repo.GetOwner()
  113. if !permission {
  114. isCollaborator, _ := datasets[i].Repo.IsCollaborator(opts.User.ID)
  115. isInRepoTeam,_:=datasets[i].Repo.IsInRepoTeam(opts.User.ID)
  116. if isCollaborator ||isInRepoTeam {
  117. log.Info("Collaborator user may visit the attach.")
  118. permission = true
  119. }
  120. }
  121. permissionMap[datasets[i].ID] = permission
  122. }
  123. if permission {
  124. datasets[i].Attachments = append(datasets[i].Attachments, attachment)
  125. }
  126. }
  127. }
  128. }
  129. }
  130. for i := range datasets {
  131. if datasets[i].Attachments == nil {
  132. datasets[i].Attachments = []*Attachment{}
  133. }
  134. datasets[i].Repo.Owner = nil
  135. }
  136. return nil
  137. }
  138. type SearchDatasetOptions struct {
  139. Keyword string
  140. OwnerID int64
  141. User *User
  142. RepoID int64
  143. IncludePublic bool
  144. RecommendOnly bool
  145. Category string
  146. Task string
  147. License string
  148. DatasetIDs []int64
  149. ExcludeDatasetId int64
  150. ListOptions
  151. SearchOrderBy
  152. IsOwner bool
  153. StarByMe bool
  154. CloudBrainType int //0 cloudbrain 1 modelarts -1 all
  155. PublicOnly bool
  156. JustNeedZipFile bool
  157. NeedAttachment bool
  158. UploadAttachmentByMe bool
  159. QueryReference bool
  160. }
  161. func CreateDataset(dataset *Dataset) (err error) {
  162. sess := x.NewSession()
  163. defer sess.Close()
  164. if err := sess.Begin(); err != nil {
  165. return err
  166. }
  167. datasetByRepoId := &Dataset{RepoID: dataset.RepoID}
  168. has, err := sess.Get(datasetByRepoId)
  169. if err != nil {
  170. return err
  171. }
  172. if has {
  173. return fmt.Errorf("The dataset already exists.")
  174. }
  175. if _, err = sess.Insert(dataset); err != nil {
  176. return err
  177. }
  178. return sess.Commit()
  179. }
  180. func RecommendDataset(dataSetId int64, recommend bool) error {
  181. dataset := Dataset{Recommend: recommend}
  182. _, err := x.ID(dataSetId).Cols("recommend").Update(dataset)
  183. return err
  184. }
  185. func SearchDataset(opts *SearchDatasetOptions) (DatasetList, int64, error) {
  186. cond := SearchDatasetCondition(opts)
  187. return SearchDatasetByCondition(opts, cond)
  188. }
  189. func SearchDatasetCondition(opts *SearchDatasetOptions) builder.Cond {
  190. var cond = builder.NewCond()
  191. cond = cond.And(builder.Neq{"dataset.status": DatasetStatusDeleted})
  192. cond = generateFilterCond(opts, cond)
  193. if opts.RepoID > 0 {
  194. cond = cond.And(builder.Eq{"dataset.repo_id": opts.RepoID})
  195. }
  196. if opts.ExcludeDatasetId > 0 {
  197. cond = cond.And(builder.Neq{"dataset.id": opts.ExcludeDatasetId})
  198. }
  199. if opts.PublicOnly {
  200. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  201. cond = cond.And(builder.Eq{"attachment.is_private": false})
  202. } else if opts.IncludePublic {
  203. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  204. cond = cond.And(builder.Eq{"attachment.is_private": false})
  205. if opts.OwnerID > 0 {
  206. subCon := builder.NewCond()
  207. subCon = subCon.And(builder.Eq{"repository.owner_id": opts.OwnerID})
  208. subCon = generateFilterCond(opts, subCon)
  209. cond = cond.Or(subCon)
  210. }
  211. } else if opts.OwnerID > 0 && !opts.StarByMe && !opts.UploadAttachmentByMe {
  212. cond = cond.And(builder.Eq{"repository.owner_id": opts.OwnerID})
  213. if !opts.IsOwner {
  214. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  215. cond = cond.And(builder.Eq{"attachment.is_private": false})
  216. }
  217. }
  218. if len(opts.DatasetIDs) > 0 {
  219. if opts.StarByMe || (opts.RepoID == 0 && opts.QueryReference) {
  220. cond = cond.And(builder.In("dataset.id", opts.DatasetIDs))
  221. } else {
  222. subCon := builder.NewCond()
  223. subCon = subCon.And(builder.In("dataset.id", opts.DatasetIDs))
  224. subCon = generateFilterCond(opts, subCon)
  225. cond = cond.Or(subCon)
  226. }
  227. } else {
  228. if opts.StarByMe {
  229. cond = cond.And(builder.Eq{"dataset.id": -1})
  230. }
  231. }
  232. return cond
  233. }
  234. func generateFilterCond(opts *SearchDatasetOptions, cond builder.Cond) builder.Cond {
  235. if len(opts.Keyword) > 0 {
  236. cond = cond.And(builder.Or(builder.Like{"LOWER(dataset.title)", strings.ToLower(opts.Keyword)}, builder.Like{"LOWER(dataset.description)", strings.ToLower(opts.Keyword)}))
  237. }
  238. if len(opts.Category) > 0 {
  239. cond = cond.And(builder.Eq{"dataset.category": opts.Category})
  240. }
  241. if len(opts.Task) > 0 {
  242. cond = cond.And(builder.Eq{"dataset.task": opts.Task})
  243. }
  244. if len(opts.License) > 0 {
  245. cond = cond.And(builder.Eq{"dataset.license": opts.License})
  246. }
  247. if opts.RecommendOnly {
  248. cond = cond.And(builder.Eq{"dataset.recommend": opts.RecommendOnly})
  249. }
  250. if opts.JustNeedZipFile {
  251. cond = cond.And(builder.Gt{"attachment.decompress_state": 0})
  252. }
  253. if opts.CloudBrainType >= 0 {
  254. cond = cond.And(builder.Eq{"attachment.type": opts.CloudBrainType})
  255. }
  256. if opts.UploadAttachmentByMe {
  257. cond = cond.And(builder.Eq{"attachment.uploader_id": opts.User.ID})
  258. }
  259. return cond
  260. }
  261. func SearchDatasetByCondition(opts *SearchDatasetOptions, cond builder.Cond) (DatasetList, int64, error) {
  262. if opts.Page <= 0 {
  263. opts.Page = 1
  264. }
  265. var err error
  266. sess := x.NewSession()
  267. defer sess.Close()
  268. datasets := make(DatasetList, 0, opts.PageSize)
  269. selectColumnsSql := "distinct dataset.id,dataset.title, dataset.status, dataset.category, dataset.description, dataset.download_times, dataset.license, dataset.task, dataset.release_id, dataset.user_id, dataset.repo_id, dataset.created_unix,dataset.updated_unix,dataset.num_stars,dataset.recommend,dataset.use_count"
  270. count, err := sess.Distinct("dataset.id").Join("INNER", "repository", "repository.id = dataset.repo_id").
  271. Join("INNER", "attachment", "attachment.dataset_id=dataset.id").
  272. Where(cond).Count(new(Dataset))
  273. if err != nil {
  274. return nil, 0, fmt.Errorf("Count: %v", err)
  275. }
  276. builderQuery := builder.Dialect(setting.Database.Type).Select("id", "title", "status", "category", "description", "download_times", "license", "task", "release_id", "user_id", "repo_id", "created_unix", "updated_unix", "num_stars", "recommend", "use_count").From(builder.Dialect(setting.Database.Type).Select(selectColumnsSql).From("dataset").Join("INNER", "repository", "repository.id = dataset.repo_id").
  277. Join("INNER", "attachment", "attachment.dataset_id=dataset.id").
  278. Where(cond), "d").OrderBy(opts.SearchOrderBy.String())
  279. if opts.PageSize > 0 {
  280. builderQuery.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  281. }
  282. if err = sess.SQL(builderQuery).Find(&datasets); err != nil {
  283. return nil, 0, fmt.Errorf("Dataset: %v", err)
  284. }
  285. if err = datasets.loadAttributes(sess); err != nil {
  286. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  287. }
  288. if opts.NeedAttachment {
  289. if err = datasets.loadAttachmentAttributes(opts); err != nil {
  290. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  291. }
  292. }
  293. return datasets, count, nil
  294. }
  295. type datasetMetaSearch struct {
  296. ID []int64
  297. Rel []*Dataset
  298. }
  299. func (s datasetMetaSearch) Len() int {
  300. return len(s.ID)
  301. }
  302. func (s datasetMetaSearch) Swap(i, j int) {
  303. s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
  304. s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
  305. }
  306. func (s datasetMetaSearch) Less(i, j int) bool {
  307. return s.ID[i] < s.ID[j]
  308. }
  309. func GetDatasetAttachments(typeCloudBrain int, isSigned bool, user *User, rels ...*Dataset) (err error) {
  310. return getDatasetAttachments(x, typeCloudBrain, isSigned, user, rels...)
  311. }
  312. func getDatasetAttachments(e Engine, typeCloudBrain int, isSigned bool, user *User, rels ...*Dataset) (err error) {
  313. if len(rels) == 0 {
  314. return
  315. }
  316. // To keep this efficient as possible sort all datasets by id,
  317. // select attachments by dataset id,
  318. // then merge join them
  319. // Sort
  320. var sortedRels = datasetMetaSearch{ID: make([]int64, len(rels)), Rel: make([]*Dataset, len(rels))}
  321. var attachments []*Attachment
  322. for index, element := range rels {
  323. element.Attachments = []*Attachment{}
  324. sortedRels.ID[index] = element.ID
  325. sortedRels.Rel[index] = element
  326. }
  327. sort.Sort(sortedRels)
  328. // Select attachments
  329. if typeCloudBrain == -1 {
  330. err = e.
  331. Asc("dataset_id").
  332. In("dataset_id", sortedRels.ID).
  333. Find(&attachments, Attachment{})
  334. if err != nil {
  335. return err
  336. }
  337. } else {
  338. err = e.
  339. Asc("dataset_id").
  340. In("dataset_id", sortedRels.ID).
  341. And("type = ?", typeCloudBrain).
  342. Find(&attachments, Attachment{})
  343. if err != nil {
  344. return err
  345. }
  346. }
  347. // merge join
  348. var currentIndex = 0
  349. for _, attachment := range attachments {
  350. for sortedRels.ID[currentIndex] < attachment.DatasetID {
  351. currentIndex++
  352. }
  353. fileChunks := make([]*FileChunk, 0, 10)
  354. err = e.
  355. Where("uuid = ?", attachment.UUID).
  356. Find(&fileChunks)
  357. if err != nil {
  358. return err
  359. }
  360. if len(fileChunks) > 0 {
  361. attachment.Md5 = fileChunks[0].Md5
  362. } else {
  363. log.Error("has attachment record, but has no file_chunk record")
  364. attachment.Md5 = "no_record"
  365. }
  366. attachment.CanDel = CanDelAttachment(isSigned, user, attachment)
  367. sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
  368. }
  369. return
  370. }
  371. // AddDatasetAttachments adds a Dataset attachments
  372. func AddDatasetAttachments(DatasetID int64, attachmentUUIDs []string) (err error) {
  373. // Check attachments
  374. attachments, err := GetAttachmentsByUUIDs(attachmentUUIDs)
  375. if err != nil {
  376. return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err)
  377. }
  378. for i := range attachments {
  379. attachments[i].DatasetID = DatasetID
  380. // No assign value could be 0, so ignore AllCols().
  381. if _, err = x.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  382. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  383. }
  384. }
  385. return
  386. }
  387. func UpdateDataset(ctx DBContext, rel *Dataset) error {
  388. _, err := ctx.e.ID(rel.ID).AllCols().Update(rel)
  389. return err
  390. }
  391. func IncreaseDatasetUseCount(uuid string) {
  392. IncreaseAttachmentUseNumber(uuid)
  393. attachments, _ := GetAttachmentsByUUIDs(strings.Split(uuid, ";"))
  394. countMap := make(map[int64]int)
  395. for _, attachment := range attachments {
  396. value, ok := countMap[attachment.DatasetID]
  397. if ok {
  398. countMap[attachment.DatasetID] = value + 1
  399. } else {
  400. countMap[attachment.DatasetID] = 1
  401. }
  402. }
  403. for key, value := range countMap {
  404. x.Exec("UPDATE `dataset` SET use_count=use_count+? WHERE id=?", value, key)
  405. }
  406. }
  407. // GetDatasetByID returns Dataset with given ID.
  408. func GetDatasetByID(id int64) (*Dataset, error) {
  409. rel := new(Dataset)
  410. has, err := x.
  411. ID(id).
  412. Get(rel)
  413. if err != nil {
  414. return nil, err
  415. } else if !has {
  416. return nil, ErrDatasetNotExist{id}
  417. }
  418. return rel, nil
  419. }
  420. func GetDatasetByRepo(repo *Repository) (*Dataset, error) {
  421. dataset := &Dataset{RepoID: repo.ID}
  422. has, err := x.Get(dataset)
  423. if err != nil {
  424. return nil, err
  425. }
  426. if has {
  427. return dataset, nil
  428. } else {
  429. return nil, ErrNotExist{repo.ID}
  430. }
  431. }
  432. func GetDatasetStarByUser(user *User) ([]*DatasetStar, error) {
  433. datasetStars := make([]*DatasetStar, 0)
  434. err := x.Cols("id", "uid", "dataset_id", "created_unix").Where("uid=?", user.ID).Find(&datasetStars)
  435. return datasetStars, err
  436. }
  437. func DeleteDataset(datasetID int64, uid int64) error {
  438. var err error
  439. sess := x.NewSession()
  440. defer sess.Close()
  441. if err = sess.Begin(); err != nil {
  442. return err
  443. }
  444. dataset := &Dataset{ID: datasetID, UserID: uid}
  445. has, err := sess.Get(dataset)
  446. if err != nil {
  447. return err
  448. } else if !has {
  449. return errors.New("not found")
  450. }
  451. if cnt, err := sess.ID(datasetID).Delete(new(Dataset)); err != nil {
  452. return err
  453. } else if cnt != 1 {
  454. return errors.New("not found")
  455. }
  456. if err = sess.Commit(); err != nil {
  457. sess.Close()
  458. return fmt.Errorf("Commit: %v", err)
  459. }
  460. return nil
  461. }
  462. func GetOwnerDatasetByID(id int64, user *User) (*Dataset, error) {
  463. dataset, err := GetDatasetByID(id)
  464. if err != nil {
  465. return nil, err
  466. }
  467. if !dataset.IsPrivate() {
  468. return dataset, nil
  469. }
  470. if dataset.IsPrivate() && user != nil && user.ID == dataset.UserID {
  471. return dataset, nil
  472. }
  473. return nil, errors.New("dataset not fount")
  474. }
  475. func IncreaseDownloadCount(datasetID int64) error {
  476. // Update download count.
  477. if _, err := x.Exec("UPDATE `dataset` SET download_times=download_times+1 WHERE id=?", datasetID); err != nil {
  478. return fmt.Errorf("increase dataset count: %v", err)
  479. }
  480. return nil
  481. }
  482. func GetCollaboratorDatasetIdsByUserID(userID int64) []int64 {
  483. var datasets []int64
  484. _ = x.Table("dataset").Join("INNER", "collaboration", "dataset.repo_id = collaboration.repo_id and collaboration.mode>0 and collaboration.user_id=?", userID).
  485. Cols("dataset.id").Find(&datasets)
  486. return datasets
  487. }
  488. func GetTeamDatasetIdsByUserID(userID int64) []int64 {
  489. var datasets []int64
  490. _ = x.Table("dataset").Join("INNER", "team_repo", "dataset.repo_id = team_repo.repo_id").
  491. Join("INNER", "team_user", "team_repo.team_id=team_user.team_id and team_user.uid=?", userID).
  492. Cols("dataset.id").Find(&datasets)
  493. return datasets
  494. }
  495. func UpdateDatasetCreateUser(ID int64, user *User) error {
  496. _, err := x.Where("id = ?", ID).Cols("user_id").Update(&Dataset{
  497. UserID: user.ID,
  498. })
  499. if err != nil {
  500. return err
  501. }
  502. return nil
  503. }