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