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

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