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 14 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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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 datasetMultiple(ctx *context.Context, opts *models.SearchDatasetOptions) {
  292. page := ctx.QueryInt("page")
  293. keyword := strings.Trim(ctx.Query("q"), " ")
  294. opts.Keyword = keyword
  295. if opts.SearchOrderBy.String() == "" {
  296. opts.SearchOrderBy = models.SearchOrderByRecentUpdated
  297. }
  298. opts.RecommendOnly = ctx.QueryBool("recommend")
  299. opts.ListOptions = models.ListOptions{
  300. Page: page,
  301. PageSize: setting.UI.DatasetPagingNum,
  302. }
  303. opts.JustNeedZipFile = true
  304. opts.User = ctx.User
  305. datasets, count, err := models.SearchDataset(opts)
  306. if err != nil {
  307. ctx.ServerError("datasets", err)
  308. return
  309. }
  310. data, err := json.Marshal(datasets)
  311. log.Info("datakey", string(data))
  312. if err != nil {
  313. log.Error("json.Marshal failed:", err.Error())
  314. ctx.JSON(200, map[string]string{
  315. "result_code": "-1",
  316. "error_msg": err.Error(),
  317. "data": "",
  318. })
  319. return
  320. }
  321. ctx.JSON(200, map[string]string{
  322. "result_code": "0",
  323. "data": string(data),
  324. "count": strconv.FormatInt(count, 10),
  325. })
  326. }
  327. func CurrentRepoDatasetMultiple(ctx *context.Context) {
  328. datasetIds := models.GetDatasetIdsByRepoID(ctx.Repo.Repository.ID)
  329. searchOrderBy := getSearchOrderByInValues(datasetIds)
  330. opts := &models.SearchDatasetOptions{
  331. RepoID: ctx.Repo.Repository.ID,
  332. NeedAttachment: true,
  333. CloudBrainType: ctx.QueryInt("type"),
  334. DatasetIDs: datasetIds,
  335. SearchOrderBy: searchOrderBy,
  336. }
  337. datasetMultiple(ctx, opts)
  338. }
  339. func getSearchOrderByInValues(datasetIds []int64) models.SearchOrderBy {
  340. if len(datasetIds) == 0 {
  341. return ""
  342. }
  343. searchOrderBy := "CASE id "
  344. for i, id := range datasetIds {
  345. searchOrderBy += fmt.Sprintf(" WHEN %d THEN %d", id, i+1)
  346. }
  347. searchOrderBy += " ELSE 0 END"
  348. return models.SearchOrderBy(searchOrderBy)
  349. }
  350. func MyDatasetsMultiple(ctx *context.Context) {
  351. opts := &models.SearchDatasetOptions{
  352. UploadAttachmentByMe: true,
  353. NeedAttachment: true,
  354. CloudBrainType: ctx.QueryInt("type"),
  355. }
  356. datasetMultiple(ctx, opts)
  357. }
  358. func ReferenceDatasetAvailable(ctx *context.Context) {
  359. opts := &models.SearchDatasetOptions{
  360. PublicOnly: true,
  361. NeedAttachment: false,
  362. CloudBrainType: models.TypeCloudBrainAll,
  363. SearchOrderBy: models.SearchOrderByDefault,
  364. }
  365. dataset, _ := models.GetDatasetByRepo(&models.Repository{ID: ctx.Repo.Repository.ID})
  366. if dataset != nil {
  367. opts.ExcludeDatasetId = dataset.ID
  368. }
  369. datasetMultiple(ctx, opts)
  370. }
  371. func PublicDatasetMultiple(ctx *context.Context) {
  372. opts := &models.SearchDatasetOptions{
  373. PublicOnly: true,
  374. NeedAttachment: true,
  375. CloudBrainType: ctx.QueryInt("type"),
  376. SearchOrderBy: models.SearchOrderByDefault,
  377. }
  378. datasetMultiple(ctx, opts)
  379. }
  380. func MyFavoriteDatasetMultiple(ctx *context.Context) {
  381. opts := &models.SearchDatasetOptions{
  382. StarByMe: true,
  383. DatasetIDs: models.GetDatasetIdsStarByUser(ctx.User.ID),
  384. NeedAttachment: true,
  385. CloudBrainType: ctx.QueryInt("type"),
  386. }
  387. datasetMultiple(ctx, opts)
  388. }
  389. func ReferenceDataset(ctx *context.Context) {
  390. MustEnableDataset(ctx)
  391. ctx.Data["PageIsDataset"] = true
  392. ctx.Data["MaxReferenceDatasetNum"] = setting.RepoMaxReferenceDatasetNum
  393. ctx.Data["CanWrite"] = ctx.Repo.CanWrite(models.UnitTypeDatasets)
  394. ctx.HTML(200, tplReference)
  395. }
  396. func ReferenceDatasetData(ctx *context.Context) {
  397. MustEnableDataset(ctx)
  398. datasetIds := models.GetDatasetIdsByRepoID(ctx.Repo.Repository.ID)
  399. var datasets models.DatasetList
  400. var err error
  401. if len(datasetIds) > 0 {
  402. opts := &models.SearchDatasetOptions{
  403. DatasetIDs: datasetIds,
  404. NeedAttachment: false,
  405. CloudBrainType: models.TypeCloudBrainAll,
  406. ListOptions: models.ListOptions{
  407. Page: 1,
  408. PageSize: setting.RepoMaxReferenceDatasetNum,
  409. },
  410. SearchOrderBy: getSearchOrderByInValues(datasetIds),
  411. QueryReference: true,
  412. }
  413. datasets, _, err = models.SearchDataset(opts)
  414. if err != nil {
  415. ctx.ServerError("SearchDatasets", err)
  416. return
  417. }
  418. }
  419. ctx.JSON(http.StatusOK, repository.ConvertToDatasetWithStar(ctx, datasets))
  420. }
  421. func GetDatasetStatus(ctx *context.Context) {
  422. var (
  423. err error
  424. )
  425. UUID := ctx.Params(":uuid")
  426. attachment, err := models.GetAttachmentByUUID(UUID)
  427. if err != nil {
  428. log.Error("GetDatasetStarByUser failed:", err.Error())
  429. ctx.JSON(200, map[string]string{
  430. "result_code": "-1",
  431. "error_msg": err.Error(),
  432. "data": "",
  433. })
  434. return
  435. }
  436. ctx.JSON(200, map[string]string{
  437. "result_code": "0",
  438. "UUID": UUID,
  439. "AttachmentStatus": fmt.Sprint(attachment.DecompressState),
  440. })
  441. }