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 30 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
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
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
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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 GetSuccessChunks(ctx *context.Context) {
  465. fileMD5 := ctx.Query("md5")
  466. typeCloudBrain := ctx.QueryInt("type")
  467. fileName := ctx.Query("file_name")
  468. var chunks string
  469. err := checkTypeCloudBrain(typeCloudBrain)
  470. if err != nil {
  471. ctx.ServerError("checkTypeCloudBrain failed", err)
  472. return
  473. }
  474. fileChunk, err := models.GetFileChunkByMD5AndUser(fileMD5, ctx.User.ID, typeCloudBrain)
  475. if err != nil {
  476. if models.IsErrFileChunkNotExist(err) {
  477. ctx.JSON(200, map[string]string{
  478. "uuid": "",
  479. "uploaded": "0",
  480. "uploadID": "",
  481. "chunks": "",
  482. })
  483. } else {
  484. ctx.ServerError("GetFileChunkByMD5", err)
  485. }
  486. return
  487. }
  488. isExist := false
  489. if typeCloudBrain == models.TypeCloudBrainOne {
  490. isExist, err = storage.Attachments.HasObject(setting.Attachment.Minio.BasePath + models.AttachmentRelativePath(fileChunk.UUID))
  491. if err != nil {
  492. ctx.ServerError("HasObject failed", err)
  493. return
  494. }
  495. } else {
  496. oldFileName := fileName
  497. oldAttachment, _ := models.GetAttachmentByUUID(fileChunk.UUID)
  498. if oldAttachment != nil {
  499. oldFileName = oldAttachment.Name
  500. }
  501. isExist, err = storage.ObsHasObject(setting.BasePath + models.AttachmentRelativePath(fileChunk.UUID) + "/" + oldFileName)
  502. if err != nil {
  503. ctx.ServerError("ObsHasObject failed", err)
  504. return
  505. }
  506. }
  507. if isExist {
  508. if fileChunk.IsUploaded == models.FileNotUploaded {
  509. log.Info("the file has been uploaded but not recorded")
  510. fileChunk.IsUploaded = models.FileUploaded
  511. if err = models.UpdateFileChunk(fileChunk); err != nil {
  512. log.Error("UpdateFileChunk failed:", err.Error())
  513. }
  514. }
  515. } else {
  516. if fileChunk.IsUploaded == models.FileUploaded {
  517. log.Info("the file has been recorded but not uploaded")
  518. fileChunk.IsUploaded = models.FileNotUploaded
  519. if err = models.UpdateFileChunk(fileChunk); err != nil {
  520. log.Error("UpdateFileChunk failed:", err.Error())
  521. }
  522. }
  523. if typeCloudBrain == models.TypeCloudBrainOne {
  524. chunks, err = storage.GetPartInfos(strings.TrimPrefix(path.Join(setting.Attachment.Minio.BasePath, path.Join(fileChunk.UUID[0:1], fileChunk.UUID[1:2], fileChunk.UUID)), "/"), fileChunk.UploadID)
  525. if err != nil {
  526. log.Error("GetPartInfos failed:%v", err.Error())
  527. }
  528. } else {
  529. chunks, err = storage.GetObsPartInfos(strings.TrimPrefix(path.Join(setting.BasePath, path.Join(fileChunk.UUID[0:1], fileChunk.UUID[1:2], fileChunk.UUID, fileName)), "/"), fileChunk.UploadID)
  530. if err != nil {
  531. log.Error("GetObsPartInfos failed:%v", err.Error())
  532. }
  533. }
  534. if err != nil {
  535. models.DeleteFileChunk(fileChunk)
  536. ctx.JSON(200, map[string]string{
  537. "uuid": "",
  538. "uploaded": "0",
  539. "uploadID": "",
  540. "chunks": "",
  541. })
  542. return
  543. }
  544. }
  545. var attachID int64
  546. attach, err := models.GetAttachmentByUUID(fileChunk.UUID)
  547. if err != nil {
  548. if models.IsErrAttachmentNotExist(err) {
  549. attachID = 0
  550. } else {
  551. ctx.ServerError("GetAttachmentByUUID", err)
  552. return
  553. }
  554. } else {
  555. attachID = attach.ID
  556. }
  557. if attach == nil {
  558. ctx.JSON(200, map[string]string{
  559. "uuid": fileChunk.UUID,
  560. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  561. "uploadID": fileChunk.UploadID,
  562. "chunks": string(chunks),
  563. "attachID": "0",
  564. "datasetID": "0",
  565. "fileName": "",
  566. "datasetName": "",
  567. })
  568. return
  569. }
  570. dataset, err := models.GetDatasetByID(attach.DatasetID)
  571. if err != nil {
  572. ctx.ServerError("GetDatasetByID", err)
  573. return
  574. }
  575. ctx.JSON(200, map[string]string{
  576. "uuid": fileChunk.UUID,
  577. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  578. "uploadID": fileChunk.UploadID,
  579. "chunks": string(chunks),
  580. "attachID": strconv.Itoa(int(attachID)),
  581. "datasetID": strconv.Itoa(int(attach.DatasetID)),
  582. "fileName": attach.Name,
  583. "datasetName": dataset.Title,
  584. })
  585. }
  586. func NewMultipart(ctx *context.Context) {
  587. if !setting.Attachment.Enabled {
  588. ctx.Error(404, "attachment is not enabled")
  589. return
  590. }
  591. err := upload.VerifyFileType(ctx.Query("fileType"), strings.Split(setting.Attachment.AllowedTypes, ","))
  592. if err != nil {
  593. ctx.Error(400, err.Error())
  594. return
  595. }
  596. typeCloudBrain := ctx.QueryInt("type")
  597. err = checkTypeCloudBrain(typeCloudBrain)
  598. if err != nil {
  599. ctx.ServerError("checkTypeCloudBrain failed", err)
  600. return
  601. }
  602. fileName := ctx.Query("file_name")
  603. if setting.Attachment.StoreType == storage.MinioStorageType {
  604. totalChunkCounts := ctx.QueryInt("totalChunkCounts")
  605. if totalChunkCounts > minio_ext.MaxPartsCount {
  606. ctx.Error(400, fmt.Sprintf("chunk counts(%d) is too much", totalChunkCounts))
  607. return
  608. }
  609. fileSize := ctx.QueryInt64("size")
  610. if fileSize > minio_ext.MaxMultipartPutObjectSize {
  611. ctx.Error(400, fmt.Sprintf("file size(%d) is too big", fileSize))
  612. return
  613. }
  614. uuid := gouuid.NewV4().String()
  615. var uploadID string
  616. if typeCloudBrain == models.TypeCloudBrainOne {
  617. uploadID, err = storage.NewMultiPartUpload(strings.TrimPrefix(path.Join(setting.Attachment.Minio.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid)), "/"))
  618. if err != nil {
  619. ctx.ServerError("NewMultipart", err)
  620. return
  621. }
  622. } else {
  623. uploadID, err = storage.NewObsMultiPartUpload(strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/"))
  624. if err != nil {
  625. ctx.ServerError("NewObsMultiPartUpload", err)
  626. return
  627. }
  628. }
  629. _, err = models.InsertFileChunk(&models.FileChunk{
  630. UUID: uuid,
  631. UserID: ctx.User.ID,
  632. UploadID: uploadID,
  633. Md5: ctx.Query("md5"),
  634. Size: fileSize,
  635. TotalChunks: totalChunkCounts,
  636. Type: typeCloudBrain,
  637. })
  638. if err != nil {
  639. ctx.Error(500, fmt.Sprintf("InsertFileChunk: %v", err))
  640. return
  641. }
  642. ctx.JSON(200, map[string]string{
  643. "uuid": uuid,
  644. "uploadID": uploadID,
  645. })
  646. } else {
  647. ctx.Error(404, "storage type is not enabled")
  648. return
  649. }
  650. }
  651. func PutOBSProxyUpload(ctx *context.Context) {
  652. uuid := ctx.Query("uuid")
  653. uploadID := ctx.Query("uploadId")
  654. partNumber := ctx.QueryInt("partNumber")
  655. fileName := ctx.Query("file_name")
  656. RequestBody := ctx.Req.Body()
  657. if RequestBody == nil {
  658. ctx.Error(500, fmt.Sprintf("FormFile: %v", RequestBody))
  659. return
  660. }
  661. objectName := strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  662. err := storage.ObsMultiPartUpload(objectName, uploadID, partNumber, fileName, RequestBody.ReadCloser())
  663. if err != nil {
  664. log.Info("upload error.")
  665. }
  666. }
  667. func GetOBSProxyDownload(ctx *context.Context) {
  668. uuid := ctx.Query("uuid")
  669. fileName := ctx.Query("file_name")
  670. objectName := strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/")
  671. body, err := storage.ObsDownloadAFile(setting.Bucket, objectName)
  672. if err != nil {
  673. log.Info("upload error.")
  674. } else {
  675. defer body.Close()
  676. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  677. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  678. p := make([]byte, 1024)
  679. var readErr error
  680. var readCount int
  681. // 读取对象内容
  682. for {
  683. readCount, readErr = body.Read(p)
  684. if readCount > 0 {
  685. ctx.Resp.Write(p[:readCount])
  686. //fmt.Printf("%s", p[:readCount])
  687. }
  688. if readErr != nil {
  689. break
  690. }
  691. }
  692. }
  693. }
  694. func GetMultipartUploadUrl(ctx *context.Context) {
  695. uuid := ctx.Query("uuid")
  696. uploadID := ctx.Query("uploadID")
  697. partNumber := ctx.QueryInt("chunkNumber")
  698. size := ctx.QueryInt64("size")
  699. fileName := ctx.Query("file_name")
  700. typeCloudBrain := ctx.QueryInt("type")
  701. err := checkTypeCloudBrain(typeCloudBrain)
  702. if err != nil {
  703. ctx.ServerError("checkTypeCloudBrain failed", err)
  704. return
  705. }
  706. url := ""
  707. if typeCloudBrain == models.TypeCloudBrainOne {
  708. if size > minio_ext.MinPartSize {
  709. ctx.Error(400, fmt.Sprintf("chunk size(%d) is too big", size))
  710. return
  711. }
  712. url, err = storage.GenMultiPartSignedUrl(strings.TrimPrefix(path.Join(setting.Attachment.Minio.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid)), "/"), uploadID, partNumber, size)
  713. if err != nil {
  714. ctx.Error(500, fmt.Sprintf("GenMultiPartSignedUrl failed: %v", err))
  715. return
  716. }
  717. } else {
  718. if setting.PROXYURL != "" {
  719. url = setting.PROXYURL + "/obs_proxy_multipart?uuid=" + uuid + "&uploadId=" + uploadID + "&partNumber=" + fmt.Sprint(partNumber) + "&file_name=" + fileName
  720. log.Info("return url=" + url)
  721. } else {
  722. url, err = storage.ObsGenMultiPartSignedUrl(strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, fileName)), "/"), uploadID, partNumber)
  723. if err != nil {
  724. ctx.Error(500, fmt.Sprintf("ObsGenMultiPartSignedUrl failed: %v", err))
  725. return
  726. }
  727. log.Info("url=" + url)
  728. }
  729. }
  730. ctx.JSON(200, map[string]string{
  731. "url": url,
  732. })
  733. }
  734. func CompleteMultipart(ctx *context.Context) {
  735. uuid := ctx.Query("uuid")
  736. uploadID := ctx.Query("uploadID")
  737. typeCloudBrain := ctx.QueryInt("type")
  738. fileName := ctx.Query("file_name")
  739. log.Warn("uuid:" + uuid)
  740. log.Warn("typeCloudBrain:" + strconv.Itoa(typeCloudBrain))
  741. err := checkTypeCloudBrain(typeCloudBrain)
  742. if err != nil {
  743. ctx.ServerError("checkTypeCloudBrain failed", err)
  744. return
  745. }
  746. fileChunk, err := models.GetFileChunkByUUID(uuid)
  747. if err != nil {
  748. if models.IsErrFileChunkNotExist(err) {
  749. ctx.Error(404)
  750. } else {
  751. ctx.ServerError("GetFileChunkByUUID", err)
  752. }
  753. return
  754. }
  755. if typeCloudBrain == models.TypeCloudBrainOne {
  756. _, err = storage.CompleteMultiPartUpload(strings.TrimPrefix(path.Join(setting.Attachment.Minio.BasePath, path.Join(fileChunk.UUID[0:1], fileChunk.UUID[1:2], fileChunk.UUID)), "/"), uploadID, fileChunk.TotalChunks)
  757. if err != nil {
  758. ctx.Error(500, fmt.Sprintf("CompleteMultiPartUpload failed: %v", err))
  759. return
  760. }
  761. } else {
  762. err = storage.CompleteObsMultiPartUpload(strings.TrimPrefix(path.Join(setting.BasePath, path.Join(fileChunk.UUID[0:1], fileChunk.UUID[1:2], fileChunk.UUID, fileName)), "/"), uploadID, fileChunk.TotalChunks)
  763. if err != nil {
  764. ctx.Error(500, fmt.Sprintf("CompleteObsMultiPartUpload failed: %v", err))
  765. return
  766. }
  767. }
  768. fileChunk.IsUploaded = models.FileUploaded
  769. err = models.UpdateFileChunk(fileChunk)
  770. if err != nil {
  771. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  772. return
  773. }
  774. dataset, _ := models.GetDatasetByID(ctx.QueryInt64("dataset_id"))
  775. log.Warn("insert attachment to datasetId:" + strconv.FormatInt(dataset.ID, 10))
  776. attachment, err := models.InsertAttachment(&models.Attachment{
  777. UUID: uuid,
  778. UploaderID: ctx.User.ID,
  779. IsPrivate: dataset.IsPrivate(),
  780. Name: fileName,
  781. Size: ctx.QueryInt64("size"),
  782. DatasetID: ctx.QueryInt64("dataset_id"),
  783. Description: ctx.Query("description"),
  784. Type: typeCloudBrain,
  785. })
  786. if err != nil {
  787. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  788. return
  789. }
  790. attachment.UpdateDatasetUpdateUnix()
  791. repository, _ := models.GetRepositoryByID(dataset.RepoID)
  792. notification.NotifyOtherTask(ctx.User, repository, fmt.Sprint(repository.IsPrivate, attachment.IsPrivate), attachment.Name, models.ActionUploadAttachment)
  793. if attachment.DatasetID != 0 {
  794. if isCanDecompress(attachment.Name) {
  795. if typeCloudBrain == models.TypeCloudBrainOne {
  796. err = worker.SendDecompressTask(contexExt.Background(), uuid, attachment.Name)
  797. if err != nil {
  798. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  799. } else {
  800. updateAttachmentDecompressStateIng(attachment)
  801. }
  802. }
  803. if typeCloudBrain == models.TypeCloudBrainTwo {
  804. attachjson, _ := json.Marshal(attachment)
  805. err = labelmsg.SendDecompressAttachToLabelOBS(string(attachjson))
  806. if err != nil {
  807. log.Error("SendDecompressTask to labelsystem (%s) failed:%s", attachment.UUID, err.Error())
  808. } else {
  809. updateAttachmentDecompressStateIng(attachment)
  810. }
  811. }
  812. } else {
  813. var labelMap map[string]string
  814. labelMap = make(map[string]string)
  815. labelMap["UUID"] = uuid
  816. labelMap["Type"] = fmt.Sprint(attachment.Type)
  817. labelMap["UploaderID"] = fmt.Sprint(attachment.UploaderID)
  818. labelMap["RepoID"] = fmt.Sprint(dataset.RepoID)
  819. labelMap["AttachName"] = attachment.Name
  820. attachjson, _ := json.Marshal(labelMap)
  821. labelmsg.SendAddAttachToLabelSys(string(attachjson))
  822. }
  823. }
  824. ctx.JSON(200, map[string]string{
  825. "result_code": "0",
  826. })
  827. }
  828. func HandleUnDecompressAttachment() {
  829. attachs, err := models.GetUnDecompressAttachments()
  830. if err != nil {
  831. log.Error("GetUnDecompressAttachments failed:", err.Error())
  832. return
  833. }
  834. for _, attach := range attachs {
  835. if attach.Type == models.TypeCloudBrainOne {
  836. err = worker.SendDecompressTask(contexExt.Background(), attach.UUID, attach.Name)
  837. if err != nil {
  838. log.Error("SendDecompressTask(%s) failed:%s", attach.UUID, err.Error())
  839. } else {
  840. updateAttachmentDecompressStateIng(attach)
  841. }
  842. } else if attach.Type == models.TypeCloudBrainTwo {
  843. attachjson, _ := json.Marshal(attach)
  844. err = labelmsg.SendDecompressAttachToLabelOBS(string(attachjson))
  845. if err != nil {
  846. log.Error("SendDecompressTask to labelsystem (%s) failed:%s", attach.UUID, err.Error())
  847. } else {
  848. updateAttachmentDecompressStateIng(attach)
  849. }
  850. }
  851. }
  852. return
  853. }
  854. func updateAttachmentDecompressStateIng(attach *models.Attachment) {
  855. attach.DecompressState = models.DecompressStateIng
  856. err := models.UpdateAttachment(attach)
  857. if err != nil {
  858. log.Error("UpdateAttachment state(%s) failed:%s", attach.UUID, err.Error())
  859. }
  860. }
  861. func QueryAllPublicDataset(ctx *context.Context) {
  862. attachs, err := models.GetAllPublicAttachments()
  863. if err != nil {
  864. ctx.JSON(200, map[string]string{
  865. "result_code": "-1",
  866. "error_msg": err.Error(),
  867. "data": "",
  868. })
  869. return
  870. }
  871. queryDatasets(ctx, attachs)
  872. }
  873. func QueryPrivateDataset(ctx *context.Context) {
  874. username := ctx.Params(":username")
  875. attachs, err := models.GetPrivateAttachments(username)
  876. if err != nil {
  877. ctx.JSON(200, map[string]string{
  878. "result_code": "-1",
  879. "error_msg": err.Error(),
  880. "data": "",
  881. })
  882. return
  883. }
  884. for _, attach := range attachs {
  885. attach.Name = username
  886. }
  887. queryDatasets(ctx, attachs)
  888. }
  889. func queryDatasets(ctx *context.Context, attachs []*models.AttachmentUsername) {
  890. var datasets []CloudBrainDataset
  891. if len(attachs) == 0 {
  892. log.Info("dataset is null")
  893. ctx.JSON(200, map[string]string{
  894. "result_code": "0",
  895. "error_msg": "",
  896. "data": "",
  897. })
  898. return
  899. }
  900. for _, attch := range attachs {
  901. has, err := storage.Attachments.HasObject(setting.Attachment.Minio.BasePath + models.AttachmentRelativePath(attch.UUID))
  902. if err != nil || !has {
  903. continue
  904. }
  905. datasets = append(datasets, CloudBrainDataset{strconv.FormatInt(attch.ID, 10),
  906. attch.Attachment.Name,
  907. setting.Attachment.Minio.RealPath +
  908. setting.Attachment.Minio.Bucket + "/" +
  909. setting.Attachment.Minio.BasePath +
  910. models.AttachmentRelativePath(attch.UUID) +
  911. attch.UUID,
  912. attch.Name,
  913. attch.CreatedUnix.Format("2006-01-02 03:04:05 PM")})
  914. }
  915. data, err := json.Marshal(datasets)
  916. if err != nil {
  917. log.Error("json.Marshal failed:", err.Error())
  918. ctx.JSON(200, map[string]string{
  919. "result_code": "-1",
  920. "error_msg": err.Error(),
  921. "data": "",
  922. })
  923. return
  924. }
  925. ctx.JSON(200, map[string]string{
  926. "result_code": "0",
  927. "error_msg": "",
  928. "data": string(data),
  929. })
  930. return
  931. }
  932. func checkTypeCloudBrain(typeCloudBrain int) error {
  933. if typeCloudBrain != models.TypeCloudBrainOne && typeCloudBrain != models.TypeCloudBrainTwo {
  934. log.Error("type error:", typeCloudBrain)
  935. return errors.New("type error")
  936. }
  937. return nil
  938. }