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
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 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
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 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
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. SearchOrderBy: models.SearchOrderByDefault,
  447. }
  448. dataset, _ := models.GetDatasetByRepo(&models.Repository{ID: ctx.Repo.Repository.ID})
  449. if dataset != nil {
  450. opts.ExcludeDatasetId = dataset.ID
  451. }
  452. datasetMultiple(ctx, opts)
  453. }
  454. func PublicDatasetMultiple(ctx *context.Context) {
  455. opts := &models.SearchDatasetOptions{
  456. PublicOnly: true,
  457. NeedAttachment: true,
  458. CloudBrainType: ctx.QueryInt("type"),
  459. SearchOrderBy: models.SearchOrderByDefault,
  460. }
  461. datasetMultiple(ctx, opts)
  462. }
  463. func MyFavoriteDatasetMultiple(ctx *context.Context) {
  464. opts := &models.SearchDatasetOptions{
  465. StarByMe: true,
  466. DatasetIDs: models.GetDatasetIdsStarByUser(ctx.User.ID),
  467. NeedAttachment: true,
  468. CloudBrainType: ctx.QueryInt("type"),
  469. }
  470. datasetMultiple(ctx, opts)
  471. }
  472. func ReferenceDataset(ctx *context.Context) {
  473. MustEnableDataset(ctx)
  474. ctx.Data["PageIsDataset"] = true
  475. ctx.Data["MaxReferenceDatasetNum"] = setting.RepoMaxReferenceDatasetNum
  476. ctx.Data["CanWrite"] = ctx.Repo.CanWrite(models.UnitTypeDatasets)
  477. ctx.HTML(200, tplReference)
  478. }
  479. func ReferenceDatasetData(ctx *context.Context) {
  480. MustEnableDataset(ctx)
  481. datasetIds := models.GetDatasetIdsByRepoID(ctx.Repo.Repository.ID)
  482. var datasets models.DatasetList
  483. var err error
  484. if len(datasetIds) > 0 {
  485. opts := &models.SearchDatasetOptions{
  486. DatasetIDs: datasetIds,
  487. NeedAttachment: false,
  488. CloudBrainType: models.TypeCloudBrainAll,
  489. ListOptions: models.ListOptions{
  490. Page: 1,
  491. PageSize: setting.RepoMaxReferenceDatasetNum,
  492. },
  493. SearchOrderBy: getSearchOrderByInValues(datasetIds),
  494. QueryReference: true,
  495. }
  496. datasets, _, err = models.SearchDataset(opts)
  497. if err != nil {
  498. ctx.ServerError("SearchDatasets", err)
  499. return
  500. }
  501. }
  502. ctx.JSON(http.StatusOK, repository.ConvertToDatasetWithStar(ctx, datasets))
  503. }
  504. func PublicDataset(ctx *context.Context) {
  505. page := ctx.QueryInt("page")
  506. cloudbrainType := ctx.QueryInt("type")
  507. keyword := strings.Trim(ctx.Query("q"), " ")
  508. datasets, count, err := models.Attachments(&models.AttachmentsOptions{
  509. ListOptions: models.ListOptions{
  510. Page: page,
  511. PageSize: setting.UI.DatasetPagingNum,
  512. },
  513. Keyword: keyword,
  514. NeedDatasetIDs: false,
  515. NeedIsPrivate: true,
  516. IsPrivate: false,
  517. Type: cloudbrainType,
  518. JustNeedZipFile: true,
  519. NeedRepoInfo: true,
  520. RecommendOnly: ctx.QueryBool("recommend"),
  521. })
  522. if err != nil {
  523. ctx.ServerError("datasets", err)
  524. return
  525. }
  526. data, err := json.Marshal(datasets)
  527. if err != nil {
  528. log.Error("json.Marshal failed:", err.Error())
  529. ctx.JSON(200, map[string]string{
  530. "result_code": "-1",
  531. "error_msg": err.Error(),
  532. "data": "",
  533. })
  534. return
  535. }
  536. ctx.JSON(200, map[string]string{
  537. "result_code": "0",
  538. "data": string(data),
  539. "count": strconv.FormatInt(count, 10),
  540. })
  541. }
  542. func MyFavoriteDataset(ctx *context.Context) {
  543. UserId := ctx.User.ID
  544. cloudbrainType := ctx.QueryInt("type")
  545. keyword := strings.Trim(ctx.Query("q"), " ")
  546. var NotColDatasetIDs []int64
  547. var IsColDatasetIDs []int64
  548. datasetStars, err := models.GetDatasetStarByUser(ctx.User)
  549. if err != nil {
  550. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("GetDatasetStarByUser failed", err)))
  551. log.Error("GetDatasetStarByUser failed:", err.Error())
  552. ctx.JSON(200, map[string]string{
  553. "result_code": "-1",
  554. "error_msg": err.Error(),
  555. "data": "",
  556. })
  557. return
  558. }
  559. //If the dataset has been deleted, it will not be counted
  560. for _, datasetStar := range datasetStars {
  561. IsExist, repo, dataset, err := IsDatasetStarExist(datasetStar)
  562. if err != nil {
  563. log.Error("IsDatasetStarExist error:", err.Error())
  564. }
  565. if IsExist {
  566. DatasetIsCollaborator := DatasetIsCollaborator(ctx, dataset)
  567. if repo.OwnerID == ctx.User.ID || DatasetIsCollaborator {
  568. IsColDatasetIDs = append(IsColDatasetIDs, datasetStar.DatasetID)
  569. } else {
  570. NotColDatasetIDs = append(NotColDatasetIDs, datasetStar.DatasetID)
  571. }
  572. }
  573. }
  574. NotColDatasets, NotColcount, err := models.Attachments(&models.AttachmentsOptions{
  575. Keyword: keyword,
  576. NeedDatasetIDs: true,
  577. DatasetIDs: NotColDatasetIDs,
  578. NeedIsPrivate: true,
  579. IsPrivate: false,
  580. Type: cloudbrainType,
  581. JustNeedZipFile: true,
  582. NeedRepoInfo: true,
  583. RecommendOnly: ctx.QueryBool("recommend"),
  584. UserId: UserId,
  585. })
  586. if err != nil {
  587. ctx.ServerError("datasets", err)
  588. return
  589. }
  590. //If is collaborator, there is no need to determine whether the dataset is private or public
  591. IsColDatasets, IsColcount, err := models.Attachments(&models.AttachmentsOptions{
  592. Keyword: keyword,
  593. NeedDatasetIDs: true,
  594. DatasetIDs: IsColDatasetIDs,
  595. NeedIsPrivate: false,
  596. Type: cloudbrainType,
  597. JustNeedZipFile: true,
  598. NeedRepoInfo: true,
  599. RecommendOnly: ctx.QueryBool("recommend"),
  600. UserId: UserId,
  601. })
  602. if err != nil {
  603. ctx.ServerError("datasets", err)
  604. return
  605. }
  606. for _, NotColDataset := range NotColDatasets {
  607. IsColDatasets = append(IsColDatasets, NotColDataset)
  608. }
  609. datasets := IsColDatasets
  610. count := NotColcount + IsColcount
  611. sort.Slice(datasets, func(i, j int) bool {
  612. return datasets[i].Attachment.CreatedUnix > datasets[j].Attachment.CreatedUnix
  613. })
  614. page := ctx.QueryInt("page")
  615. if page <= 0 {
  616. page = 1
  617. }
  618. pagesize := ctx.QueryInt("pagesize")
  619. if pagesize <= 0 {
  620. pagesize = 5
  621. }
  622. pageDatasetsInfo := getPageDatasets(datasets, page, pagesize)
  623. if pageDatasetsInfo == nil {
  624. ctx.JSON(200, map[string]string{
  625. "result_code": "0",
  626. "data": "[]",
  627. "count": strconv.FormatInt(count, 10),
  628. })
  629. return
  630. }
  631. data, err := json.Marshal(pageDatasetsInfo)
  632. log.Info("data:", data)
  633. if err != nil {
  634. log.Error("json.Marshal failed:", err.Error())
  635. ctx.JSON(200, map[string]string{
  636. "result_code": "-1",
  637. "error_msg": err.Error(),
  638. "data": "",
  639. })
  640. return
  641. }
  642. ctx.JSON(200, map[string]string{
  643. "result_code": "0",
  644. "data": string(data),
  645. "count": strconv.FormatInt(count, 10),
  646. })
  647. }
  648. func getPageDatasets(AttachmentInfos []*models.AttachmentInfo, page int, pagesize int) []*models.AttachmentInfo {
  649. begin := (page - 1) * pagesize
  650. end := (page) * pagesize
  651. if begin > len(AttachmentInfos)-1 {
  652. return nil
  653. }
  654. if end > len(AttachmentInfos)-1 {
  655. return AttachmentInfos[begin:]
  656. } else {
  657. return AttachmentInfos[begin:end]
  658. }
  659. }
  660. func getTotalPage(total int64, pageSize int) int {
  661. another := 0
  662. if int(total)%pageSize != 0 {
  663. another = 1
  664. }
  665. return int(total)/pageSize + another
  666. }
  667. func GetDatasetStatus(ctx *context.Context) {
  668. var (
  669. err error
  670. )
  671. UUID := ctx.Params(":uuid")
  672. attachment, err := models.GetAttachmentByUUID(UUID)
  673. if err != nil {
  674. log.Error("GetDatasetStarByUser failed:", err.Error())
  675. ctx.JSON(200, map[string]string{
  676. "result_code": "-1",
  677. "error_msg": err.Error(),
  678. "data": "",
  679. })
  680. return
  681. }
  682. ctx.JSON(200, map[string]string{
  683. "result_code": "0",
  684. "UUID": UUID,
  685. "AttachmentStatus": fmt.Sprint(attachment.DecompressState),
  686. })
  687. }
  688. func DatasetIsCollaborator(ctx *context.Context, dataset *models.Dataset) bool {
  689. repo, err := models.GetRepositoryByID(dataset.RepoID)
  690. if err != nil {
  691. log.Error("query repo error:", err.Error())
  692. } else {
  693. repo.GetOwner()
  694. if ctx.User != nil {
  695. if repo.Owner.IsOrganization() {
  696. org := repo.Owner
  697. org.Teams, err = org.GetUserTeams(ctx.User.ID)
  698. if err != nil {
  699. log.Error("GetUserTeams error:", err.Error())
  700. return false
  701. }
  702. if org.IsUserPartOfOrg(ctx.User.ID) {
  703. for _, t := range org.Teams {
  704. if t.IsMember(ctx.User.ID) && t.HasRepository(repo.ID) {
  705. return true
  706. }
  707. }
  708. isOwner, _ := models.IsOrganizationOwner(repo.OwnerID, ctx.User.ID)
  709. if isOwner {
  710. return isOwner
  711. }
  712. return false
  713. }
  714. }
  715. isCollaborator, _ := repo.IsCollaborator(ctx.User.ID)
  716. if isCollaborator {
  717. return true
  718. }
  719. }
  720. }
  721. return false
  722. }
  723. func IsDatasetStarExist(datasetStar *models.DatasetStar) (bool, *models.Repository, *models.Dataset, error) {
  724. dataset, err := models.GetDatasetByID(datasetStar.DatasetID)
  725. if err != nil {
  726. log.Error("query dataset error:", err.Error())
  727. return false, nil, nil, err
  728. } else {
  729. repo, err := models.GetRepositoryByID(dataset.RepoID)
  730. if err != nil {
  731. log.Error("GetRepositoryByID error:", err.Error())
  732. return false, nil, nil, err
  733. }
  734. return true, repo, dataset, nil
  735. }
  736. }