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