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