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