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