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
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
5 years ago
5 years ago
4 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
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
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  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. // GetAttachment serve attachements
  126. func GetAttachment(ctx *context.Context) {
  127. typeCloudBrain := ctx.QueryInt("type")
  128. err := checkTypeCloudBrain(typeCloudBrain)
  129. if err != nil {
  130. ctx.ServerError("checkTypeCloudBrain failed", err)
  131. return
  132. }
  133. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  134. if err != nil {
  135. if models.IsErrAttachmentNotExist(err) {
  136. ctx.Error(404)
  137. } else {
  138. ctx.ServerError("GetAttachmentByUUID", err)
  139. }
  140. return
  141. }
  142. repository, unitType, err := attach.LinkedRepository()
  143. if err != nil {
  144. ctx.ServerError("LinkedRepository", err)
  145. return
  146. }
  147. if repository == nil { //If not linked
  148. if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) && attach.IsPrivate { //We block if not the uploader
  149. ctx.Error(http.StatusNotFound)
  150. return
  151. }
  152. } else { //If we have the repository we check access
  153. perm, err := models.GetUserRepoPermission(repository, ctx.User)
  154. if err != nil {
  155. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err.Error())
  156. return
  157. }
  158. if !perm.CanRead(unitType) {
  159. ctx.Error(http.StatusNotFound)
  160. return
  161. }
  162. }
  163. dataSet, err := attach.LinkedDataSet()
  164. if err != nil {
  165. ctx.ServerError("LinkedDataSet", err)
  166. return
  167. }
  168. if dataSet != nil {
  169. isPermit, err := models.GetUserDataSetPermission(dataSet, ctx.User)
  170. if err != nil {
  171. ctx.Error(http.StatusInternalServerError, "GetUserDataSetPermission", err.Error())
  172. return
  173. }
  174. if !isPermit {
  175. ctx.Error(http.StatusNotFound)
  176. return
  177. }
  178. }
  179. //If we have matched and access to release or issue
  180. if setting.Attachment.StoreType == storage.MinioStorageType {
  181. url := ""
  182. if typeCloudBrain == models.TypeCloudBrainOne {
  183. url, err = storage.Attachments.PresignedGetURL(attach.RelativePath(), attach.Name)
  184. if err != nil {
  185. ctx.ServerError("PresignedGetURL", err)
  186. return
  187. }
  188. } else {
  189. url, err = storage.ObsGetPreSignedUrl(attach.UUID, attach.Name)
  190. if err != nil {
  191. ctx.ServerError("ObsGetPreSignedUrl", err)
  192. return
  193. }
  194. }
  195. log.Info(url)
  196. if err = increaseDownloadCount(attach, dataSet); err != nil {
  197. ctx.ServerError("Update", err)
  198. return
  199. }
  200. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  201. } else {
  202. fr, err := storage.Attachments.Open(attach.RelativePath())
  203. if err != nil {
  204. ctx.ServerError("Open", err)
  205. return
  206. }
  207. defer fr.Close()
  208. if err = increaseDownloadCount(attach, dataSet); err != nil {
  209. ctx.ServerError("Update", err)
  210. return
  211. }
  212. if err = ServeData(ctx, attach.Name, fr); err != nil {
  213. ctx.ServerError("ServeData", err)
  214. return
  215. }
  216. }
  217. }
  218. func increaseDownloadCount(attach *models.Attachment, dataSet *models.Dataset) error {
  219. if err := attach.IncreaseDownloadCount(); err != nil {
  220. return err
  221. }
  222. if dataSet != nil {
  223. if err := models.IncreaseDownloadCount(dataSet.ID); err != nil {
  224. return err
  225. }
  226. }
  227. return nil
  228. }
  229. // Get a presigned url for put object
  230. func GetPresignedPutObjectURL(ctx *context.Context) {
  231. if !setting.Attachment.Enabled {
  232. ctx.Error(404, "attachment is not enabled")
  233. return
  234. }
  235. err := upload.VerifyFileType(ctx.Params("file_type"), strings.Split(setting.Attachment.AllowedTypes, ","))
  236. if err != nil {
  237. ctx.Error(400, err.Error())
  238. return
  239. }
  240. if setting.Attachment.StoreType == storage.MinioStorageType {
  241. uuid := gouuid.NewV4().String()
  242. url, err := storage.Attachments.PresignedPutURL(models.AttachmentRelativePath(uuid))
  243. if err != nil {
  244. ctx.ServerError("PresignedPutURL", err)
  245. return
  246. }
  247. ctx.JSON(200, map[string]string{
  248. "uuid": uuid,
  249. "url": url,
  250. })
  251. } else {
  252. ctx.Error(404, "storage type is not enabled")
  253. return
  254. }
  255. }
  256. // AddAttachment response for add attachment record
  257. func AddAttachment(ctx *context.Context) {
  258. typeCloudBrain := ctx.QueryInt("type")
  259. err := checkTypeCloudBrain(typeCloudBrain)
  260. if err != nil {
  261. ctx.ServerError("checkTypeCloudBrain failed", err)
  262. return
  263. }
  264. uuid := ctx.Query("uuid")
  265. has := false
  266. if typeCloudBrain == models.TypeCloudBrainOne {
  267. has, err = storage.Attachments.HasObject(models.AttachmentRelativePath(uuid))
  268. if err != nil {
  269. ctx.ServerError("HasObject", err)
  270. return
  271. }
  272. } else {
  273. has, err = storage.ObsHasObject(setting.BasePath + models.AttachmentRelativePath(uuid) + "/" + uuid)
  274. if err != nil {
  275. ctx.ServerError("ObsHasObject", err)
  276. return
  277. }
  278. }
  279. if !has {
  280. ctx.Error(404, "attachment has not been uploaded")
  281. return
  282. }
  283. attachment, err := models.InsertAttachment(&models.Attachment{
  284. UUID: uuid,
  285. UploaderID: ctx.User.ID,
  286. IsPrivate: true,
  287. Name: ctx.Query("file_name"),
  288. Size: ctx.QueryInt64("size"),
  289. DatasetID: ctx.QueryInt64("dataset_id"),
  290. Type: typeCloudBrain,
  291. })
  292. if err != nil {
  293. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  294. return
  295. }
  296. if attachment.DatasetID != 0 {
  297. if strings.HasSuffix(attachment.Name, ".zip") {
  298. if typeCloudBrain == models.TypeCloudBrainOne {
  299. err = worker.SendDecompressTask(contexExt.Background(), uuid)
  300. if err != nil {
  301. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  302. } else {
  303. attachment.DecompressState = models.DecompressStateIng
  304. err = models.UpdateAttachment(attachment)
  305. if err != nil {
  306. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  307. }
  308. }
  309. }
  310. //todo:decompress type_two
  311. }
  312. }
  313. ctx.JSON(200, map[string]string{
  314. "result_code": "0",
  315. })
  316. }
  317. func UpdateAttachmentDecompressState(ctx *context.Context) {
  318. uuid := ctx.Query("uuid")
  319. result := ctx.Query("result")
  320. attach, err := models.GetAttachmentByUUID(uuid)
  321. if err != nil {
  322. log.Error("GetAttachmentByUUID(%s) failed:%s", uuid, err.Error())
  323. return
  324. }
  325. if result == DecompressSuccess {
  326. attach.DecompressState = models.DecompressStateDone
  327. } else if result == DecompressFailed {
  328. attach.DecompressState = models.DecompressStateFailed
  329. } else {
  330. log.Error("result is error:", result)
  331. return
  332. }
  333. err = models.UpdateAttachment(attach)
  334. if err != nil {
  335. log.Error("UpdateAttachment(%s) failed:%s", uuid, err.Error())
  336. return
  337. }
  338. ctx.JSON(200, map[string]string{
  339. "result_code": "0",
  340. })
  341. }
  342. func GetSuccessChunks(ctx *context.Context) {
  343. fileMD5 := ctx.Query("md5")
  344. typeCloudBrain := ctx.QueryInt("type")
  345. var chunks string
  346. err := checkTypeCloudBrain(typeCloudBrain)
  347. if err != nil {
  348. ctx.ServerError("checkTypeCloudBrain failed", err)
  349. return
  350. }
  351. fileChunk, err := models.GetFileChunkByMD5AndUser(fileMD5, ctx.User.ID, typeCloudBrain)
  352. if err != nil {
  353. if models.IsErrFileChunkNotExist(err) {
  354. ctx.JSON(200, map[string]string{
  355. "uuid": "",
  356. "uploaded": "0",
  357. "uploadID": "",
  358. "chunks": "",
  359. })
  360. } else {
  361. ctx.ServerError("GetFileChunkByMD5", err)
  362. }
  363. return
  364. }
  365. isExist := false
  366. if typeCloudBrain == models.TypeCloudBrainOne {
  367. isExist, err = storage.Attachments.HasObject(models.AttachmentRelativePath(fileChunk.UUID))
  368. if err != nil {
  369. ctx.ServerError("HasObject failed", err)
  370. return
  371. }
  372. } else {
  373. isExist, err = storage.ObsHasObject(models.AttachmentRelativePath(fileChunk.UUID))
  374. if err != nil {
  375. ctx.ServerError("ObsHasObject failed", err)
  376. return
  377. }
  378. }
  379. if isExist {
  380. if fileChunk.IsUploaded == models.FileNotUploaded {
  381. log.Info("the file has been uploaded but not recorded")
  382. fileChunk.IsUploaded = models.FileUploaded
  383. if err = models.UpdateFileChunk(fileChunk); err != nil {
  384. log.Error("UpdateFileChunk failed:", err.Error())
  385. }
  386. }
  387. } else {
  388. if fileChunk.IsUploaded == models.FileUploaded {
  389. log.Info("the file has been recorded but not uploaded")
  390. fileChunk.IsUploaded = models.FileNotUploaded
  391. if err = models.UpdateFileChunk(fileChunk); err != nil {
  392. log.Error("UpdateFileChunk failed:", err.Error())
  393. }
  394. }
  395. if typeCloudBrain == models.TypeCloudBrainOne {
  396. chunks, err = storage.GetPartInfos(fileChunk.UUID, fileChunk.UploadID)
  397. if err != nil {
  398. ctx.ServerError("GetPartInfos failed", err)
  399. return
  400. }
  401. } else {
  402. chunks, err = storage.GetObsPartInfos(fileChunk.UUID, fileChunk.UploadID)
  403. if err != nil {
  404. ctx.ServerError("GetObsPartInfos failed", err)
  405. return
  406. }
  407. }
  408. }
  409. var attachID int64
  410. attach, err := models.GetAttachmentByUUID(fileChunk.UUID)
  411. if err != nil {
  412. if models.IsErrAttachmentNotExist(err) {
  413. attachID = 0
  414. } else {
  415. ctx.ServerError("GetAttachmentByUUID", err)
  416. return
  417. }
  418. } else {
  419. attachID = attach.ID
  420. }
  421. if attach == nil {
  422. ctx.JSON(200, map[string]string{
  423. "uuid": fileChunk.UUID,
  424. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  425. "uploadID": fileChunk.UploadID,
  426. "chunks": string(chunks),
  427. "attachID": "0",
  428. "datasetID": "0",
  429. "fileName": "",
  430. "datasetName": "",
  431. })
  432. return
  433. }
  434. dataset, err := models.GetDatasetByID(attach.DatasetID)
  435. if err != nil {
  436. ctx.ServerError("GetDatasetByID", err)
  437. return
  438. }
  439. ctx.JSON(200, map[string]string{
  440. "uuid": fileChunk.UUID,
  441. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  442. "uploadID": fileChunk.UploadID,
  443. "chunks": string(chunks),
  444. "attachID": strconv.Itoa(int(attachID)),
  445. "datasetID": strconv.Itoa(int(attach.DatasetID)),
  446. "fileName": attach.Name,
  447. "datasetName": dataset.Title,
  448. })
  449. }
  450. func NewMultipart(ctx *context.Context) {
  451. if !setting.Attachment.Enabled {
  452. ctx.Error(404, "attachment is not enabled")
  453. return
  454. }
  455. err := upload.VerifyFileType(ctx.Query("fileType"), strings.Split(setting.Attachment.AllowedTypes, ","))
  456. if err != nil {
  457. ctx.Error(400, err.Error())
  458. return
  459. }
  460. typeCloudBrain := ctx.QueryInt("type")
  461. err = checkTypeCloudBrain(typeCloudBrain)
  462. if err != nil {
  463. ctx.ServerError("checkTypeCloudBrain failed", err)
  464. return
  465. }
  466. if setting.Attachment.StoreType == storage.MinioStorageType {
  467. totalChunkCounts := ctx.QueryInt("totalChunkCounts")
  468. if totalChunkCounts > minio_ext.MaxPartsCount {
  469. ctx.Error(400, fmt.Sprintf("chunk counts(%d) is too much", totalChunkCounts))
  470. return
  471. }
  472. fileSize := ctx.QueryInt64("size")
  473. if fileSize > minio_ext.MaxMultipartPutObjectSize {
  474. ctx.Error(400, fmt.Sprintf("file size(%d) is too big", fileSize))
  475. return
  476. }
  477. uuid := gouuid.NewV4().String()
  478. var uploadID string
  479. if typeCloudBrain == models.TypeCloudBrainOne {
  480. uploadID, err = storage.NewMultiPartUpload(uuid)
  481. if err != nil {
  482. ctx.ServerError("NewMultipart", err)
  483. return
  484. }
  485. } else {
  486. uploadID, err = storage.NewObsMultiPartUpload(uuid)
  487. if err != nil {
  488. ctx.ServerError("NewObsMultiPartUpload", err)
  489. return
  490. }
  491. }
  492. _, err = models.InsertFileChunk(&models.FileChunk{
  493. UUID: uuid,
  494. UserID: ctx.User.ID,
  495. UploadID: uploadID,
  496. Md5: ctx.Query("md5"),
  497. Size: fileSize,
  498. TotalChunks: totalChunkCounts,
  499. Type: typeCloudBrain,
  500. })
  501. if err != nil {
  502. ctx.Error(500, fmt.Sprintf("InsertFileChunk: %v", err))
  503. return
  504. }
  505. ctx.JSON(200, map[string]string{
  506. "uuid": uuid,
  507. "uploadID": uploadID,
  508. })
  509. } else {
  510. ctx.Error(404, "storage type is not enabled")
  511. return
  512. }
  513. }
  514. func GetMultipartUploadUrl(ctx *context.Context) {
  515. uuid := ctx.Query("uuid")
  516. uploadID := ctx.Query("uploadID")
  517. partNumber := ctx.QueryInt("chunkNumber")
  518. size := ctx.QueryInt64("size")
  519. typeCloudBrain := ctx.QueryInt("type")
  520. err := checkTypeCloudBrain(typeCloudBrain)
  521. if err != nil {
  522. ctx.ServerError("checkTypeCloudBrain failed", err)
  523. return
  524. }
  525. url := ""
  526. if typeCloudBrain == models.TypeCloudBrainOne {
  527. if size > minio_ext.MinPartSize {
  528. ctx.Error(400, fmt.Sprintf("chunk size(%d) is too big", size))
  529. return
  530. }
  531. url, err = storage.GenMultiPartSignedUrl(uuid, uploadID, partNumber, size)
  532. if err != nil {
  533. ctx.Error(500, fmt.Sprintf("GenMultiPartSignedUrl failed: %v", err))
  534. return
  535. }
  536. } else {
  537. url, err = storage.ObsGenMultiPartSignedUrl(uuid, uploadID, partNumber, size)
  538. if err != nil {
  539. ctx.Error(500, fmt.Sprintf("ObsGenMultiPartSignedUrl failed: %v", err))
  540. return
  541. }
  542. }
  543. ctx.JSON(200, map[string]string{
  544. "url": url,
  545. })
  546. }
  547. func GetObsKey(ctx *context.Context) {
  548. uuid := gouuid.NewV4().String()
  549. key := strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, uuid)), "/")
  550. ctx.JSON(200, map[string]string{
  551. "uuid": uuid,
  552. "key": key,
  553. "access_key_id": setting.AccessKeyID,
  554. "secret_access_key": setting.SecretAccessKey,
  555. "server": setting.Endpoint,
  556. "bucket": setting.Bucket,
  557. })
  558. }
  559. func UploadPart(ctx *context.Context) {
  560. tmp, err := ctx.Req.Body().String()
  561. log.Info(tmp)
  562. err = ctx.Req.ParseMultipartForm(100*1024*1024)
  563. if err != nil {
  564. ctx.Error(http.StatusBadRequest, fmt.Sprintf("ParseMultipartForm failed: %v", err))
  565. return
  566. }
  567. file, fileHeader, err := ctx.Req.FormFile("file")
  568. log.Info(ctx.Req.Form.Get("file"))
  569. if err != nil {
  570. ctx.Error(http.StatusBadRequest, fmt.Sprintf("FormFile failed: %v", err))
  571. return
  572. }
  573. log.Info(fileHeader.Filename)
  574. etag, err := storage.ObsUploadPart("", "", 1, 1, file)
  575. if err != nil {
  576. ctx.Error(500, fmt.Sprintf("ObsUploadPart failed: %v", err))
  577. return
  578. }
  579. ctx.JSON(200, map[string]string{
  580. "etag": etag,
  581. })
  582. }
  583. func CompleteMultipart(ctx *context.Context) {
  584. uuid := ctx.Query("uuid")
  585. uploadID := ctx.Query("uploadID")
  586. typeCloudBrain := ctx.QueryInt("type")
  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)
  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: ctx.Query("file_name"),
  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 strings.HasSuffix(attachment.Name, ".zip") {
  635. err = worker.SendDecompressTask(contexExt.Background(), uuid)
  636. if err != nil {
  637. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  638. } else {
  639. attachment.DecompressState = models.DecompressStateIng
  640. err = models.UpdateAttachment(attachment)
  641. if err != nil {
  642. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  643. }
  644. }
  645. }
  646. }
  647. ctx.JSON(200, map[string]string{
  648. "result_code": "0",
  649. })
  650. }
  651. func UpdateMultipart(ctx *context.Context) {
  652. uuid := ctx.Query("uuid")
  653. partNumber := ctx.QueryInt("chunkNumber")
  654. etag := ctx.Query("etag")
  655. fileChunk, err := models.GetFileChunkByUUID(uuid)
  656. if err != nil {
  657. if models.IsErrFileChunkNotExist(err) {
  658. ctx.Error(404)
  659. } else {
  660. ctx.ServerError("GetFileChunkByUUID", err)
  661. }
  662. return
  663. }
  664. fileChunk.CompletedParts = append(fileChunk.CompletedParts, strconv.Itoa(partNumber)+"-"+strings.Replace(etag, "\"", "", -1))
  665. err = models.UpdateFileChunk(fileChunk)
  666. if err != nil {
  667. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  668. return
  669. }
  670. ctx.JSON(200, map[string]string{
  671. "result_code": "0",
  672. })
  673. }
  674. func HandleUnDecompressAttachment() {
  675. attachs, err := models.GetUnDecompressAttachments()
  676. if err != nil {
  677. log.Error("GetUnDecompressAttachments failed:", err.Error())
  678. return
  679. }
  680. for _, attach := range attachs {
  681. err = worker.SendDecompressTask(contexExt.Background(), attach.UUID)
  682. if err != nil {
  683. log.Error("SendDecompressTask(%s) failed:%s", attach.UUID, err.Error())
  684. } else {
  685. attach.DecompressState = models.DecompressStateIng
  686. err = models.UpdateAttachment(attach)
  687. if err != nil {
  688. log.Error("UpdateAttachment state(%s) failed:%s", attach.UUID, err.Error())
  689. }
  690. }
  691. }
  692. return
  693. }
  694. func QueryAllPublicDataset(ctx *context.Context) {
  695. attachs, err := models.GetAllPublicAttachments()
  696. if err != nil {
  697. ctx.JSON(200, map[string]string{
  698. "result_code": "-1",
  699. "error_msg": err.Error(),
  700. "data": "",
  701. })
  702. return
  703. }
  704. queryDatasets(ctx, attachs)
  705. }
  706. func QueryPrivateDataset(ctx *context.Context) {
  707. username := ctx.Params(":username")
  708. attachs, err := models.GetPrivateAttachments(username)
  709. if err != nil {
  710. ctx.JSON(200, map[string]string{
  711. "result_code": "-1",
  712. "error_msg": err.Error(),
  713. "data": "",
  714. })
  715. return
  716. }
  717. for _, attach := range attachs {
  718. attach.Name = username
  719. }
  720. queryDatasets(ctx, attachs)
  721. }
  722. func queryDatasets(ctx *context.Context, attachs []*models.AttachmentUsername) {
  723. var datasets []CloudBrainDataset
  724. if len(attachs) == 0 {
  725. log.Info("dataset is null")
  726. ctx.JSON(200, map[string]string{
  727. "result_code": "0",
  728. "error_msg": "",
  729. "data": "",
  730. })
  731. return
  732. }
  733. for _, attch := range attachs {
  734. has, err := storage.Attachments.HasObject(models.AttachmentRelativePath(attch.UUID))
  735. if err != nil || !has {
  736. continue
  737. }
  738. datasets = append(datasets, CloudBrainDataset{strconv.FormatInt(attch.ID, 10),
  739. attch.Attachment.Name,
  740. setting.Attachment.Minio.RealPath +
  741. setting.Attachment.Minio.Bucket + "/" +
  742. setting.Attachment.Minio.BasePath +
  743. models.AttachmentRelativePath(attch.UUID) +
  744. attch.UUID,
  745. attch.Name,
  746. attch.CreatedUnix.Format("2006-01-02 03:04:05 PM")})
  747. }
  748. data, err := json.Marshal(datasets)
  749. if err != nil {
  750. log.Error("json.Marshal failed:", err.Error())
  751. ctx.JSON(200, map[string]string{
  752. "result_code": "-1",
  753. "error_msg": err.Error(),
  754. "data": "",
  755. })
  756. return
  757. }
  758. ctx.JSON(200, map[string]string{
  759. "result_code": "0",
  760. "error_msg": "",
  761. "data": string(data),
  762. })
  763. return
  764. }
  765. func checkTypeCloudBrain(typeCloudBrain int) error {
  766. if typeCloudBrain != models.TypeCloudBrainOne && typeCloudBrain != models.TypeCloudBrainTwo {
  767. log.Error("type error:", typeCloudBrain)
  768. return errors.New("type error")
  769. }
  770. return nil
  771. }