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.

attachment.go 25 kB

4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. contexExt "context"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "mime/multipart"
  11. "net/http"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/context"
  17. "code.gitea.io/gitea/modules/labelmsg"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/minio_ext"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/storage"
  22. "code.gitea.io/gitea/modules/upload"
  23. "code.gitea.io/gitea/modules/worker"
  24. gouuid "github.com/satori/go.uuid"
  25. )
  26. const (
  27. //result of decompress
  28. DecompressSuccess = "0"
  29. DecompressFailed = "1"
  30. )
  31. type CloudBrainDataset struct {
  32. UUID string `json:"id"`
  33. Name string `json:"name"`
  34. Path string `json:"place"`
  35. UserName string `json:"provider"`
  36. CreateTime string `json:"created_at"`
  37. }
  38. type UploadForm struct {
  39. UploadID string `form:"uploadId"`
  40. UuID string `form:"uuid"`
  41. PartSize int64 `form:"size"`
  42. Offset int64 `form:"offset"`
  43. PartNumber int `form:"chunkNumber"`
  44. PartFile multipart.File `form:"file"`
  45. }
  46. func RenderAttachmentSettings(ctx *context.Context) {
  47. renderAttachmentSettings(ctx)
  48. }
  49. func renderAttachmentSettings(ctx *context.Context) {
  50. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  51. ctx.Data["AttachmentStoreType"] = setting.Attachment.StoreType
  52. ctx.Data["AttachmentAllowedTypes"] = setting.Attachment.AllowedTypes
  53. ctx.Data["AttachmentMaxSize"] = setting.Attachment.MaxSize
  54. ctx.Data["AttachmentMaxFiles"] = setting.Attachment.MaxFiles
  55. }
  56. // UploadAttachment response for uploading issue's attachment
  57. func UploadAttachment(ctx *context.Context) {
  58. if !setting.Attachment.Enabled {
  59. ctx.Error(404, "attachment is not enabled")
  60. return
  61. }
  62. file, header, err := ctx.Req.FormFile("file")
  63. if err != nil {
  64. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  65. return
  66. }
  67. defer file.Close()
  68. buf := make([]byte, 1024)
  69. n, _ := file.Read(buf)
  70. if n > 0 {
  71. buf = buf[:n]
  72. }
  73. err = upload.VerifyAllowedContentType(buf, strings.Split(setting.Attachment.AllowedTypes, ","))
  74. if err != nil {
  75. ctx.Error(400, err.Error())
  76. return
  77. }
  78. datasetID, _ := strconv.ParseInt(ctx.Req.FormValue("dataset_id"), 10, 64)
  79. attach, err := models.NewAttachment(&models.Attachment{
  80. IsPrivate: true,
  81. UploaderID: ctx.User.ID,
  82. Name: header.Filename,
  83. DatasetID: datasetID,
  84. }, buf, file)
  85. if err != nil {
  86. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  87. return
  88. }
  89. log.Trace("New attachment uploaded: %s", attach.UUID)
  90. ctx.JSON(200, map[string]string{
  91. "uuid": attach.UUID,
  92. })
  93. }
  94. func UpdatePublicAttachment(ctx *context.Context) {
  95. file := ctx.Query("file")
  96. isPrivate, _ := strconv.ParseBool(ctx.Query("is_private"))
  97. attach, err := models.GetAttachmentByUUID(file)
  98. if err != nil {
  99. ctx.Error(404, err.Error())
  100. return
  101. }
  102. attach.IsPrivate = isPrivate
  103. models.UpdateAttachment(attach)
  104. }
  105. // DeleteAttachment response for deleting issue's attachment
  106. func DeleteAttachment(ctx *context.Context) {
  107. file := ctx.Query("file")
  108. attach, err := models.GetAttachmentByUUID(file)
  109. if err != nil {
  110. ctx.Error(400, err.Error())
  111. return
  112. }
  113. //issue 214: mod del-dataset permission
  114. if !models.CanDelAttachment(ctx.IsSigned, ctx.User, attach) {
  115. ctx.Error(403)
  116. return
  117. }
  118. err = models.DeleteAttachment(attach, true)
  119. if err != nil {
  120. ctx.Error(500, fmt.Sprintf("DeleteAttachment: %v", err))
  121. return
  122. }
  123. attachjson, _ := json.Marshal(attach)
  124. labelmsg.SendDeleteAttachToLabelSys(string(attachjson))
  125. DeleteAllUnzipFile(attach, "")
  126. _, err = models.DeleteFileChunkById(attach.UUID)
  127. if err != nil {
  128. ctx.Error(500, fmt.Sprintf("DeleteFileChunkById: %v", err))
  129. return
  130. }
  131. ctx.JSON(200, map[string]string{
  132. "uuid": attach.UUID,
  133. })
  134. }
  135. func DownloadUserIsOrgOrCollaboration(ctx *context.Context, attach *models.Attachment) bool {
  136. dataset, err := models.GetDatasetByID(attach.DatasetID)
  137. if err != nil {
  138. log.Info("query dataset error")
  139. } else {
  140. repo, err := models.GetRepositoryByID(dataset.RepoID)
  141. if err != nil {
  142. log.Info("query repo error.")
  143. } else {
  144. repo.GetOwner()
  145. if ctx.User != nil {
  146. if repo.Owner.IsOrganization() {
  147. if repo.Owner.IsUserPartOfOrg(ctx.User.ID) {
  148. log.Info("org user may visit the attach.")
  149. return true
  150. }
  151. }
  152. isCollaborator, _ := repo.IsCollaborator(ctx.User.ID)
  153. if isCollaborator {
  154. log.Info("Collaborator user may visit the attach.")
  155. return true
  156. }
  157. }
  158. }
  159. }
  160. return false
  161. }
  162. // GetAttachment serve attachements
  163. func GetAttachment(ctx *context.Context) {
  164. typeCloudBrain := ctx.QueryInt("type")
  165. err := checkTypeCloudBrain(typeCloudBrain)
  166. if err != nil {
  167. ctx.ServerError("checkTypeCloudBrain failed", err)
  168. return
  169. }
  170. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  171. if err != nil {
  172. if models.IsErrAttachmentNotExist(err) {
  173. ctx.Error(404)
  174. } else {
  175. ctx.ServerError("GetAttachmentByUUID", err)
  176. }
  177. return
  178. }
  179. repository, unitType, err := attach.LinkedRepository()
  180. if err != nil {
  181. ctx.ServerError("LinkedRepository", err)
  182. return
  183. }
  184. dataSet, err := attach.LinkedDataSet()
  185. if err != nil {
  186. ctx.ServerError("LinkedDataSet", err)
  187. return
  188. }
  189. if repository == nil && dataSet != nil {
  190. repository, _ = models.GetRepositoryByID(dataSet.RepoID)
  191. unitType = models.UnitTypeDatasets
  192. }
  193. if repository == nil { //If not linked
  194. //if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) && attach.IsPrivate { //We block if not the uploader
  195. //log.Info("ctx.IsSigned =" + fmt.Sprintf("%v", ctx.IsSigned))
  196. if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) && attach.IsPrivate && !DownloadUserIsOrgOrCollaboration(ctx, attach) { //We block if not the uploader
  197. ctx.Error(http.StatusNotFound)
  198. return
  199. }
  200. } else { //If we have the repository we check access
  201. perm, errPermission := models.GetUserRepoPermission(repository, ctx.User)
  202. if errPermission != nil {
  203. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", errPermission.Error())
  204. return
  205. }
  206. if !perm.CanRead(unitType) {
  207. ctx.Error(http.StatusNotFound)
  208. return
  209. }
  210. }
  211. if dataSet != nil {
  212. isPermit, err := models.GetUserDataSetPermission(dataSet, ctx.User)
  213. if err != nil {
  214. ctx.Error(http.StatusInternalServerError, "GetUserDataSetPermission", err.Error())
  215. return
  216. }
  217. if !isPermit {
  218. ctx.Error(http.StatusNotFound)
  219. return
  220. }
  221. }
  222. //If we have matched and access to release or issue
  223. if setting.Attachment.StoreType == storage.MinioStorageType {
  224. url := ""
  225. if typeCloudBrain == models.TypeCloudBrainOne {
  226. url, err = storage.Attachments.PresignedGetURL(setting.Attachment.Minio.BasePath+attach.RelativePath(), attach.Name)
  227. if err != nil {
  228. ctx.ServerError("PresignedGetURL", err)
  229. return
  230. }
  231. } else {
  232. url, err = storage.ObsGetPreSignedUrl(attach.UUID, attach.Name)
  233. if err != nil {
  234. ctx.ServerError("ObsGetPreSignedUrl", err)
  235. return
  236. }
  237. }
  238. if err = increaseDownloadCount(attach, dataSet); err != nil {
  239. ctx.ServerError("Update", err)
  240. return
  241. }
  242. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  243. } else {
  244. fr, err := storage.Attachments.Open(attach.RelativePath())
  245. if err != nil {
  246. ctx.ServerError("Open", err)
  247. return
  248. }
  249. defer fr.Close()
  250. if err = increaseDownloadCount(attach, dataSet); err != nil {
  251. ctx.ServerError("Update", err)
  252. return
  253. }
  254. if err = ServeData(ctx, attach.Name, fr); err != nil {
  255. ctx.ServerError("ServeData", err)
  256. return
  257. }
  258. }
  259. }
  260. func increaseDownloadCount(attach *models.Attachment, dataSet *models.Dataset) error {
  261. if err := attach.IncreaseDownloadCount(); err != nil {
  262. return err
  263. }
  264. if dataSet != nil {
  265. if err := models.IncreaseDownloadCount(dataSet.ID); err != nil {
  266. return err
  267. }
  268. }
  269. return nil
  270. }
  271. // Get a presigned url for put object
  272. func GetPresignedPutObjectURL(ctx *context.Context) {
  273. if !setting.Attachment.Enabled {
  274. ctx.Error(404, "attachment is not enabled")
  275. return
  276. }
  277. err := upload.VerifyFileType(ctx.Params("file_type"), strings.Split(setting.Attachment.AllowedTypes, ","))
  278. if err != nil {
  279. ctx.Error(400, err.Error())
  280. return
  281. }
  282. if setting.Attachment.StoreType == storage.MinioStorageType {
  283. uuid := gouuid.NewV4().String()
  284. url, err := storage.Attachments.PresignedPutURL(models.AttachmentRelativePath(uuid))
  285. if err != nil {
  286. ctx.ServerError("PresignedPutURL", err)
  287. return
  288. }
  289. ctx.JSON(200, map[string]string{
  290. "uuid": uuid,
  291. "url": url,
  292. })
  293. } else {
  294. ctx.Error(404, "storage type is not enabled")
  295. return
  296. }
  297. }
  298. // AddAttachment response for add attachment record
  299. func AddAttachment(ctx *context.Context) {
  300. typeCloudBrain := ctx.QueryInt("type")
  301. err := checkTypeCloudBrain(typeCloudBrain)
  302. if err != nil {
  303. ctx.ServerError("checkTypeCloudBrain failed", err)
  304. return
  305. }
  306. uuid := ctx.Query("uuid")
  307. has := false
  308. if typeCloudBrain == models.TypeCloudBrainOne {
  309. has, err = storage.Attachments.HasObject(models.AttachmentRelativePath(uuid))
  310. if err != nil {
  311. ctx.ServerError("HasObject", err)
  312. return
  313. }
  314. } else {
  315. has, err = storage.ObsHasObject(setting.BasePath + models.AttachmentRelativePath(uuid) + "/" + uuid)
  316. if err != nil {
  317. ctx.ServerError("ObsHasObject", err)
  318. return
  319. }
  320. }
  321. if !has {
  322. ctx.Error(404, "attachment has not been uploaded")
  323. return
  324. }
  325. attachment, err := models.InsertAttachment(&models.Attachment{
  326. UUID: uuid,
  327. UploaderID: ctx.User.ID,
  328. IsPrivate: true,
  329. Name: ctx.Query("file_name"),
  330. Size: ctx.QueryInt64("size"),
  331. DatasetID: ctx.QueryInt64("dataset_id"),
  332. Type: typeCloudBrain,
  333. })
  334. if err != nil {
  335. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  336. return
  337. }
  338. if attachment.DatasetID != 0 {
  339. if isCanDecompress(attachment.Name) {
  340. if typeCloudBrain == models.TypeCloudBrainOne {
  341. err = worker.SendDecompressTask(contexExt.Background(), uuid, attachment.Name)
  342. if err != nil {
  343. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  344. } else {
  345. attachment.DecompressState = models.DecompressStateIng
  346. err = models.UpdateAttachment(attachment)
  347. if err != nil {
  348. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  349. }
  350. }
  351. }
  352. //todo:decompress type_two
  353. }
  354. }
  355. ctx.JSON(200, map[string]string{
  356. "result_code": "0",
  357. })
  358. }
  359. func isCanDecompress(name string) bool {
  360. if strings.HasSuffix(name, ".zip") || strings.HasSuffix(name, ".tar.gz") || strings.HasSuffix(name, ".tgz") {
  361. return true
  362. }
  363. return false
  364. }
  365. func UpdateAttachmentDecompressState(ctx *context.Context) {
  366. uuid := ctx.Query("uuid")
  367. result := ctx.Query("result")
  368. attach, err := models.GetAttachmentByUUID(uuid)
  369. if err != nil {
  370. log.Error("GetAttachmentByUUID(%s) failed:%s", uuid, err.Error())
  371. return
  372. }
  373. if result == DecompressSuccess {
  374. attach.DecompressState = models.DecompressStateDone
  375. } else if result == DecompressFailed {
  376. attach.DecompressState = models.DecompressStateFailed
  377. } else {
  378. log.Error("result is error:", result)
  379. return
  380. }
  381. err = models.UpdateAttachment(attach)
  382. if err != nil {
  383. log.Error("UpdateAttachment(%s) failed:%s", uuid, err.Error())
  384. return
  385. }
  386. log.Info("start to send msg to labelsystem ")
  387. dataset, _ := models.GetDatasetByID(attach.DatasetID)
  388. var labelMap map[string]string
  389. labelMap = make(map[string]string)
  390. labelMap["UUID"] = uuid
  391. labelMap["Type"] = fmt.Sprint(attach.Type)
  392. labelMap["UploaderID"] = fmt.Sprint(attach.UploaderID)
  393. labelMap["RepoID"] = fmt.Sprint(dataset.RepoID)
  394. labelMap["AttachName"] = attach.Name
  395. attachjson, _ := json.Marshal(labelMap)
  396. labelmsg.SendAddAttachToLabelSys(string(attachjson))
  397. log.Info("end to send msg to labelsystem ")
  398. ctx.JSON(200, map[string]string{
  399. "result_code": "0",
  400. })
  401. }
  402. func GetSuccessChunks(ctx *context.Context) {
  403. fileMD5 := ctx.Query("md5")
  404. typeCloudBrain := ctx.QueryInt("type")
  405. var chunks string
  406. err := checkTypeCloudBrain(typeCloudBrain)
  407. if err != nil {
  408. ctx.ServerError("checkTypeCloudBrain failed", err)
  409. return
  410. }
  411. fileChunk, err := models.GetFileChunkByMD5AndUser(fileMD5, ctx.User.ID, typeCloudBrain)
  412. if err != nil {
  413. if models.IsErrFileChunkNotExist(err) {
  414. ctx.JSON(200, map[string]string{
  415. "uuid": "",
  416. "uploaded": "0",
  417. "uploadID": "",
  418. "chunks": "",
  419. })
  420. } else {
  421. ctx.ServerError("GetFileChunkByMD5", err)
  422. }
  423. return
  424. }
  425. isExist := false
  426. if typeCloudBrain == models.TypeCloudBrainOne {
  427. isExist, err = storage.Attachments.HasObject(models.AttachmentRelativePath(fileChunk.UUID))
  428. if err != nil {
  429. ctx.ServerError("HasObject failed", err)
  430. return
  431. }
  432. } else {
  433. isExist, err = storage.ObsHasObject(setting.BasePath + models.AttachmentRelativePath(fileChunk.UUID) + "/" + fileChunk.UUID)
  434. if err != nil {
  435. ctx.ServerError("ObsHasObject failed", err)
  436. return
  437. }
  438. }
  439. if isExist {
  440. if fileChunk.IsUploaded == models.FileNotUploaded {
  441. log.Info("the file has been uploaded but not recorded")
  442. fileChunk.IsUploaded = models.FileUploaded
  443. if err = models.UpdateFileChunk(fileChunk); err != nil {
  444. log.Error("UpdateFileChunk failed:", err.Error())
  445. }
  446. }
  447. } else {
  448. if fileChunk.IsUploaded == models.FileUploaded {
  449. log.Info("the file has been recorded but not uploaded")
  450. fileChunk.IsUploaded = models.FileNotUploaded
  451. if err = models.UpdateFileChunk(fileChunk); err != nil {
  452. log.Error("UpdateFileChunk failed:", err.Error())
  453. }
  454. }
  455. if typeCloudBrain == models.TypeCloudBrainOne {
  456. chunks, err = storage.GetPartInfos(fileChunk.UUID, fileChunk.UploadID)
  457. if err != nil {
  458. log.Error("GetPartInfos failed:%v", err.Error())
  459. }
  460. } else {
  461. chunks, err = storage.GetObsPartInfos(fileChunk.UUID, fileChunk.UploadID)
  462. if err != nil {
  463. log.Error("GetObsPartInfos failed:%v", err.Error())
  464. }
  465. }
  466. if err != nil {
  467. models.DeleteFileChunk(fileChunk)
  468. ctx.JSON(200, map[string]string{
  469. "uuid": "",
  470. "uploaded": "0",
  471. "uploadID": "",
  472. "chunks": "",
  473. })
  474. return
  475. }
  476. }
  477. var attachID int64
  478. attach, err := models.GetAttachmentByUUID(fileChunk.UUID)
  479. if err != nil {
  480. if models.IsErrAttachmentNotExist(err) {
  481. attachID = 0
  482. } else {
  483. ctx.ServerError("GetAttachmentByUUID", err)
  484. return
  485. }
  486. } else {
  487. attachID = attach.ID
  488. }
  489. if attach == nil {
  490. ctx.JSON(200, map[string]string{
  491. "uuid": fileChunk.UUID,
  492. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  493. "uploadID": fileChunk.UploadID,
  494. "chunks": string(chunks),
  495. "attachID": "0",
  496. "datasetID": "0",
  497. "fileName": "",
  498. "datasetName": "",
  499. })
  500. return
  501. }
  502. dataset, err := models.GetDatasetByID(attach.DatasetID)
  503. if err != nil {
  504. ctx.ServerError("GetDatasetByID", err)
  505. return
  506. }
  507. ctx.JSON(200, map[string]string{
  508. "uuid": fileChunk.UUID,
  509. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  510. "uploadID": fileChunk.UploadID,
  511. "chunks": string(chunks),
  512. "attachID": strconv.Itoa(int(attachID)),
  513. "datasetID": strconv.Itoa(int(attach.DatasetID)),
  514. "fileName": attach.Name,
  515. "datasetName": dataset.Title,
  516. })
  517. }
  518. func NewMultipart(ctx *context.Context) {
  519. if !setting.Attachment.Enabled {
  520. ctx.Error(404, "attachment is not enabled")
  521. return
  522. }
  523. err := upload.VerifyFileType(ctx.Query("fileType"), strings.Split(setting.Attachment.AllowedTypes, ","))
  524. if err != nil {
  525. ctx.Error(400, err.Error())
  526. return
  527. }
  528. typeCloudBrain := ctx.QueryInt("type")
  529. err = checkTypeCloudBrain(typeCloudBrain)
  530. if err != nil {
  531. ctx.ServerError("checkTypeCloudBrain failed", err)
  532. return
  533. }
  534. fileName := ctx.Query("file_name")
  535. if setting.Attachment.StoreType == storage.MinioStorageType {
  536. totalChunkCounts := ctx.QueryInt("totalChunkCounts")
  537. if totalChunkCounts > minio_ext.MaxPartsCount {
  538. ctx.Error(400, fmt.Sprintf("chunk counts(%d) is too much", totalChunkCounts))
  539. return
  540. }
  541. fileSize := ctx.QueryInt64("size")
  542. if fileSize > minio_ext.MaxMultipartPutObjectSize {
  543. ctx.Error(400, fmt.Sprintf("file size(%d) is too big", fileSize))
  544. return
  545. }
  546. uuid := gouuid.NewV4().String()
  547. var uploadID string
  548. if typeCloudBrain == models.TypeCloudBrainOne {
  549. uploadID, err = storage.NewMultiPartUpload(uuid)
  550. if err != nil {
  551. ctx.ServerError("NewMultipart", err)
  552. return
  553. }
  554. } else {
  555. uploadID, err = storage.NewObsMultiPartUpload(uuid, fileName)
  556. if err != nil {
  557. ctx.ServerError("NewObsMultiPartUpload", err)
  558. return
  559. }
  560. }
  561. _, err = models.InsertFileChunk(&models.FileChunk{
  562. UUID: uuid,
  563. UserID: ctx.User.ID,
  564. UploadID: uploadID,
  565. Md5: ctx.Query("md5"),
  566. Size: fileSize,
  567. TotalChunks: totalChunkCounts,
  568. Type: typeCloudBrain,
  569. })
  570. if err != nil {
  571. ctx.Error(500, fmt.Sprintf("InsertFileChunk: %v", err))
  572. return
  573. }
  574. ctx.JSON(200, map[string]string{
  575. "uuid": uuid,
  576. "uploadID": uploadID,
  577. })
  578. } else {
  579. ctx.Error(404, "storage type is not enabled")
  580. return
  581. }
  582. }
  583. func GetMultipartUploadUrl(ctx *context.Context) {
  584. uuid := ctx.Query("uuid")
  585. uploadID := ctx.Query("uploadID")
  586. partNumber := ctx.QueryInt("chunkNumber")
  587. size := ctx.QueryInt64("size")
  588. fileName := ctx.Query("file_name")
  589. typeCloudBrain := ctx.QueryInt("type")
  590. err := checkTypeCloudBrain(typeCloudBrain)
  591. if err != nil {
  592. ctx.ServerError("checkTypeCloudBrain failed", err)
  593. return
  594. }
  595. url := ""
  596. if typeCloudBrain == models.TypeCloudBrainOne {
  597. if size > minio_ext.MinPartSize {
  598. ctx.Error(400, fmt.Sprintf("chunk size(%d) is too big", size))
  599. return
  600. }
  601. url, err = storage.GenMultiPartSignedUrl(uuid, uploadID, partNumber, size)
  602. if err != nil {
  603. ctx.Error(500, fmt.Sprintf("GenMultiPartSignedUrl failed: %v", err))
  604. return
  605. }
  606. } else {
  607. url, err = storage.ObsGenMultiPartSignedUrl(uuid, uploadID, partNumber, fileName)
  608. if err != nil {
  609. ctx.Error(500, fmt.Sprintf("ObsGenMultiPartSignedUrl failed: %v", err))
  610. return
  611. }
  612. }
  613. ctx.JSON(200, map[string]string{
  614. "url": url,
  615. })
  616. }
  617. func GetObsKey(ctx *context.Context) {
  618. uuid := gouuid.NewV4().String()
  619. key := strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, uuid)), "/")
  620. ctx.JSON(200, map[string]string{
  621. "uuid": uuid,
  622. "key": key,
  623. "access_key_id": setting.AccessKeyID,
  624. "secret_access_key": setting.SecretAccessKey,
  625. "server": setting.Endpoint,
  626. "bucket": setting.Bucket,
  627. })
  628. }
  629. func CompleteMultipart(ctx *context.Context) {
  630. uuid := ctx.Query("uuid")
  631. uploadID := ctx.Query("uploadID")
  632. typeCloudBrain := ctx.QueryInt("type")
  633. fileName := ctx.Query("file_name")
  634. err := checkTypeCloudBrain(typeCloudBrain)
  635. if err != nil {
  636. ctx.ServerError("checkTypeCloudBrain failed", err)
  637. return
  638. }
  639. fileChunk, err := models.GetFileChunkByUUID(uuid)
  640. if err != nil {
  641. if models.IsErrFileChunkNotExist(err) {
  642. ctx.Error(404)
  643. } else {
  644. ctx.ServerError("GetFileChunkByUUID", err)
  645. }
  646. return
  647. }
  648. if typeCloudBrain == models.TypeCloudBrainOne {
  649. _, err = storage.CompleteMultiPartUpload(uuid, uploadID)
  650. if err != nil {
  651. ctx.Error(500, fmt.Sprintf("CompleteMultiPartUpload failed: %v", err))
  652. return
  653. }
  654. } else {
  655. err = storage.CompleteObsMultiPartUpload(uuid, uploadID, fileName)
  656. if err != nil {
  657. ctx.Error(500, fmt.Sprintf("CompleteObsMultiPartUpload failed: %v", err))
  658. return
  659. }
  660. }
  661. fileChunk.IsUploaded = models.FileUploaded
  662. err = models.UpdateFileChunk(fileChunk)
  663. if err != nil {
  664. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  665. return
  666. }
  667. attachment, err := models.InsertAttachment(&models.Attachment{
  668. UUID: uuid,
  669. UploaderID: ctx.User.ID,
  670. IsPrivate: true,
  671. Name: fileName,
  672. Size: ctx.QueryInt64("size"),
  673. DatasetID: ctx.QueryInt64("dataset_id"),
  674. Type: typeCloudBrain,
  675. })
  676. if err != nil {
  677. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  678. return
  679. }
  680. if attachment.DatasetID != 0 {
  681. if isCanDecompress(attachment.Name) {
  682. if typeCloudBrain == models.TypeCloudBrainOne {
  683. err = worker.SendDecompressTask(contexExt.Background(), uuid, attachment.Name)
  684. if err != nil {
  685. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  686. } else {
  687. attachment.DecompressState = models.DecompressStateIng
  688. err = models.UpdateAttachment(attachment)
  689. if err != nil {
  690. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  691. }
  692. }
  693. }
  694. if typeCloudBrain == models.TypeCloudBrainTwo {
  695. attachjson, _ := json.Marshal(attachment)
  696. labelmsg.SendDecompressAttachToLabelOBS(string(attachjson))
  697. }
  698. } else {
  699. dataset, _ := models.GetDatasetByID(attachment.DatasetID)
  700. var labelMap map[string]string
  701. labelMap = make(map[string]string)
  702. labelMap["UUID"] = uuid
  703. labelMap["Type"] = fmt.Sprint(attachment.Type)
  704. labelMap["UploaderID"] = fmt.Sprint(attachment.UploaderID)
  705. labelMap["RepoID"] = fmt.Sprint(dataset.RepoID)
  706. labelMap["AttachName"] = attachment.Name
  707. attachjson, _ := json.Marshal(labelMap)
  708. labelmsg.SendAddAttachToLabelSys(string(attachjson))
  709. }
  710. }
  711. ctx.JSON(200, map[string]string{
  712. "result_code": "0",
  713. })
  714. }
  715. func UpdateMultipart(ctx *context.Context) {
  716. uuid := ctx.Query("uuid")
  717. partNumber := ctx.QueryInt("chunkNumber")
  718. etag := ctx.Query("etag")
  719. fileChunk, err := models.GetFileChunkByUUID(uuid)
  720. if err != nil {
  721. if models.IsErrFileChunkNotExist(err) {
  722. ctx.Error(404)
  723. } else {
  724. ctx.ServerError("GetFileChunkByUUID", err)
  725. }
  726. return
  727. }
  728. fileChunk.CompletedParts = append(fileChunk.CompletedParts, strconv.Itoa(partNumber)+"-"+strings.Replace(etag, "\"", "", -1))
  729. err = models.UpdateFileChunk(fileChunk)
  730. if err != nil {
  731. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  732. return
  733. }
  734. ctx.JSON(200, map[string]string{
  735. "result_code": "0",
  736. })
  737. }
  738. func HandleUnDecompressAttachment() {
  739. attachs, err := models.GetUnDecompressAttachments()
  740. if err != nil {
  741. log.Error("GetUnDecompressAttachments failed:", err.Error())
  742. return
  743. }
  744. for _, attach := range attachs {
  745. err = worker.SendDecompressTask(contexExt.Background(), attach.UUID, attach.Name)
  746. if err != nil {
  747. log.Error("SendDecompressTask(%s) failed:%s", attach.UUID, err.Error())
  748. } else {
  749. attach.DecompressState = models.DecompressStateIng
  750. err = models.UpdateAttachment(attach)
  751. if err != nil {
  752. log.Error("UpdateAttachment state(%s) failed:%s", attach.UUID, err.Error())
  753. }
  754. }
  755. }
  756. return
  757. }
  758. func QueryAllPublicDataset(ctx *context.Context) {
  759. attachs, err := models.GetAllPublicAttachments()
  760. if err != nil {
  761. ctx.JSON(200, map[string]string{
  762. "result_code": "-1",
  763. "error_msg": err.Error(),
  764. "data": "",
  765. })
  766. return
  767. }
  768. queryDatasets(ctx, attachs)
  769. }
  770. func QueryPrivateDataset(ctx *context.Context) {
  771. username := ctx.Params(":username")
  772. attachs, err := models.GetPrivateAttachments(username)
  773. if err != nil {
  774. ctx.JSON(200, map[string]string{
  775. "result_code": "-1",
  776. "error_msg": err.Error(),
  777. "data": "",
  778. })
  779. return
  780. }
  781. for _, attach := range attachs {
  782. attach.Name = username
  783. }
  784. queryDatasets(ctx, attachs)
  785. }
  786. func queryDatasets(ctx *context.Context, attachs []*models.AttachmentUsername) {
  787. var datasets []CloudBrainDataset
  788. if len(attachs) == 0 {
  789. log.Info("dataset is null")
  790. ctx.JSON(200, map[string]string{
  791. "result_code": "0",
  792. "error_msg": "",
  793. "data": "",
  794. })
  795. return
  796. }
  797. for _, attch := range attachs {
  798. has, err := storage.Attachments.HasObject(models.AttachmentRelativePath(attch.UUID))
  799. if err != nil || !has {
  800. continue
  801. }
  802. datasets = append(datasets, CloudBrainDataset{strconv.FormatInt(attch.ID, 10),
  803. attch.Attachment.Name,
  804. setting.Attachment.Minio.RealPath +
  805. setting.Attachment.Minio.Bucket + "/" +
  806. setting.Attachment.Minio.BasePath +
  807. models.AttachmentRelativePath(attch.UUID) +
  808. attch.UUID,
  809. attch.Name,
  810. attch.CreatedUnix.Format("2006-01-02 03:04:05 PM")})
  811. }
  812. data, err := json.Marshal(datasets)
  813. if err != nil {
  814. log.Error("json.Marshal failed:", err.Error())
  815. ctx.JSON(200, map[string]string{
  816. "result_code": "-1",
  817. "error_msg": err.Error(),
  818. "data": "",
  819. })
  820. return
  821. }
  822. ctx.JSON(200, map[string]string{
  823. "result_code": "0",
  824. "error_msg": "",
  825. "data": string(data),
  826. })
  827. return
  828. }
  829. func checkTypeCloudBrain(typeCloudBrain int) error {
  830. if typeCloudBrain != models.TypeCloudBrainOne && typeCloudBrain != models.TypeCloudBrainTwo {
  831. log.Error("type error:", typeCloudBrain)
  832. return errors.New("type error")
  833. }
  834. return nil
  835. }