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

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
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
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
3 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. url, err = storage.ObsGetPreSignedUrl(attach.UUID, attach.Name)
  273. if err != nil {
  274. ctx.ServerError("ObsGetPreSignedUrl", err)
  275. return
  276. }
  277. }
  278. }
  279. if err = increaseDownloadCount(attach, dataSet); err != nil {
  280. ctx.ServerError("Update", err)
  281. return
  282. }
  283. if dataSet != nil {
  284. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  285. } else {
  286. fr, err := storage.Attachments.Open(attach.RelativePath())
  287. if err != nil {
  288. ctx.ServerError("Open", err)
  289. return
  290. }
  291. defer fr.Close()
  292. if err = ServeData(ctx, attach.Name, fr); err != nil {
  293. ctx.ServerError("ServeData", err)
  294. return
  295. }
  296. }
  297. } else {
  298. fr, err := storage.Attachments.Open(attach.RelativePath())
  299. if err != nil {
  300. ctx.ServerError("Open", err)
  301. return
  302. }
  303. defer fr.Close()
  304. if err = increaseDownloadCount(attach, dataSet); err != nil {
  305. ctx.ServerError("Update", err)
  306. return
  307. }
  308. if err = ServeData(ctx, attach.Name, fr); err != nil {
  309. ctx.ServerError("ServeData", err)
  310. return
  311. }
  312. }
  313. }
  314. func increaseDownloadCount(attach *models.Attachment, dataSet *models.Dataset) error {
  315. if err := attach.IncreaseDownloadCount(); err != nil {
  316. return err
  317. }
  318. if dataSet != nil {
  319. if err := models.IncreaseDownloadCount(dataSet.ID); err != nil {
  320. return err
  321. }
  322. }
  323. return nil
  324. }
  325. // Get a presigned url for put object
  326. func GetPresignedPutObjectURL(ctx *context.Context) {
  327. if !setting.Attachment.Enabled {
  328. ctx.Error(404, "attachment is not enabled")
  329. return
  330. }
  331. err := upload.VerifyFileType(ctx.Params("file_type"), strings.Split(setting.Attachment.AllowedTypes, ","))
  332. if err != nil {
  333. ctx.Error(400, err.Error())
  334. return
  335. }
  336. if setting.Attachment.StoreType == storage.MinioStorageType {
  337. uuid := gouuid.NewV4().String()
  338. url, err := storage.Attachments.PresignedPutURL(models.AttachmentRelativePath(uuid))
  339. if err != nil {
  340. ctx.ServerError("PresignedPutURL", err)
  341. return
  342. }
  343. ctx.JSON(200, map[string]string{
  344. "uuid": uuid,
  345. "url": url,
  346. })
  347. } else {
  348. ctx.Error(404, "storage type is not enabled")
  349. return
  350. }
  351. }
  352. // AddAttachment response for add attachment record
  353. func AddAttachment(ctx *context.Context) {
  354. typeCloudBrain := ctx.QueryInt("type")
  355. fileName := ctx.Query("file_name")
  356. err := checkTypeCloudBrain(typeCloudBrain)
  357. if err != nil {
  358. ctx.ServerError("checkTypeCloudBrain failed", err)
  359. return
  360. }
  361. uuid := ctx.Query("uuid")
  362. has := false
  363. if typeCloudBrain == models.TypeCloudBrainOne {
  364. has, err = storage.Attachments.HasObject(models.AttachmentRelativePath(uuid))
  365. if err != nil {
  366. ctx.ServerError("HasObject", err)
  367. return
  368. }
  369. } else {
  370. has, err = storage.ObsHasObject(setting.BasePath + models.AttachmentRelativePath(uuid) + "/" + fileName)
  371. if err != nil {
  372. ctx.ServerError("ObsHasObject", err)
  373. return
  374. }
  375. }
  376. if !has {
  377. ctx.Error(404, "attachment has not been uploaded")
  378. return
  379. }
  380. datasetId := ctx.QueryInt64("dataset_id")
  381. dataset, err := models.GetDatasetByID(datasetId)
  382. if err != nil {
  383. ctx.Error(404, "dataset does not exist.")
  384. return
  385. }
  386. attachment, err := models.InsertAttachment(&models.Attachment{
  387. UUID: uuid,
  388. UploaderID: ctx.User.ID,
  389. IsPrivate: dataset.IsPrivate(),
  390. Name: fileName,
  391. Size: ctx.QueryInt64("size"),
  392. DatasetID: ctx.QueryInt64("dataset_id"),
  393. Type: typeCloudBrain,
  394. })
  395. if err != nil {
  396. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  397. return
  398. }
  399. if attachment.DatasetID != 0 {
  400. if isCanDecompress(attachment.Name) {
  401. if typeCloudBrain == models.TypeCloudBrainOne {
  402. err = worker.SendDecompressTask(contexExt.Background(), uuid, attachment.Name)
  403. if err != nil {
  404. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  405. } else {
  406. attachment.DecompressState = models.DecompressStateIng
  407. err = models.UpdateAttachment(attachment)
  408. if err != nil {
  409. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  410. }
  411. }
  412. }
  413. //todo:decompress type_two
  414. }
  415. }
  416. ctx.JSON(200, map[string]string{
  417. "result_code": "0",
  418. })
  419. }
  420. func isCanDecompress(name string) bool {
  421. if strings.HasSuffix(name, ".zip") || strings.HasSuffix(name, ".tar.gz") || strings.HasSuffix(name, ".tgz") {
  422. return true
  423. }
  424. return false
  425. }
  426. func UpdateAttachmentDecompressState(ctx *context.Context) {
  427. uuid := ctx.Query("uuid")
  428. result := ctx.Query("result")
  429. attach, err := models.GetAttachmentByUUID(uuid)
  430. if err != nil {
  431. log.Error("GetAttachmentByUUID(%s) failed:%s", uuid, err.Error())
  432. return
  433. }
  434. if result == DecompressSuccess {
  435. attach.DecompressState = models.DecompressStateDone
  436. } else if result == DecompressFailed {
  437. attach.DecompressState = models.DecompressStateFailed
  438. } else {
  439. log.Error("result is error:", result)
  440. return
  441. }
  442. err = models.UpdateAttachment(attach)
  443. if err != nil {
  444. log.Error("UpdateAttachment(%s) failed:%s", uuid, err.Error())
  445. return
  446. }
  447. log.Info("start to send msg to labelsystem ")
  448. dataset, _ := models.GetDatasetByID(attach.DatasetID)
  449. var labelMap map[string]string
  450. labelMap = make(map[string]string)
  451. labelMap["UUID"] = uuid
  452. labelMap["Type"] = fmt.Sprint(attach.Type)
  453. labelMap["UploaderID"] = fmt.Sprint(attach.UploaderID)
  454. labelMap["RepoID"] = fmt.Sprint(dataset.RepoID)
  455. labelMap["AttachName"] = attach.Name
  456. attachjson, _ := json.Marshal(labelMap)
  457. labelmsg.SendAddAttachToLabelSys(string(attachjson))
  458. log.Info("end to send msg to labelsystem ")
  459. ctx.JSON(200, map[string]string{
  460. "result_code": "0",
  461. })
  462. }
  463. func GetSuccessChunks(ctx *context.Context) {
  464. fileMD5 := ctx.Query("md5")
  465. typeCloudBrain := ctx.QueryInt("type")
  466. fileName := ctx.Query("file_name")
  467. var chunks string
  468. err := checkTypeCloudBrain(typeCloudBrain)
  469. if err != nil {
  470. ctx.ServerError("checkTypeCloudBrain failed", err)
  471. return
  472. }
  473. fileChunk, err := models.GetFileChunkByMD5AndUser(fileMD5, ctx.User.ID, typeCloudBrain)
  474. if err != nil {
  475. if models.IsErrFileChunkNotExist(err) {
  476. ctx.JSON(200, map[string]string{
  477. "uuid": "",
  478. "uploaded": "0",
  479. "uploadID": "",
  480. "chunks": "",
  481. })
  482. } else {
  483. ctx.ServerError("GetFileChunkByMD5", err)
  484. }
  485. return
  486. }
  487. isExist := false
  488. if typeCloudBrain == models.TypeCloudBrainOne {
  489. isExist, err = storage.Attachments.HasObject(models.AttachmentRelativePath(fileChunk.UUID))
  490. if err != nil {
  491. ctx.ServerError("HasObject failed", err)
  492. return
  493. }
  494. } else {
  495. oldFileName := fileName
  496. oldAttachment, _ := models.GetAttachmentByUUID(fileChunk.UUID)
  497. if oldAttachment != nil {
  498. oldFileName = oldAttachment.Name
  499. }
  500. isExist, err = storage.ObsHasObject(setting.BasePath + models.AttachmentRelativePath(fileChunk.UUID) + "/" + oldFileName)
  501. if err != nil {
  502. ctx.ServerError("ObsHasObject failed", err)
  503. return
  504. }
  505. }
  506. if isExist {
  507. if fileChunk.IsUploaded == models.FileNotUploaded {
  508. log.Info("the file has been uploaded but not recorded")
  509. fileChunk.IsUploaded = models.FileUploaded
  510. if err = models.UpdateFileChunk(fileChunk); err != nil {
  511. log.Error("UpdateFileChunk failed:", err.Error())
  512. }
  513. }
  514. } else {
  515. if fileChunk.IsUploaded == models.FileUploaded {
  516. log.Info("the file has been recorded but not uploaded")
  517. fileChunk.IsUploaded = models.FileNotUploaded
  518. if err = models.UpdateFileChunk(fileChunk); err != nil {
  519. log.Error("UpdateFileChunk failed:", err.Error())
  520. }
  521. }
  522. if typeCloudBrain == models.TypeCloudBrainOne {
  523. chunks, err = storage.GetPartInfos(fileChunk.UUID, fileChunk.UploadID)
  524. if err != nil {
  525. log.Error("GetPartInfos failed:%v", err.Error())
  526. }
  527. } else {
  528. chunks, err = storage.GetObsPartInfos(fileChunk.UUID, fileChunk.UploadID, fileName)
  529. if err != nil {
  530. log.Error("GetObsPartInfos failed:%v", err.Error())
  531. }
  532. }
  533. if err != nil {
  534. models.DeleteFileChunk(fileChunk)
  535. ctx.JSON(200, map[string]string{
  536. "uuid": "",
  537. "uploaded": "0",
  538. "uploadID": "",
  539. "chunks": "",
  540. })
  541. return
  542. }
  543. }
  544. var attachID int64
  545. attach, err := models.GetAttachmentByUUID(fileChunk.UUID)
  546. if err != nil {
  547. if models.IsErrAttachmentNotExist(err) {
  548. attachID = 0
  549. } else {
  550. ctx.ServerError("GetAttachmentByUUID", err)
  551. return
  552. }
  553. } else {
  554. attachID = attach.ID
  555. }
  556. if attach == nil {
  557. ctx.JSON(200, map[string]string{
  558. "uuid": fileChunk.UUID,
  559. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  560. "uploadID": fileChunk.UploadID,
  561. "chunks": string(chunks),
  562. "attachID": "0",
  563. "datasetID": "0",
  564. "fileName": "",
  565. "datasetName": "",
  566. })
  567. return
  568. }
  569. dataset, err := models.GetDatasetByID(attach.DatasetID)
  570. if err != nil {
  571. ctx.ServerError("GetDatasetByID", err)
  572. return
  573. }
  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": strconv.Itoa(int(attachID)),
  580. "datasetID": strconv.Itoa(int(attach.DatasetID)),
  581. "fileName": attach.Name,
  582. "datasetName": dataset.Title,
  583. })
  584. }
  585. func NewMultipart(ctx *context.Context) {
  586. if !setting.Attachment.Enabled {
  587. ctx.Error(404, "attachment is not enabled")
  588. return
  589. }
  590. err := upload.VerifyFileType(ctx.Query("fileType"), strings.Split(setting.Attachment.AllowedTypes, ","))
  591. if err != nil {
  592. ctx.Error(400, err.Error())
  593. return
  594. }
  595. typeCloudBrain := ctx.QueryInt("type")
  596. err = checkTypeCloudBrain(typeCloudBrain)
  597. if err != nil {
  598. ctx.ServerError("checkTypeCloudBrain failed", err)
  599. return
  600. }
  601. fileName := ctx.Query("file_name")
  602. if setting.Attachment.StoreType == storage.MinioStorageType {
  603. totalChunkCounts := ctx.QueryInt("totalChunkCounts")
  604. if totalChunkCounts > minio_ext.MaxPartsCount {
  605. ctx.Error(400, fmt.Sprintf("chunk counts(%d) is too much", totalChunkCounts))
  606. return
  607. }
  608. fileSize := ctx.QueryInt64("size")
  609. if fileSize > minio_ext.MaxMultipartPutObjectSize {
  610. ctx.Error(400, fmt.Sprintf("file size(%d) is too big", fileSize))
  611. return
  612. }
  613. uuid := gouuid.NewV4().String()
  614. var uploadID string
  615. if typeCloudBrain == models.TypeCloudBrainOne {
  616. uploadID, err = storage.NewMultiPartUpload(uuid)
  617. if err != nil {
  618. ctx.ServerError("NewMultipart", err)
  619. return
  620. }
  621. } else {
  622. uploadID, err = storage.NewObsMultiPartUpload(uuid, fileName)
  623. if err != nil {
  624. ctx.ServerError("NewObsMultiPartUpload", err)
  625. return
  626. }
  627. }
  628. _, err = models.InsertFileChunk(&models.FileChunk{
  629. UUID: uuid,
  630. UserID: ctx.User.ID,
  631. UploadID: uploadID,
  632. Md5: ctx.Query("md5"),
  633. Size: fileSize,
  634. TotalChunks: totalChunkCounts,
  635. Type: typeCloudBrain,
  636. })
  637. if err != nil {
  638. ctx.Error(500, fmt.Sprintf("InsertFileChunk: %v", err))
  639. return
  640. }
  641. ctx.JSON(200, map[string]string{
  642. "uuid": uuid,
  643. "uploadID": uploadID,
  644. })
  645. } else {
  646. ctx.Error(404, "storage type is not enabled")
  647. return
  648. }
  649. }
  650. func PutOBSProxyUpload(ctx *context.Context) {
  651. uuid := ctx.Query("uuid")
  652. uploadID := ctx.Query("uploadId")
  653. partNumber := ctx.QueryInt("partNumber")
  654. fileName := ctx.Query("file_name")
  655. RequestBody := ctx.Req.Body()
  656. if RequestBody == nil {
  657. ctx.Error(500, fmt.Sprintf("FormFile: %v", RequestBody))
  658. return
  659. }
  660. err := storage.ObsMultiPartUpload(uuid, uploadID, partNumber, fileName, RequestBody.ReadCloser())
  661. if err != nil {
  662. log.Info("upload error.")
  663. }
  664. }
  665. func GetOBSProxyDownload(ctx *context.Context) {
  666. uuid := ctx.Query("uuid")
  667. fileName := ctx.Query("file_name")
  668. body, err := storage.ObsDownload(uuid, fileName)
  669. if err != nil {
  670. log.Info("upload error.")
  671. } else {
  672. defer body.Close()
  673. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  674. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  675. p := make([]byte, 1024)
  676. var readErr error
  677. var readCount int
  678. // 读取对象内容
  679. for {
  680. readCount, readErr = body.Read(p)
  681. if readCount > 0 {
  682. ctx.Resp.Write(p[:readCount])
  683. //fmt.Printf("%s", p[:readCount])
  684. }
  685. if readErr != nil {
  686. break
  687. }
  688. }
  689. }
  690. }
  691. func GetMultipartUploadUrl(ctx *context.Context) {
  692. uuid := ctx.Query("uuid")
  693. uploadID := ctx.Query("uploadID")
  694. partNumber := ctx.QueryInt("chunkNumber")
  695. size := ctx.QueryInt64("size")
  696. fileName := ctx.Query("file_name")
  697. typeCloudBrain := ctx.QueryInt("type")
  698. err := checkTypeCloudBrain(typeCloudBrain)
  699. if err != nil {
  700. ctx.ServerError("checkTypeCloudBrain failed", err)
  701. return
  702. }
  703. url := ""
  704. if typeCloudBrain == models.TypeCloudBrainOne {
  705. if size > minio_ext.MinPartSize {
  706. ctx.Error(400, fmt.Sprintf("chunk size(%d) is too big", size))
  707. return
  708. }
  709. url, err = storage.GenMultiPartSignedUrl(uuid, uploadID, partNumber, size)
  710. if err != nil {
  711. ctx.Error(500, fmt.Sprintf("GenMultiPartSignedUrl failed: %v", err))
  712. return
  713. }
  714. } else {
  715. if setting.PROXYURL != "" {
  716. url = setting.PROXYURL + "/obs_proxy_multipart?uuid=" + uuid + "&uploadId=" + uploadID + "&partNumber=" + fmt.Sprint(partNumber) + "&file_name=" + fileName
  717. log.Info("return url=" + url)
  718. } else {
  719. url, err = storage.ObsGenMultiPartSignedUrl(uuid, uploadID, partNumber, fileName)
  720. if err != nil {
  721. ctx.Error(500, fmt.Sprintf("ObsGenMultiPartSignedUrl failed: %v", err))
  722. return
  723. }
  724. log.Info("url=" + url)
  725. }
  726. }
  727. ctx.JSON(200, map[string]string{
  728. "url": url,
  729. })
  730. }
  731. func GetObsKey(ctx *context.Context) {
  732. uuid := gouuid.NewV4().String()
  733. key := strings.TrimPrefix(path.Join(setting.BasePath, path.Join(uuid[0:1], uuid[1:2], uuid, uuid)), "/")
  734. ctx.JSON(200, map[string]string{
  735. "uuid": uuid,
  736. "key": key,
  737. "access_key_id": setting.AccessKeyID,
  738. "secret_access_key": setting.SecretAccessKey,
  739. "server": setting.Endpoint,
  740. "bucket": setting.Bucket,
  741. })
  742. }
  743. func CompleteMultipart(ctx *context.Context) {
  744. uuid := ctx.Query("uuid")
  745. uploadID := ctx.Query("uploadID")
  746. typeCloudBrain := ctx.QueryInt("type")
  747. fileName := ctx.Query("file_name")
  748. log.Warn("uuid:" + uuid)
  749. log.Warn("typeCloudBrain:" + strconv.Itoa(typeCloudBrain))
  750. err := checkTypeCloudBrain(typeCloudBrain)
  751. if err != nil {
  752. ctx.ServerError("checkTypeCloudBrain failed", err)
  753. return
  754. }
  755. fileChunk, err := models.GetFileChunkByUUID(uuid)
  756. if err != nil {
  757. if models.IsErrFileChunkNotExist(err) {
  758. ctx.Error(404)
  759. } else {
  760. ctx.ServerError("GetFileChunkByUUID", err)
  761. }
  762. return
  763. }
  764. if typeCloudBrain == models.TypeCloudBrainOne {
  765. _, err = storage.CompleteMultiPartUpload(uuid, uploadID)
  766. if err != nil {
  767. ctx.Error(500, fmt.Sprintf("CompleteMultiPartUpload failed: %v", err))
  768. return
  769. }
  770. } else {
  771. err = storage.CompleteObsMultiPartUpload(uuid, uploadID, fileName)
  772. if err != nil {
  773. ctx.Error(500, fmt.Sprintf("CompleteObsMultiPartUpload failed: %v", err))
  774. return
  775. }
  776. }
  777. fileChunk.IsUploaded = models.FileUploaded
  778. err = models.UpdateFileChunk(fileChunk)
  779. if err != nil {
  780. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  781. return
  782. }
  783. dataset, _ := models.GetDatasetByID(ctx.QueryInt64("dataset_id"))
  784. log.Warn("insert attachment to datasetId:" + strconv.FormatInt(dataset.ID, 10))
  785. attachment, err := models.InsertAttachment(&models.Attachment{
  786. UUID: uuid,
  787. UploaderID: ctx.User.ID,
  788. IsPrivate: dataset.IsPrivate(),
  789. Name: fileName,
  790. Size: ctx.QueryInt64("size"),
  791. DatasetID: ctx.QueryInt64("dataset_id"),
  792. Description: ctx.Query("description"),
  793. Type: typeCloudBrain,
  794. })
  795. if err != nil {
  796. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  797. return
  798. }
  799. repository, _ := models.GetRepositoryByID(dataset.RepoID)
  800. notification.NotifyOtherTask(ctx.User, repository, fmt.Sprint(attachment.Type), attachment.Name, models.ActionUploadAttachment)
  801. if attachment.DatasetID != 0 {
  802. if isCanDecompress(attachment.Name) {
  803. if typeCloudBrain == models.TypeCloudBrainOne {
  804. err = worker.SendDecompressTask(contexExt.Background(), uuid, attachment.Name)
  805. if err != nil {
  806. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  807. } else {
  808. attachment.DecompressState = models.DecompressStateIng
  809. err = models.UpdateAttachment(attachment)
  810. if err != nil {
  811. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  812. }
  813. }
  814. }
  815. if typeCloudBrain == models.TypeCloudBrainTwo {
  816. attachjson, _ := json.Marshal(attachment)
  817. labelmsg.SendDecompressAttachToLabelOBS(string(attachjson))
  818. }
  819. } else {
  820. var labelMap map[string]string
  821. labelMap = make(map[string]string)
  822. labelMap["UUID"] = uuid
  823. labelMap["Type"] = fmt.Sprint(attachment.Type)
  824. labelMap["UploaderID"] = fmt.Sprint(attachment.UploaderID)
  825. labelMap["RepoID"] = fmt.Sprint(dataset.RepoID)
  826. labelMap["AttachName"] = attachment.Name
  827. attachjson, _ := json.Marshal(labelMap)
  828. labelmsg.SendAddAttachToLabelSys(string(attachjson))
  829. }
  830. }
  831. ctx.JSON(200, map[string]string{
  832. "result_code": "0",
  833. })
  834. }
  835. func UpdateMultipart(ctx *context.Context) {
  836. uuid := ctx.Query("uuid")
  837. partNumber := ctx.QueryInt("chunkNumber")
  838. etag := ctx.Query("etag")
  839. fileChunk, err := models.GetFileChunkByUUID(uuid)
  840. if err != nil {
  841. if models.IsErrFileChunkNotExist(err) {
  842. ctx.Error(404)
  843. } else {
  844. ctx.ServerError("GetFileChunkByUUID", err)
  845. }
  846. return
  847. }
  848. fileChunk.CompletedParts = append(fileChunk.CompletedParts, strconv.Itoa(partNumber)+"-"+strings.Replace(etag, "\"", "", -1))
  849. err = models.UpdateFileChunk(fileChunk)
  850. if err != nil {
  851. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  852. return
  853. }
  854. ctx.JSON(200, map[string]string{
  855. "result_code": "0",
  856. })
  857. }
  858. func HandleUnDecompressAttachment() {
  859. attachs, err := models.GetUnDecompressAttachments()
  860. if err != nil {
  861. log.Error("GetUnDecompressAttachments failed:", err.Error())
  862. return
  863. }
  864. for _, attach := range attachs {
  865. if attach.Type == models.TypeCloudBrainOne {
  866. err = worker.SendDecompressTask(contexExt.Background(), attach.UUID, attach.Name)
  867. if err != nil {
  868. log.Error("SendDecompressTask(%s) failed:%s", attach.UUID, err.Error())
  869. } else {
  870. updateAttachmentDecompressStateIng(attach)
  871. }
  872. } else if attach.Type == models.TypeCloudBrainTwo {
  873. attachjson, _ := json.Marshal(attach)
  874. err = labelmsg.SendDecompressAttachToLabelOBS(string(attachjson))
  875. if err != nil {
  876. log.Error("SendDecompressTask to labelsystem (%s) failed:%s", attach.UUID, err.Error())
  877. } else {
  878. updateAttachmentDecompressStateIng(attach)
  879. }
  880. }
  881. }
  882. return
  883. }
  884. func updateAttachmentDecompressStateIng(attach *models.Attachment) {
  885. attach.DecompressState = models.DecompressStateIng
  886. err := models.UpdateAttachment(attach)
  887. if err != nil {
  888. log.Error("UpdateAttachment state(%s) failed:%s", attach.UUID, err.Error())
  889. }
  890. }
  891. func QueryAllPublicDataset(ctx *context.Context) {
  892. attachs, err := models.GetAllPublicAttachments()
  893. if err != nil {
  894. ctx.JSON(200, map[string]string{
  895. "result_code": "-1",
  896. "error_msg": err.Error(),
  897. "data": "",
  898. })
  899. return
  900. }
  901. queryDatasets(ctx, attachs)
  902. }
  903. func QueryPrivateDataset(ctx *context.Context) {
  904. username := ctx.Params(":username")
  905. attachs, err := models.GetPrivateAttachments(username)
  906. if err != nil {
  907. ctx.JSON(200, map[string]string{
  908. "result_code": "-1",
  909. "error_msg": err.Error(),
  910. "data": "",
  911. })
  912. return
  913. }
  914. for _, attach := range attachs {
  915. attach.Name = username
  916. }
  917. queryDatasets(ctx, attachs)
  918. }
  919. func queryDatasets(ctx *context.Context, attachs []*models.AttachmentUsername) {
  920. var datasets []CloudBrainDataset
  921. if len(attachs) == 0 {
  922. log.Info("dataset is null")
  923. ctx.JSON(200, map[string]string{
  924. "result_code": "0",
  925. "error_msg": "",
  926. "data": "",
  927. })
  928. return
  929. }
  930. for _, attch := range attachs {
  931. has, err := storage.Attachments.HasObject(models.AttachmentRelativePath(attch.UUID))
  932. if err != nil || !has {
  933. continue
  934. }
  935. datasets = append(datasets, CloudBrainDataset{strconv.FormatInt(attch.ID, 10),
  936. attch.Attachment.Name,
  937. setting.Attachment.Minio.RealPath +
  938. setting.Attachment.Minio.Bucket + "/" +
  939. setting.Attachment.Minio.BasePath +
  940. models.AttachmentRelativePath(attch.UUID) +
  941. attch.UUID,
  942. attch.Name,
  943. attch.CreatedUnix.Format("2006-01-02 03:04:05 PM")})
  944. }
  945. data, err := json.Marshal(datasets)
  946. if err != nil {
  947. log.Error("json.Marshal failed:", err.Error())
  948. ctx.JSON(200, map[string]string{
  949. "result_code": "-1",
  950. "error_msg": err.Error(),
  951. "data": "",
  952. })
  953. return
  954. }
  955. ctx.JSON(200, map[string]string{
  956. "result_code": "0",
  957. "error_msg": "",
  958. "data": string(data),
  959. })
  960. return
  961. }
  962. func checkTypeCloudBrain(typeCloudBrain int) error {
  963. if typeCloudBrain != models.TypeCloudBrainOne && typeCloudBrain != models.TypeCloudBrainTwo {
  964. log.Error("type error:", typeCloudBrain)
  965. return errors.New("type error")
  966. }
  967. return nil
  968. }