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
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
4 years ago
3 years ago
4 years ago
5 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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 opts.StarByMe {
  107. permission, ok := permissionMap[datasets[i].ID]
  108. if !ok {
  109. permission = false
  110. datasets[i].Repo.GetOwner()
  111. if datasets[i].Repo.Owner.IsOrganization() {
  112. if datasets[i].Repo.Owner.IsUserPartOfOrg(opts.User.ID) {
  113. log.Info("user is member of org.")
  114. permission = true
  115. }
  116. }
  117. if !permission {
  118. isCollaborator, _ := datasets[i].Repo.IsCollaborator(opts.User.ID)
  119. if isCollaborator {
  120. log.Info("Collaborator user may visit the attach.")
  121. permission = true
  122. }
  123. }
  124. permissionMap[datasets[i].ID] = permission
  125. }
  126. if permission {
  127. datasets[i].Attachments = append(datasets[i].Attachments, attachment)
  128. } else if !attachment.IsPrivate {
  129. datasets[i].Attachments = append(datasets[i].Attachments, attachment)
  130. }
  131. } else {
  132. datasets[i].Attachments = append(datasets[i].Attachments, attachment)
  133. }
  134. }
  135. }
  136. }
  137. for i := range datasets {
  138. if datasets[i].Attachments == nil {
  139. datasets[i].Attachments = []*Attachment{}
  140. }
  141. datasets[i].Repo.Owner = nil
  142. }
  143. return nil
  144. }
  145. type SearchDatasetOptions struct {
  146. Keyword string
  147. OwnerID int64
  148. User *User
  149. RepoID int64
  150. IncludePublic bool
  151. RecommendOnly bool
  152. Category string
  153. Task string
  154. License string
  155. DatasetIDs []int64
  156. ListOptions
  157. SearchOrderBy
  158. IsOwner bool
  159. StarByMe bool
  160. CloudBrainType int //0 cloudbrain 1 modelarts -1 all
  161. PublicOnly bool
  162. JustNeedZipFile bool
  163. NeedAttachment bool
  164. UploadAttachmentByMe bool
  165. }
  166. func CreateDataset(dataset *Dataset) (err error) {
  167. sess := x.NewSession()
  168. defer sess.Close()
  169. if err := sess.Begin(); err != nil {
  170. return err
  171. }
  172. datasetByRepoId := &Dataset{RepoID: dataset.RepoID}
  173. has, err := sess.Get(datasetByRepoId)
  174. if err != nil {
  175. return err
  176. }
  177. if has {
  178. return fmt.Errorf("The dataset already exists.")
  179. }
  180. if _, err = sess.Insert(dataset); err != nil {
  181. return err
  182. }
  183. return sess.Commit()
  184. }
  185. func RecommendDataset(dataSetId int64, recommend bool) error {
  186. dataset := Dataset{Recommend: recommend}
  187. _, err := x.ID(dataSetId).Cols("recommend").Update(dataset)
  188. return err
  189. }
  190. func SearchDataset(opts *SearchDatasetOptions) (DatasetList, int64, error) {
  191. cond := SearchDatasetCondition(opts)
  192. return SearchDatasetByCondition(opts, cond)
  193. }
  194. func SearchDatasetCondition(opts *SearchDatasetOptions) builder.Cond {
  195. var cond = builder.NewCond()
  196. cond = cond.And(builder.Neq{"dataset.status": DatasetStatusDeleted})
  197. cond = generateFilterCond(opts, cond)
  198. if opts.RepoID > 0 {
  199. cond = cond.And(builder.Eq{"dataset.repo_id": opts.RepoID})
  200. }
  201. if opts.PublicOnly {
  202. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  203. cond = cond.And(builder.Eq{"attachment.is_private": false})
  204. } else if opts.IncludePublic {
  205. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  206. cond = cond.And(builder.Eq{"attachment.is_private": false})
  207. if opts.OwnerID > 0 {
  208. subCon := builder.NewCond()
  209. subCon = subCon.And(builder.Eq{"repository.owner_id": opts.OwnerID})
  210. subCon = generateFilterCond(opts, subCon)
  211. cond = cond.Or(subCon)
  212. }
  213. } else if opts.OwnerID > 0 && !opts.StarByMe && !opts.UploadAttachmentByMe {
  214. cond = cond.And(builder.Eq{"repository.owner_id": opts.OwnerID})
  215. if !opts.IsOwner {
  216. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  217. cond = cond.And(builder.Eq{"attachment.is_private": false})
  218. }
  219. }
  220. if len(opts.DatasetIDs) > 0 {
  221. if opts.StarByMe {
  222. cond = cond.And(builder.In("dataset.id", opts.DatasetIDs))
  223. } else {
  224. subCon := builder.NewCond()
  225. subCon = subCon.And(builder.In("dataset.id", opts.DatasetIDs))
  226. subCon = generateFilterCond(opts, subCon)
  227. cond = cond.Or(subCon)
  228. }
  229. } else {
  230. if opts.StarByMe {
  231. cond = cond.And(builder.Eq{"dataset.id": -1})
  232. }
  233. }
  234. return cond
  235. }
  236. func generateFilterCond(opts *SearchDatasetOptions, cond builder.Cond) builder.Cond {
  237. if len(opts.Keyword) > 0 {
  238. cond = cond.And(builder.Or(builder.Like{"LOWER(dataset.title)", strings.ToLower(opts.Keyword)}, builder.Like{"LOWER(dataset.description)", strings.ToLower(opts.Keyword)}))
  239. }
  240. if len(opts.Category) > 0 {
  241. cond = cond.And(builder.Eq{"dataset.category": opts.Category})
  242. }
  243. if len(opts.Task) > 0 {
  244. cond = cond.And(builder.Eq{"dataset.task": opts.Task})
  245. }
  246. if len(opts.License) > 0 {
  247. cond = cond.And(builder.Eq{"dataset.license": opts.License})
  248. }
  249. if opts.RecommendOnly {
  250. cond = cond.And(builder.Eq{"dataset.recommend": opts.RecommendOnly})
  251. }
  252. if opts.JustNeedZipFile {
  253. cond = cond.And(builder.Gt{"attachment.decompress_state": 0})
  254. }
  255. if opts.CloudBrainType >= 0 {
  256. cond = cond.And(builder.Eq{"attachment.type": opts.CloudBrainType})
  257. }
  258. if opts.UploadAttachmentByMe {
  259. cond = cond.And(builder.Eq{"attachment.uploader_id": opts.User.ID})
  260. }
  261. return cond
  262. }
  263. func SearchDatasetByCondition(opts *SearchDatasetOptions, cond builder.Cond) (DatasetList, int64, error) {
  264. if opts.Page <= 0 {
  265. opts.Page = 1
  266. }
  267. var err error
  268. sess := x.NewSession()
  269. defer sess.Close()
  270. datasets := make(DatasetList, 0, opts.PageSize)
  271. 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"
  272. count, err := sess.Distinct("dataset.id").Join("INNER", "repository", "repository.id = dataset.repo_id").
  273. Join("INNER", "attachment", "attachment.dataset_id=dataset.id").
  274. Where(cond).Count(new(Dataset))
  275. if err != nil {
  276. return nil, 0, fmt.Errorf("Count: %v", err)
  277. }
  278. 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").
  279. Join("INNER", "attachment", "attachment.dataset_id=dataset.id").
  280. Where(cond), "d").OrderBy(opts.SearchOrderBy.String())
  281. if opts.PageSize > 0 {
  282. builderQuery.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  283. }
  284. if err = sess.SQL(builderQuery).Find(&datasets); err != nil {
  285. return nil, 0, fmt.Errorf("Dataset: %v", err)
  286. }
  287. if err = datasets.loadAttributes(sess); err != nil {
  288. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  289. }
  290. if opts.NeedAttachment {
  291. if err = datasets.loadAttachmentAttributes(opts); err != nil {
  292. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  293. }
  294. }
  295. return datasets, count, nil
  296. }
  297. type datasetMetaSearch struct {
  298. ID []int64
  299. Rel []*Dataset
  300. }
  301. func (s datasetMetaSearch) Len() int {
  302. return len(s.ID)
  303. }
  304. func (s datasetMetaSearch) Swap(i, j int) {
  305. s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
  306. s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
  307. }
  308. func (s datasetMetaSearch) Less(i, j int) bool {
  309. return s.ID[i] < s.ID[j]
  310. }
  311. func GetDatasetAttachments(typeCloudBrain int, isSigned bool, user *User, rels ...*Dataset) (err error) {
  312. return getDatasetAttachments(x, typeCloudBrain, isSigned, user, rels...)
  313. }
  314. func getDatasetAttachments(e Engine, typeCloudBrain int, isSigned bool, user *User, rels ...*Dataset) (err error) {
  315. if len(rels) == 0 {
  316. return
  317. }
  318. // To keep this efficient as possible sort all datasets by id,
  319. // select attachments by dataset id,
  320. // then merge join them
  321. // Sort
  322. var sortedRels = datasetMetaSearch{ID: make([]int64, len(rels)), Rel: make([]*Dataset, len(rels))}
  323. var attachments []*Attachment
  324. for index, element := range rels {
  325. element.Attachments = []*Attachment{}
  326. sortedRels.ID[index] = element.ID
  327. sortedRels.Rel[index] = element
  328. }
  329. sort.Sort(sortedRels)
  330. // Select attachments
  331. if typeCloudBrain == -1 {
  332. err = e.
  333. Asc("dataset_id").
  334. In("dataset_id", sortedRels.ID).
  335. Find(&attachments, Attachment{})
  336. if err != nil {
  337. return err
  338. }
  339. } else {
  340. err = e.
  341. Asc("dataset_id").
  342. In("dataset_id", sortedRels.ID).
  343. And("type = ?", typeCloudBrain).
  344. Find(&attachments, Attachment{})
  345. if err != nil {
  346. return err
  347. }
  348. }
  349. // merge join
  350. var currentIndex = 0
  351. for _, attachment := range attachments {
  352. for sortedRels.ID[currentIndex] < attachment.DatasetID {
  353. currentIndex++
  354. }
  355. fileChunks := make([]*FileChunk, 0, 10)
  356. err = e.
  357. Where("uuid = ?", attachment.UUID).
  358. Find(&fileChunks)
  359. if err != nil {
  360. return err
  361. }
  362. if len(fileChunks) > 0 {
  363. attachment.Md5 = fileChunks[0].Md5
  364. } else {
  365. log.Error("has attachment record, but has no file_chunk record")
  366. attachment.Md5 = "no_record"
  367. }
  368. attachment.CanDel = CanDelAttachment(isSigned, user, attachment)
  369. sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
  370. }
  371. return
  372. }
  373. // AddDatasetAttachments adds a Dataset attachments
  374. func AddDatasetAttachments(DatasetID int64, attachmentUUIDs []string) (err error) {
  375. // Check attachments
  376. attachments, err := GetAttachmentsByUUIDs(attachmentUUIDs)
  377. if err != nil {
  378. return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err)
  379. }
  380. for i := range attachments {
  381. attachments[i].DatasetID = DatasetID
  382. // No assign value could be 0, so ignore AllCols().
  383. if _, err = x.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  384. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  385. }
  386. }
  387. return
  388. }
  389. func UpdateDataset(ctx DBContext, rel *Dataset) error {
  390. _, err := ctx.e.ID(rel.ID).AllCols().Update(rel)
  391. return err
  392. }
  393. func IncreaseDatasetUseCount(uuid string) {
  394. IncreaseAttachmentUseNumber(uuid)
  395. attachments, _ := GetAttachmentsByUUIDs(strings.Split(uuid, ";"))
  396. countMap := make(map[int64]int)
  397. for _, attachment := range attachments {
  398. value, ok := countMap[attachment.DatasetID]
  399. if ok {
  400. countMap[attachment.DatasetID] = value + 1
  401. } else {
  402. countMap[attachment.DatasetID] = 1
  403. }
  404. }
  405. for key, value := range countMap {
  406. x.Exec("UPDATE `dataset` SET use_count=use_count+? WHERE id=?", value, key)
  407. }
  408. }
  409. // GetDatasetByID returns Dataset with given ID.
  410. func GetDatasetByID(id int64) (*Dataset, error) {
  411. rel := new(Dataset)
  412. has, err := x.
  413. ID(id).
  414. Get(rel)
  415. if err != nil {
  416. return nil, err
  417. } else if !has {
  418. return nil, ErrDatasetNotExist{id}
  419. }
  420. return rel, nil
  421. }
  422. func GetDatasetByRepo(repo *Repository) (*Dataset, error) {
  423. dataset := &Dataset{RepoID: repo.ID}
  424. has, err := x.Get(dataset)
  425. if err != nil {
  426. return nil, err
  427. }
  428. if has {
  429. return dataset, nil
  430. } else {
  431. return nil, ErrNotExist{repo.ID}
  432. }
  433. }
  434. func GetDatasetStarByUser(user *User) ([]*DatasetStar, error) {
  435. datasetStars := make([]*DatasetStar, 0)
  436. err := x.Cols("id", "uid", "dataset_id", "created_unix").Where("uid=?", user.ID).Find(&datasetStars)
  437. return datasetStars, err
  438. }
  439. func DeleteDataset(datasetID int64, uid int64) error {
  440. var err error
  441. sess := x.NewSession()
  442. defer sess.Close()
  443. if err = sess.Begin(); err != nil {
  444. return err
  445. }
  446. dataset := &Dataset{ID: datasetID, UserID: uid}
  447. has, err := sess.Get(dataset)
  448. if err != nil {
  449. return err
  450. } else if !has {
  451. return errors.New("not found")
  452. }
  453. if cnt, err := sess.ID(datasetID).Delete(new(Dataset)); err != nil {
  454. return err
  455. } else if cnt != 1 {
  456. return errors.New("not found")
  457. }
  458. if err = sess.Commit(); err != nil {
  459. sess.Close()
  460. return fmt.Errorf("Commit: %v", err)
  461. }
  462. return nil
  463. }
  464. func GetOwnerDatasetByID(id int64, user *User) (*Dataset, error) {
  465. dataset, err := GetDatasetByID(id)
  466. if err != nil {
  467. return nil, err
  468. }
  469. if !dataset.IsPrivate() {
  470. return dataset, nil
  471. }
  472. if dataset.IsPrivate() && user != nil && user.ID == dataset.UserID {
  473. return dataset, nil
  474. }
  475. return nil, errors.New("dataset not fount")
  476. }
  477. func IncreaseDownloadCount(datasetID int64) error {
  478. // Update download count.
  479. if _, err := x.Exec("UPDATE `dataset` SET download_times=download_times+1 WHERE id=?", datasetID); err != nil {
  480. return fmt.Errorf("increase dataset count: %v", err)
  481. }
  482. return nil
  483. }
  484. func GetCollaboratorDatasetIdsByUserID(userID int64) []int64 {
  485. var datasets []int64
  486. _ = x.Table("dataset").Join("INNER", "collaboration", "dataset.repo_id = collaboration.repo_id and collaboration.mode>0 and collaboration.user_id=?", userID).
  487. Cols("dataset.id").Find(&datasets)
  488. return datasets
  489. }
  490. func GetTeamDatasetIdsByUserID(userID int64) []int64 {
  491. var datasets []int64
  492. _ = x.Table("dataset").Join("INNER", "team_repo", "dataset.repo_id = team_repo.repo_id").
  493. Join("INNER", "team_user", "team_repo.team_id=team_user.team_id and team_user.uid=?", userID).
  494. Cols("dataset.id").Find(&datasets)
  495. return datasets
  496. }