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 26 kB

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