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