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 22 kB

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
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
5 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
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
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
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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. package repo
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "unicode/utf8"
  10. "code.gitea.io/gitea/services/repository"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. )
  18. const (
  19. tplIndex base.TplName = "repo/datasets/index"
  20. tplDatasetCreate base.TplName = "repo/datasets/create"
  21. tplDatasetEdit base.TplName = "repo/datasets/edit"
  22. taskstplIndex base.TplName = "repo/datasets/tasks/index"
  23. tplReference base.TplName = "repo/datasets/reference"
  24. )
  25. // MustEnableDataset check if repository enable internal dataset
  26. func MustEnableDataset(ctx *context.Context) {
  27. if !ctx.Repo.CanRead(models.UnitTypeDatasets) {
  28. ctx.NotFound("MustEnableDataset", nil)
  29. return
  30. }
  31. }
  32. func newFilterPrivateAttachments(ctx *context.Context, list []*models.Attachment, repo *models.Repository) []*models.Attachment {
  33. if ctx.Repo.CanWrite(models.UnitTypeDatasets) {
  34. log.Info("can write.")
  35. return list
  36. } else {
  37. if repo.Owner == nil {
  38. repo.GetOwner()
  39. }
  40. permission := false
  41. if !permission && ctx.User != nil {
  42. isCollaborator, _ := repo.IsCollaborator(ctx.User.ID)
  43. isInRepoTeam,_:=repo.IsInRepoTeam(ctx.User.ID)
  44. if isCollaborator ||isInRepoTeam {
  45. log.Info("Collaborator user may visit the attach.")
  46. permission = true
  47. }
  48. }
  49. var publicList []*models.Attachment
  50. for _, attach := range list {
  51. if !attach.IsPrivate {
  52. publicList = append(publicList, attach)
  53. } else {
  54. if permission {
  55. publicList = append(publicList, attach)
  56. }
  57. }
  58. }
  59. return publicList
  60. }
  61. }
  62. func QueryDataSet(ctx *context.Context) []*models.Attachment {
  63. repo := ctx.Repo.Repository
  64. dataset, err := models.GetDatasetByRepo(repo)
  65. if err != nil {
  66. log.Error("zou not found dataset 1")
  67. ctx.NotFound("GetDatasetByRepo", err)
  68. return nil
  69. }
  70. if ctx.Query("type") == "" {
  71. log.Error("zou not found type 2")
  72. ctx.NotFound("type error", nil)
  73. return nil
  74. }
  75. err = models.GetDatasetAttachments(ctx.QueryInt("type"), ctx.IsSigned, ctx.User, dataset)
  76. if err != nil {
  77. ctx.ServerError("GetDatasetAttachments", err)
  78. return nil
  79. }
  80. attachments := newFilterPrivateAttachments(ctx, dataset.Attachments, repo)
  81. ctx.Data["SortType"] = ctx.Query("sort")
  82. sort.Slice(attachments, func(i, j int) bool {
  83. return attachments[i].CreatedUnix > attachments[j].CreatedUnix
  84. })
  85. return attachments
  86. }
  87. func DatasetIndex(ctx *context.Context) {
  88. log.Info("dataset index 1")
  89. MustEnableDataset(ctx)
  90. ctx.Data["PageIsDataset"] = true
  91. ctx.Data["SortType"] = ctx.Query("sort")
  92. repo := ctx.Repo.Repository
  93. dataset, err := models.GetDatasetByRepo(repo)
  94. ctx.Data["CanWrite"] = ctx.Repo.CanWrite(models.UnitTypeDatasets)
  95. if err != nil {
  96. log.Warn("query dataset, not found.")
  97. ctx.HTML(200, tplIndex)
  98. return
  99. }
  100. cloudbrainType := -1
  101. if ctx.Query("type") != "" {
  102. cloudbrainType = ctx.QueryInt("type")
  103. }
  104. err = models.GetDatasetAttachments(cloudbrainType, ctx.IsSigned, ctx.User, dataset)
  105. if err != nil {
  106. ctx.ServerError("GetDatasetAttachments", err)
  107. return
  108. }
  109. attachments := newFilterPrivateAttachments(ctx, dataset.Attachments, repo)
  110. if ctx.Data["SortType"] == "nameAsc" {
  111. sort.Slice(attachments, func(i, j int) bool {
  112. return strings.ToLower(attachments[i].Name) < strings.ToLower(attachments[j].Name)
  113. })
  114. } else if ctx.Data["SortType"] == "nameDesc" {
  115. sort.Slice(attachments, func(i, j int) bool {
  116. return strings.ToLower(attachments[i].Name) > strings.ToLower(attachments[j].Name)
  117. })
  118. } else if ctx.Data["SortType"] == "sizeAsc" {
  119. sort.Slice(attachments, func(i, j int) bool {
  120. return attachments[i].Size < attachments[j].Size
  121. })
  122. } else if ctx.Data["SortType"] == "sizeDesc" {
  123. sort.Slice(attachments, func(i, j int) bool {
  124. return attachments[i].Size > attachments[j].Size
  125. })
  126. } else if ctx.Data["SortType"] == "timeAsc" {
  127. sort.Slice(attachments, func(i, j int) bool {
  128. return attachments[i].CreatedUnix < attachments[j].CreatedUnix
  129. })
  130. } else {
  131. sort.Slice(attachments, func(i, j int) bool {
  132. return attachments[i].CreatedUnix > attachments[j].CreatedUnix
  133. })
  134. }
  135. page := ctx.QueryInt("page")
  136. if page <= 0 {
  137. page = 1
  138. }
  139. pagesize := ctx.QueryInt("pagesize")
  140. if pagesize <= 0 {
  141. pagesize = 10
  142. }
  143. pager := context.NewPagination(len(attachments), pagesize, page, 5)
  144. pageAttachments := getPageAttachments(attachments, page, pagesize)
  145. //load attachment creator
  146. for _, attachment := range pageAttachments {
  147. uploader, _ := models.GetUserByID(attachment.UploaderID)
  148. attachment.Uploader = uploader
  149. if !strings.HasSuffix(attachment.Name, ".zip") && !strings.HasSuffix(attachment.Name, ".tar.gz") {
  150. attachment.DecompressState = -1 //非压缩文件
  151. }
  152. }
  153. ctx.Data["Page"] = pager
  154. ctx.Data["Title"] = ctx.Tr("dataset.show_dataset")
  155. ctx.Data["Link"] = ctx.Repo.RepoLink + "/datasets"
  156. ctx.Data["dataset"] = dataset
  157. ctx.Data["Attachments"] = pageAttachments
  158. ctx.Data["IsOwner"] = true
  159. ctx.Data["StoreType"] = setting.Attachment.StoreType
  160. ctx.Data["Type"] = cloudbrainType
  161. renderAttachmentSettings(ctx)
  162. ctx.HTML(200, tplIndex)
  163. }
  164. func getPageAttachments(attachments []*models.Attachment, page int, pagesize int) []*models.Attachment {
  165. begin := (page - 1) * pagesize
  166. end := (page) * pagesize
  167. if begin > len(attachments)-1 {
  168. return nil
  169. }
  170. if end > len(attachments)-1 {
  171. return attachments[begin:]
  172. } else {
  173. return attachments[begin:end]
  174. }
  175. }
  176. func CreateDataset(ctx *context.Context) {
  177. MustEnableDataset(ctx)
  178. ctx.Data["PageIsDataset"] = true
  179. ctx.HTML(200, tplDatasetCreate)
  180. }
  181. func EditDataset(ctx *context.Context) {
  182. MustEnableDataset(ctx)
  183. ctx.Data["PageIsDataset"] = true
  184. datasetId, _ := strconv.ParseInt(ctx.Params(":id"), 10, 64)
  185. dataset, _ := models.GetDatasetByID(datasetId)
  186. if dataset == nil {
  187. ctx.Error(http.StatusNotFound, "")
  188. return
  189. }
  190. ctx.Data["Dataset"] = dataset
  191. ctx.HTML(200, tplDatasetEdit)
  192. }
  193. func CreateDatasetPost(ctx *context.Context, form auth.CreateDatasetForm) {
  194. dataset := &models.Dataset{}
  195. if !NamePattern.MatchString(form.Title) {
  196. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  197. return
  198. }
  199. if utf8.RuneCountInString(form.Description) > 1024 {
  200. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 1024)))
  201. return
  202. }
  203. dataset.RepoID = ctx.Repo.Repository.ID
  204. dataset.UserID = ctx.User.ID
  205. dataset.Category = form.Category
  206. dataset.Task = form.Task
  207. dataset.Title = form.Title
  208. dataset.License = form.License
  209. dataset.Description = form.Description
  210. dataset.DownloadTimes = 0
  211. if ctx.Repo.Repository.IsPrivate {
  212. dataset.Status = 0
  213. } else {
  214. dataset.Status = 1
  215. }
  216. err := models.CreateDataset(dataset)
  217. if err != nil {
  218. log.Error("fail to create dataset", err)
  219. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.create_dataset_fail")))
  220. } else {
  221. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  222. }
  223. }
  224. func ReferenceDatasetDelete(ctx *context.Context) {
  225. repoID := ctx.Repo.Repository.ID
  226. datasetId, _ := strconv.ParseInt(ctx.Params(":id"), 10, 64)
  227. oldDatasetIds := models.GetDatasetIdsByRepoID(repoID)
  228. var newDatasetIds []int64
  229. for _, tempDatasetId := range oldDatasetIds {
  230. if datasetId != tempDatasetId {
  231. newDatasetIds = append(newDatasetIds, tempDatasetId)
  232. }
  233. }
  234. err := models.NewDatasetIdsByRepoID(repoID, newDatasetIds)
  235. if err != nil {
  236. ctx.JSON(http.StatusOK, models.BaseErrorMessage("dataset.cancel_reference_dataset_fail"))
  237. }
  238. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  239. }
  240. func ReferenceDatasetPost(ctx *context.Context, form auth.ReferenceDatasetForm) {
  241. repoID := ctx.Repo.Repository.ID
  242. err := models.NewDatasetIdsByRepoID(repoID, form.DatasetID)
  243. if err != nil {
  244. ctx.JSON(http.StatusOK, models.BaseErrorMessage("dataset.reference_dataset_fail"))
  245. }
  246. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  247. }
  248. func EditDatasetPost(ctx *context.Context, form auth.EditDatasetForm) {
  249. ctx.Data["PageIsDataset"] = true
  250. ctx.Data["Title"] = ctx.Tr("dataset.edit_dataset")
  251. if !NamePattern.MatchString(form.Title) {
  252. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  253. return
  254. }
  255. if utf8.RuneCountInString(form.Description) > 1024 {
  256. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 1024)))
  257. return
  258. }
  259. rel, err := models.GetDatasetByID(form.ID)
  260. ctx.Data["dataset"] = rel
  261. if err != nil {
  262. log.Error("failed to query dataset", err)
  263. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.query_dataset_fail")))
  264. return
  265. }
  266. rel.Title = form.Title
  267. rel.Description = form.Description
  268. rel.Category = form.Category
  269. rel.Task = form.Task
  270. rel.License = form.License
  271. if err = models.UpdateDataset(models.DefaultDBContext(), rel); err != nil {
  272. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.query_dataset_fail")))
  273. }
  274. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  275. }
  276. func DatasetAction(ctx *context.Context) {
  277. var err error
  278. datasetId, _ := strconv.ParseInt(ctx.Params(":id"), 10, 64)
  279. switch ctx.Params(":action") {
  280. case "star":
  281. err = models.StarDataset(ctx.User.ID, datasetId, true)
  282. case "unstar":
  283. err = models.StarDataset(ctx.User.ID, datasetId, false)
  284. }
  285. if err != nil {
  286. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.star_fail", ctx.Params(":action"))))
  287. } else {
  288. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  289. }
  290. }
  291. func CurrentRepoDataset(ctx *context.Context) {
  292. page := ctx.QueryInt("page")
  293. cloudbrainType := ctx.QueryInt("type")
  294. keyword := strings.Trim(ctx.Query("q"), " ")
  295. repo := ctx.Repo.Repository
  296. var datasetIDs []int64
  297. dataset, err := models.GetDatasetByRepo(repo)
  298. if err != nil {
  299. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("GetDatasetByRepo failed", err)))
  300. return
  301. }
  302. datasetIDs = append(datasetIDs, dataset.ID)
  303. datasets, count, err := models.Attachments(&models.AttachmentsOptions{
  304. ListOptions: models.ListOptions{
  305. Page: page,
  306. PageSize: setting.UI.DatasetPagingNum,
  307. },
  308. Keyword: keyword,
  309. NeedDatasetIDs: true,
  310. DatasetIDs: datasetIDs,
  311. Type: cloudbrainType,
  312. NeedIsPrivate: false,
  313. JustNeedZipFile: true,
  314. NeedRepoInfo: true,
  315. })
  316. if err != nil {
  317. ctx.ServerError("datasets", err)
  318. return
  319. }
  320. data, err := json.Marshal(datasets)
  321. if err != nil {
  322. log.Error("json.Marshal failed:", err.Error())
  323. ctx.JSON(200, map[string]string{
  324. "result_code": "-1",
  325. "error_msg": err.Error(),
  326. "data": "",
  327. })
  328. return
  329. }
  330. ctx.JSON(200, map[string]string{
  331. "result_code": "0",
  332. "data": string(data),
  333. "count": strconv.FormatInt(count, 10),
  334. })
  335. }
  336. func MyDatasets(ctx *context.Context) {
  337. page := ctx.QueryInt("page")
  338. cloudbrainType := ctx.QueryInt("type")
  339. keyword := strings.Trim(ctx.Query("q"), " ")
  340. uploaderID := ctx.User.ID
  341. datasets, count, err := models.Attachments(&models.AttachmentsOptions{
  342. ListOptions: models.ListOptions{
  343. Page: page,
  344. PageSize: setting.UI.DatasetPagingNum,
  345. },
  346. Keyword: keyword,
  347. NeedDatasetIDs: false,
  348. UploaderID: uploaderID,
  349. Type: cloudbrainType,
  350. NeedIsPrivate: false,
  351. JustNeedZipFile: true,
  352. NeedRepoInfo: true,
  353. RecommendOnly: ctx.QueryBool("recommend"),
  354. })
  355. if err != nil {
  356. ctx.ServerError("datasets", err)
  357. return
  358. }
  359. data, err := json.Marshal(datasets)
  360. if err != nil {
  361. log.Error("json.Marshal failed:", err.Error())
  362. ctx.JSON(200, map[string]string{
  363. "result_code": "-1",
  364. "error_msg": err.Error(),
  365. "data": "",
  366. })
  367. return
  368. }
  369. ctx.JSON(200, map[string]string{
  370. "result_code": "0",
  371. "data": string(data),
  372. "count": strconv.FormatInt(count, 10),
  373. })
  374. }
  375. func datasetMultiple(ctx *context.Context, opts *models.SearchDatasetOptions) {
  376. page := ctx.QueryInt("page")
  377. keyword := strings.Trim(ctx.Query("q"), " ")
  378. opts.Keyword = keyword
  379. if opts.SearchOrderBy.String() == "" {
  380. opts.SearchOrderBy = models.SearchOrderByRecentUpdated
  381. }
  382. opts.RecommendOnly = ctx.QueryBool("recommend")
  383. opts.ListOptions = models.ListOptions{
  384. Page: page,
  385. PageSize: setting.UI.DatasetPagingNum,
  386. }
  387. opts.JustNeedZipFile = true
  388. opts.User = ctx.User
  389. datasets, count, err := models.SearchDataset(opts)
  390. if err != nil {
  391. ctx.ServerError("datasets", err)
  392. return
  393. }
  394. data, err := json.Marshal(datasets)
  395. if err != nil {
  396. log.Error("json.Marshal failed:", err.Error())
  397. ctx.JSON(200, map[string]string{
  398. "result_code": "-1",
  399. "error_msg": err.Error(),
  400. "data": "",
  401. })
  402. return
  403. }
  404. ctx.JSON(200, map[string]string{
  405. "result_code": "0",
  406. "data": string(data),
  407. "count": strconv.FormatInt(count, 10),
  408. })
  409. }
  410. func CurrentRepoDatasetMultiple(ctx *context.Context) {
  411. datasetIds := models.GetDatasetIdsByRepoID(ctx.Repo.Repository.ID)
  412. searchOrderBy := getSearchOrderByInValues(datasetIds)
  413. opts := &models.SearchDatasetOptions{
  414. RepoID: ctx.Repo.Repository.ID,
  415. NeedAttachment: true,
  416. CloudBrainType: ctx.QueryInt("type"),
  417. DatasetIDs: datasetIds,
  418. SearchOrderBy: searchOrderBy,
  419. }
  420. datasetMultiple(ctx, opts)
  421. }
  422. func getSearchOrderByInValues(datasetIds []int64) models.SearchOrderBy {
  423. if len(datasetIds) == 0 {
  424. return ""
  425. }
  426. searchOrderBy := "CASE id "
  427. for i, id := range datasetIds {
  428. searchOrderBy += fmt.Sprintf(" WHEN %d THEN %d", id, i+1)
  429. }
  430. searchOrderBy += " ELSE 0 END"
  431. return models.SearchOrderBy(searchOrderBy)
  432. }
  433. func MyDatasetsMultiple(ctx *context.Context) {
  434. opts := &models.SearchDatasetOptions{
  435. UploadAttachmentByMe: true,
  436. NeedAttachment: true,
  437. CloudBrainType: ctx.QueryInt("type"),
  438. }
  439. datasetMultiple(ctx, opts)
  440. }
  441. func ReferenceDatasetAvailable(ctx *context.Context) {
  442. opts := &models.SearchDatasetOptions{
  443. PublicOnly: true,
  444. NeedAttachment: false,
  445. CloudBrainType: models.TypeCloudBrainAll,
  446. }
  447. dataset, _ := models.GetDatasetByRepo(&models.Repository{ID: ctx.Repo.Repository.ID})
  448. if dataset != nil {
  449. opts.ExcludeDatasetId = dataset.ID
  450. }
  451. datasetMultiple(ctx, opts)
  452. }
  453. func PublicDatasetMultiple(ctx *context.Context) {
  454. opts := &models.SearchDatasetOptions{
  455. PublicOnly: true,
  456. NeedAttachment: true,
  457. CloudBrainType: ctx.QueryInt("type"),
  458. }
  459. datasetMultiple(ctx, opts)
  460. }
  461. func MyFavoriteDatasetMultiple(ctx *context.Context) {
  462. opts := &models.SearchDatasetOptions{
  463. StarByMe: true,
  464. DatasetIDs: models.GetDatasetIdsStarByUser(ctx.User.ID),
  465. NeedAttachment: true,
  466. CloudBrainType: ctx.QueryInt("type"),
  467. }
  468. datasetMultiple(ctx, opts)
  469. }
  470. func ReferenceDataset(ctx *context.Context) {
  471. MustEnableDataset(ctx)
  472. ctx.Data["PageIsDataset"] = true
  473. ctx.Data["MaxReferenceDatasetNum"] = setting.RepoMaxReferenceDatasetNum
  474. ctx.Data["CanWrite"] = ctx.Repo.CanWrite(models.UnitTypeDatasets)
  475. ctx.HTML(200, tplReference)
  476. }
  477. func ReferenceDatasetData(ctx *context.Context) {
  478. MustEnableDataset(ctx)
  479. datasetIds := models.GetDatasetIdsByRepoID(ctx.Repo.Repository.ID)
  480. var datasets models.DatasetList
  481. var err error
  482. if len(datasetIds) > 0 {
  483. opts := &models.SearchDatasetOptions{
  484. DatasetIDs: datasetIds,
  485. NeedAttachment: false,
  486. CloudBrainType: models.TypeCloudBrainAll,
  487. ListOptions: models.ListOptions{
  488. Page: 1,
  489. PageSize: setting.RepoMaxReferenceDatasetNum,
  490. },
  491. SearchOrderBy: getSearchOrderByInValues(datasetIds),
  492. QueryReference: true,
  493. }
  494. datasets, _, err = models.SearchDataset(opts)
  495. if err != nil {
  496. ctx.ServerError("SearchDatasets", err)
  497. return
  498. }
  499. }
  500. ctx.JSON(http.StatusOK, repository.ConvertToDatasetWithStar(ctx, datasets))
  501. }
  502. func PublicDataset(ctx *context.Context) {
  503. page := ctx.QueryInt("page")
  504. cloudbrainType := ctx.QueryInt("type")
  505. keyword := strings.Trim(ctx.Query("q"), " ")
  506. datasets, count, err := models.Attachments(&models.AttachmentsOptions{
  507. ListOptions: models.ListOptions{
  508. Page: page,
  509. PageSize: setting.UI.DatasetPagingNum,
  510. },
  511. Keyword: keyword,
  512. NeedDatasetIDs: false,
  513. NeedIsPrivate: true,
  514. IsPrivate: false,
  515. Type: cloudbrainType,
  516. JustNeedZipFile: true,
  517. NeedRepoInfo: true,
  518. RecommendOnly: ctx.QueryBool("recommend"),
  519. })
  520. if err != nil {
  521. ctx.ServerError("datasets", err)
  522. return
  523. }
  524. data, err := json.Marshal(datasets)
  525. if err != nil {
  526. log.Error("json.Marshal failed:", err.Error())
  527. ctx.JSON(200, map[string]string{
  528. "result_code": "-1",
  529. "error_msg": err.Error(),
  530. "data": "",
  531. })
  532. return
  533. }
  534. ctx.JSON(200, map[string]string{
  535. "result_code": "0",
  536. "data": string(data),
  537. "count": strconv.FormatInt(count, 10),
  538. })
  539. }
  540. func MyFavoriteDataset(ctx *context.Context) {
  541. UserId := ctx.User.ID
  542. cloudbrainType := ctx.QueryInt("type")
  543. keyword := strings.Trim(ctx.Query("q"), " ")
  544. var NotColDatasetIDs []int64
  545. var IsColDatasetIDs []int64
  546. datasetStars, err := models.GetDatasetStarByUser(ctx.User)
  547. if err != nil {
  548. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("GetDatasetStarByUser failed", err)))
  549. log.Error("GetDatasetStarByUser failed:", err.Error())
  550. ctx.JSON(200, map[string]string{
  551. "result_code": "-1",
  552. "error_msg": err.Error(),
  553. "data": "",
  554. })
  555. return
  556. }
  557. //If the dataset has been deleted, it will not be counted
  558. for _, datasetStar := range datasetStars {
  559. IsExist, repo, dataset, err := IsDatasetStarExist(datasetStar)
  560. if err != nil {
  561. log.Error("IsDatasetStarExist error:", err.Error())
  562. }
  563. if IsExist {
  564. DatasetIsCollaborator := DatasetIsCollaborator(ctx, dataset)
  565. if repo.OwnerID == ctx.User.ID || DatasetIsCollaborator {
  566. IsColDatasetIDs = append(IsColDatasetIDs, datasetStar.DatasetID)
  567. } else {
  568. NotColDatasetIDs = append(NotColDatasetIDs, datasetStar.DatasetID)
  569. }
  570. }
  571. }
  572. NotColDatasets, NotColcount, err := models.Attachments(&models.AttachmentsOptions{
  573. Keyword: keyword,
  574. NeedDatasetIDs: true,
  575. DatasetIDs: NotColDatasetIDs,
  576. NeedIsPrivate: true,
  577. IsPrivate: false,
  578. Type: cloudbrainType,
  579. JustNeedZipFile: true,
  580. NeedRepoInfo: true,
  581. RecommendOnly: ctx.QueryBool("recommend"),
  582. UserId: UserId,
  583. })
  584. if err != nil {
  585. ctx.ServerError("datasets", err)
  586. return
  587. }
  588. //If is collaborator, there is no need to determine whether the dataset is private or public
  589. IsColDatasets, IsColcount, err := models.Attachments(&models.AttachmentsOptions{
  590. Keyword: keyword,
  591. NeedDatasetIDs: true,
  592. DatasetIDs: IsColDatasetIDs,
  593. NeedIsPrivate: false,
  594. Type: cloudbrainType,
  595. JustNeedZipFile: true,
  596. NeedRepoInfo: true,
  597. RecommendOnly: ctx.QueryBool("recommend"),
  598. UserId: UserId,
  599. })
  600. if err != nil {
  601. ctx.ServerError("datasets", err)
  602. return
  603. }
  604. for _, NotColDataset := range NotColDatasets {
  605. IsColDatasets = append(IsColDatasets, NotColDataset)
  606. }
  607. datasets := IsColDatasets
  608. count := NotColcount + IsColcount
  609. sort.Slice(datasets, func(i, j int) bool {
  610. return datasets[i].Attachment.CreatedUnix > datasets[j].Attachment.CreatedUnix
  611. })
  612. page := ctx.QueryInt("page")
  613. if page <= 0 {
  614. page = 1
  615. }
  616. pagesize := ctx.QueryInt("pagesize")
  617. if pagesize <= 0 {
  618. pagesize = 5
  619. }
  620. pageDatasetsInfo := getPageDatasets(datasets, page, pagesize)
  621. if pageDatasetsInfo == nil {
  622. ctx.JSON(200, map[string]string{
  623. "result_code": "0",
  624. "data": "[]",
  625. "count": strconv.FormatInt(count, 10),
  626. })
  627. return
  628. }
  629. data, err := json.Marshal(pageDatasetsInfo)
  630. log.Info("data:", data)
  631. if err != nil {
  632. log.Error("json.Marshal failed:", err.Error())
  633. ctx.JSON(200, map[string]string{
  634. "result_code": "-1",
  635. "error_msg": err.Error(),
  636. "data": "",
  637. })
  638. return
  639. }
  640. ctx.JSON(200, map[string]string{
  641. "result_code": "0",
  642. "data": string(data),
  643. "count": strconv.FormatInt(count, 10),
  644. })
  645. }
  646. func getPageDatasets(AttachmentInfos []*models.AttachmentInfo, page int, pagesize int) []*models.AttachmentInfo {
  647. begin := (page - 1) * pagesize
  648. end := (page) * pagesize
  649. if begin > len(AttachmentInfos)-1 {
  650. return nil
  651. }
  652. if end > len(AttachmentInfos)-1 {
  653. return AttachmentInfos[begin:]
  654. } else {
  655. return AttachmentInfos[begin:end]
  656. }
  657. }
  658. func getTotalPage(total int64, pageSize int) int {
  659. another := 0
  660. if int(total)%pageSize != 0 {
  661. another = 1
  662. }
  663. return int(total)/pageSize + another
  664. }
  665. func GetDatasetStatus(ctx *context.Context) {
  666. var (
  667. err error
  668. )
  669. UUID := ctx.Params(":uuid")
  670. attachment, err := models.GetAttachmentByUUID(UUID)
  671. if err != nil {
  672. log.Error("GetDatasetStarByUser failed:", err.Error())
  673. ctx.JSON(200, map[string]string{
  674. "result_code": "-1",
  675. "error_msg": err.Error(),
  676. "data": "",
  677. })
  678. return
  679. }
  680. ctx.JSON(200, map[string]string{
  681. "result_code": "0",
  682. "UUID": UUID,
  683. "AttachmentStatus": fmt.Sprint(attachment.DecompressState),
  684. })
  685. }
  686. func DatasetIsCollaborator(ctx *context.Context, dataset *models.Dataset) bool {
  687. repo, err := models.GetRepositoryByID(dataset.RepoID)
  688. if err != nil {
  689. log.Error("query repo error:", err.Error())
  690. } else {
  691. repo.GetOwner()
  692. if ctx.User != nil {
  693. if repo.Owner.IsOrganization() {
  694. org := repo.Owner
  695. org.Teams, err = org.GetUserTeams(ctx.User.ID)
  696. if err != nil {
  697. log.Error("GetUserTeams error:", err.Error())
  698. return false
  699. }
  700. if org.IsUserPartOfOrg(ctx.User.ID) {
  701. for _, t := range org.Teams {
  702. if t.IsMember(ctx.User.ID) && t.HasRepository(repo.ID) {
  703. return true
  704. }
  705. }
  706. isOwner, _ := models.IsOrganizationOwner(repo.OwnerID, ctx.User.ID)
  707. if isOwner {
  708. return isOwner
  709. }
  710. return false
  711. }
  712. }
  713. isCollaborator, _ := repo.IsCollaborator(ctx.User.ID)
  714. if isCollaborator {
  715. return true
  716. }
  717. }
  718. }
  719. return false
  720. }
  721. func IsDatasetStarExist(datasetStar *models.DatasetStar) (bool, *models.Repository, *models.Dataset, error) {
  722. dataset, err := models.GetDatasetByID(datasetStar.DatasetID)
  723. if err != nil {
  724. log.Error("query dataset error:", err.Error())
  725. return false, nil, nil, err
  726. } else {
  727. repo, err := models.GetRepositoryByID(dataset.RepoID)
  728. if err != nil {
  729. log.Error("GetRepositoryByID error:", err.Error())
  730. return false, nil, nil, err
  731. }
  732. return true, repo, dataset, nil
  733. }
  734. }