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

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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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. "fmt"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/minio_ext"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/storage"
  18. "code.gitea.io/gitea/modules/upload"
  19. "code.gitea.io/gitea/modules/worker"
  20. gouuid "github.com/satori/go.uuid"
  21. )
  22. const (
  23. //result of decompress
  24. DecompressSuccess = "0"
  25. DecompressFailed = "1"
  26. )
  27. type PublicDataset struct {
  28. Name string `json:"name"`
  29. Path string `json:"path"`
  30. }
  31. func RenderAttachmentSettings(ctx *context.Context) {
  32. renderAttachmentSettings(ctx)
  33. }
  34. func renderAttachmentSettings(ctx *context.Context) {
  35. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  36. ctx.Data["AttachmentStoreType"] = setting.Attachment.StoreType
  37. ctx.Data["AttachmentAllowedTypes"] = setting.Attachment.AllowedTypes
  38. ctx.Data["AttachmentMaxSize"] = setting.Attachment.MaxSize
  39. ctx.Data["AttachmentMaxFiles"] = setting.Attachment.MaxFiles
  40. }
  41. // UploadAttachment response for uploading issue's attachment
  42. func UploadAttachment(ctx *context.Context) {
  43. if !setting.Attachment.Enabled {
  44. ctx.Error(404, "attachment is not enabled")
  45. return
  46. }
  47. file, header, err := ctx.Req.FormFile("file")
  48. if err != nil {
  49. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  50. return
  51. }
  52. defer file.Close()
  53. buf := make([]byte, 1024)
  54. n, _ := file.Read(buf)
  55. if n > 0 {
  56. buf = buf[:n]
  57. }
  58. err = upload.VerifyAllowedContentType(buf, strings.Split(setting.Attachment.AllowedTypes, ","))
  59. if err != nil {
  60. ctx.Error(400, err.Error())
  61. return
  62. }
  63. datasetID, _ := strconv.ParseInt(ctx.Req.FormValue("dataset_id"), 10, 64)
  64. attach, err := models.NewAttachment(&models.Attachment{
  65. IsPrivate: true,
  66. UploaderID: ctx.User.ID,
  67. Name: header.Filename,
  68. DatasetID: datasetID,
  69. }, buf, file)
  70. if err != nil {
  71. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  72. return
  73. }
  74. log.Trace("New attachment uploaded: %s", attach.UUID)
  75. ctx.JSON(200, map[string]string{
  76. "uuid": attach.UUID,
  77. })
  78. }
  79. func UpdatePublicAttachment(ctx *context.Context) {
  80. file := ctx.Query("file")
  81. isPrivate, _ := strconv.ParseBool(ctx.Query("is_private"))
  82. attach, err := models.GetAttachmentByUUID(file)
  83. if err != nil {
  84. ctx.Error(404, err.Error())
  85. return
  86. }
  87. attach.IsPrivate = isPrivate
  88. models.UpdateAttachment(attach)
  89. }
  90. // DeleteAttachment response for deleting issue's attachment
  91. func DeleteAttachment(ctx *context.Context) {
  92. file := ctx.Query("file")
  93. attach, err := models.GetAttachmentByUUID(file)
  94. if err != nil {
  95. ctx.Error(400, err.Error())
  96. return
  97. }
  98. if !ctx.IsSigned || (ctx.User.ID != attach.UploaderID) {
  99. ctx.Error(403)
  100. return
  101. }
  102. err = models.DeleteAttachment(attach, false)
  103. if err != nil {
  104. ctx.Error(500, fmt.Sprintf("DeleteAttachment: %v", err))
  105. return
  106. }
  107. ctx.JSON(200, map[string]string{
  108. "uuid": attach.UUID,
  109. })
  110. }
  111. // GetAttachment serve attachements
  112. func GetAttachment(ctx *context.Context) {
  113. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  114. if err != nil {
  115. if models.IsErrAttachmentNotExist(err) {
  116. ctx.Error(404)
  117. } else {
  118. ctx.ServerError("GetAttachmentByUUID", err)
  119. }
  120. return
  121. }
  122. repository, unitType, err := attach.LinkedRepository()
  123. if err != nil {
  124. ctx.ServerError("LinkedRepository", err)
  125. return
  126. }
  127. if repository == nil { //If not linked
  128. if !(ctx.IsSigned && attach.UploaderID == ctx.User.ID) && attach.IsPrivate { //We block if not the uploader
  129. ctx.Error(http.StatusNotFound)
  130. return
  131. }
  132. } else { //If we have the repository we check access
  133. perm, err := models.GetUserRepoPermission(repository, ctx.User)
  134. if err != nil {
  135. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err.Error())
  136. return
  137. }
  138. if !perm.CanRead(unitType) {
  139. ctx.Error(http.StatusNotFound)
  140. return
  141. }
  142. }
  143. dataSet, err := attach.LinkedDataSet()
  144. if err != nil {
  145. ctx.ServerError("LinkedDataSet", err)
  146. return
  147. }
  148. if dataSet != nil {
  149. isPermit, err := models.GetUserDataSetPermission(dataSet, ctx.User)
  150. if err != nil {
  151. ctx.Error(http.StatusInternalServerError, "GetUserDataSetPermission", err.Error())
  152. return
  153. }
  154. if !isPermit {
  155. ctx.Error(http.StatusNotFound)
  156. return
  157. }
  158. }
  159. //If we have matched and access to release or issue
  160. if setting.Attachment.StoreType == storage.MinioStorageType {
  161. url, err := storage.Attachments.PresignedGetURL(attach.RelativePath(), attach.Name)
  162. if err != nil {
  163. ctx.ServerError("PresignedGetURL", err)
  164. return
  165. }
  166. if err = increaseDownloadCount(attach, dataSet); err != nil {
  167. ctx.ServerError("Update", err)
  168. return
  169. }
  170. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  171. } else {
  172. fr, err := storage.Attachments.Open(attach.RelativePath())
  173. if err != nil {
  174. ctx.ServerError("Open", err)
  175. return
  176. }
  177. defer fr.Close()
  178. if err = increaseDownloadCount(attach, dataSet); err != nil {
  179. ctx.ServerError("Update", err)
  180. return
  181. }
  182. if err = ServeData(ctx, attach.Name, fr); err != nil {
  183. ctx.ServerError("ServeData", err)
  184. return
  185. }
  186. }
  187. }
  188. func increaseDownloadCount(attach *models.Attachment, dataSet *models.Dataset) error {
  189. if err := attach.IncreaseDownloadCount(); err != nil {
  190. return err
  191. }
  192. if dataSet != nil {
  193. if err := models.IncreaseDownloadCount(dataSet.ID); err != nil {
  194. return err
  195. }
  196. }
  197. return nil
  198. }
  199. // Get a presigned url for put object
  200. func GetPresignedPutObjectURL(ctx *context.Context) {
  201. if !setting.Attachment.Enabled {
  202. ctx.Error(404, "attachment is not enabled")
  203. return
  204. }
  205. err := upload.VerifyFileType(ctx.Params("file_type"), strings.Split(setting.Attachment.AllowedTypes, ","))
  206. if err != nil {
  207. ctx.Error(400, err.Error())
  208. return
  209. }
  210. if setting.Attachment.StoreType == storage.MinioStorageType {
  211. uuid := gouuid.NewV4().String()
  212. url, err := storage.Attachments.PresignedPutURL(models.AttachmentRelativePath(uuid))
  213. if err != nil {
  214. ctx.ServerError("PresignedPutURL", err)
  215. return
  216. }
  217. ctx.JSON(200, map[string]string{
  218. "uuid": uuid,
  219. "url": url,
  220. })
  221. } else {
  222. ctx.Error(404, "storage type is not enabled")
  223. return
  224. }
  225. }
  226. // AddAttachment response for add attachment record
  227. func AddAttachment(ctx *context.Context) {
  228. uuid := ctx.Query("uuid")
  229. has, err := storage.Attachments.HasObject(models.AttachmentRelativePath(uuid))
  230. if err != nil {
  231. ctx.ServerError("HasObject", err)
  232. return
  233. }
  234. if !has {
  235. ctx.Error(404, "attachment has not been uploaded")
  236. return
  237. }
  238. attachment, err := models.InsertAttachment(&models.Attachment{
  239. UUID: uuid,
  240. UploaderID: ctx.User.ID,
  241. IsPrivate: true,
  242. Name: ctx.Query("file_name"),
  243. Size: ctx.QueryInt64("size"),
  244. DatasetID: ctx.QueryInt64("dataset_id"),
  245. })
  246. if err != nil {
  247. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  248. return
  249. }
  250. if attachment.DatasetID != 0 {
  251. if strings.HasSuffix(attachment.Name, ".zip") {
  252. err = worker.SendDecompressTask(contexExt.Background(), uuid)
  253. if err != nil {
  254. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  255. } else {
  256. attachment.DecompressState = models.DecompressStateIng
  257. err = models.UpdateAttachment(attachment)
  258. if err != nil {
  259. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  260. }
  261. }
  262. }
  263. }
  264. ctx.JSON(200, map[string]string{
  265. "result_code": "0",
  266. })
  267. }
  268. func UpdateAttachmentDecompressState(ctx *context.Context) {
  269. uuid := ctx.Query("uuid")
  270. result := ctx.Query("result")
  271. attach, err := models.GetAttachmentByUUID(uuid)
  272. if err != nil {
  273. log.Error("GetAttachmentByUUID(%s) failed:%s", uuid, err.Error())
  274. return
  275. }
  276. if result == DecompressSuccess {
  277. attach.DecompressState = models.DecompressStateDone
  278. } else if result == DecompressFailed {
  279. attach.DecompressState = models.DecompressStateFailed
  280. } else {
  281. log.Error("result is error:", result)
  282. return
  283. }
  284. err = models.UpdateAttachment(attach)
  285. if err != nil {
  286. log.Error("UpdateAttachment(%s) failed:%s", uuid, err.Error())
  287. return
  288. }
  289. ctx.JSON(200, map[string]string{
  290. "result_code": "0",
  291. })
  292. }
  293. func GetSuccessChunks(ctx *context.Context) {
  294. fileMD5 := ctx.Query("md5")
  295. var chunks string
  296. fileChunk, err := models.GetFileChunkByMD5AndUser(fileMD5, ctx.User.ID)
  297. if err != nil {
  298. if models.IsErrFileChunkNotExist(err) {
  299. ctx.JSON(200, map[string]string{
  300. "uuid": "",
  301. "uploaded": "0",
  302. "uploadID": "",
  303. "chunks": "",
  304. })
  305. } else {
  306. ctx.ServerError("GetFileChunkByMD5", err)
  307. }
  308. return
  309. }
  310. isExist, err := storage.Attachments.HasObject(models.AttachmentRelativePath(fileChunk.UUID))
  311. if err != nil {
  312. ctx.ServerError("HasObject failed", err)
  313. return
  314. }
  315. if isExist {
  316. if fileChunk.IsUploaded == models.FileNotUploaded {
  317. log.Info("the file has been uploaded but not recorded")
  318. fileChunk.IsUploaded = models.FileUploaded
  319. if err = models.UpdateFileChunk(fileChunk); err != nil {
  320. log.Error("UpdateFileChunk failed:", err.Error())
  321. }
  322. }
  323. } else {
  324. if fileChunk.IsUploaded == models.FileUploaded {
  325. log.Info("the file has been recorded but not uploaded")
  326. fileChunk.IsUploaded = models.FileNotUploaded
  327. if err = models.UpdateFileChunk(fileChunk); err != nil {
  328. log.Error("UpdateFileChunk failed:", err.Error())
  329. }
  330. }
  331. chunks, err = storage.GetPartInfos(fileChunk.UUID, fileChunk.UploadID)
  332. if err != nil {
  333. ctx.ServerError("GetPartInfos failed", err)
  334. return
  335. }
  336. }
  337. var attachID int64
  338. attach, err := models.GetAttachmentByUUID(fileChunk.UUID)
  339. if err != nil {
  340. if models.IsErrAttachmentNotExist(err) {
  341. attachID = 0
  342. } else {
  343. ctx.ServerError("GetAttachmentByUUID", err)
  344. return
  345. }
  346. } else {
  347. attachID = attach.ID
  348. }
  349. dataset, err := models.GetDatasetByID(attach.DatasetID)
  350. if err != nil {
  351. ctx.ServerError("GetDatasetByID", err)
  352. return
  353. }
  354. ctx.JSON(200, map[string]string{
  355. "uuid": fileChunk.UUID,
  356. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  357. "uploadID": fileChunk.UploadID,
  358. "chunks": string(chunks),
  359. "attachID": strconv.Itoa(int(attachID)),
  360. "datasetID": strconv.Itoa(int(attach.DatasetID)),
  361. "fileName": attach.Name,
  362. "datasetName": dataset.Title,
  363. })
  364. }
  365. func NewMultipart(ctx *context.Context) {
  366. if !setting.Attachment.Enabled {
  367. ctx.Error(404, "attachment is not enabled")
  368. return
  369. }
  370. err := upload.VerifyFileType(ctx.Query("fileType"), strings.Split(setting.Attachment.AllowedTypes, ","))
  371. if err != nil {
  372. ctx.Error(400, err.Error())
  373. return
  374. }
  375. if setting.Attachment.StoreType == storage.MinioStorageType {
  376. totalChunkCounts := ctx.QueryInt("totalChunkCounts")
  377. if totalChunkCounts > minio_ext.MaxPartsCount {
  378. ctx.Error(400, fmt.Sprintf("chunk counts(%d) is too much", totalChunkCounts))
  379. return
  380. }
  381. fileSize := ctx.QueryInt64("size")
  382. if fileSize > minio_ext.MaxMultipartPutObjectSize {
  383. ctx.Error(400, fmt.Sprintf("file size(%d) is too big", fileSize))
  384. return
  385. }
  386. uuid := gouuid.NewV4().String()
  387. uploadID, err := storage.NewMultiPartUpload(uuid)
  388. if err != nil {
  389. ctx.ServerError("NewMultipart", err)
  390. return
  391. }
  392. _, err = models.InsertFileChunk(&models.FileChunk{
  393. UUID: uuid,
  394. UserID: ctx.User.ID,
  395. UploadID: uploadID,
  396. Md5: ctx.Query("md5"),
  397. Size: fileSize,
  398. TotalChunks: totalChunkCounts,
  399. })
  400. if err != nil {
  401. ctx.Error(500, fmt.Sprintf("InsertFileChunk: %v", err))
  402. return
  403. }
  404. ctx.JSON(200, map[string]string{
  405. "uuid": uuid,
  406. "uploadID": uploadID,
  407. })
  408. } else {
  409. ctx.Error(404, "storage type is not enabled")
  410. return
  411. }
  412. }
  413. func GetMultipartUploadUrl(ctx *context.Context) {
  414. uuid := ctx.Query("uuid")
  415. uploadID := ctx.Query("uploadID")
  416. partNumber := ctx.QueryInt("chunkNumber")
  417. size := ctx.QueryInt64("size")
  418. if size > minio_ext.MinPartSize {
  419. ctx.Error(400, fmt.Sprintf("chunk size(%d) is too big", size))
  420. return
  421. }
  422. url, err := storage.GenMultiPartSignedUrl(uuid, uploadID, partNumber, size)
  423. if err != nil {
  424. ctx.Error(500, fmt.Sprintf("GenMultiPartSignedUrl failed: %v", err))
  425. return
  426. }
  427. ctx.JSON(200, map[string]string{
  428. "url": url,
  429. })
  430. }
  431. func CompleteMultipart(ctx *context.Context) {
  432. uuid := ctx.Query("uuid")
  433. uploadID := ctx.Query("uploadID")
  434. fileChunk, err := models.GetFileChunkByUUID(uuid)
  435. if err != nil {
  436. if models.IsErrFileChunkNotExist(err) {
  437. ctx.Error(404)
  438. } else {
  439. ctx.ServerError("GetFileChunkByUUID", err)
  440. }
  441. return
  442. }
  443. _, err = storage.CompleteMultiPartUpload(uuid, uploadID)
  444. if err != nil {
  445. ctx.Error(500, fmt.Sprintf("CompleteMultiPartUpload failed: %v", err))
  446. return
  447. }
  448. fileChunk.IsUploaded = models.FileUploaded
  449. err = models.UpdateFileChunk(fileChunk)
  450. if err != nil {
  451. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  452. return
  453. }
  454. attachment, err := models.InsertAttachment(&models.Attachment{
  455. UUID: uuid,
  456. UploaderID: ctx.User.ID,
  457. IsPrivate: true,
  458. Name: ctx.Query("file_name"),
  459. Size: ctx.QueryInt64("size"),
  460. DatasetID: ctx.QueryInt64("dataset_id"),
  461. })
  462. if err != nil {
  463. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  464. return
  465. }
  466. if attachment.DatasetID != 0 {
  467. if strings.HasSuffix(attachment.Name, ".zip") {
  468. err = worker.SendDecompressTask(contexExt.Background(), uuid)
  469. if err != nil {
  470. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  471. } else {
  472. attachment.DecompressState = models.DecompressStateIng
  473. err = models.UpdateAttachment(attachment)
  474. if err != nil {
  475. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  476. }
  477. }
  478. }
  479. }
  480. ctx.JSON(200, map[string]string{
  481. "result_code": "0",
  482. })
  483. }
  484. func UpdateMultipart(ctx *context.Context) {
  485. uuid := ctx.Query("uuid")
  486. partNumber := ctx.QueryInt("chunkNumber")
  487. etag := ctx.Query("etag")
  488. fileChunk, err := models.GetFileChunkByUUID(uuid)
  489. if err != nil {
  490. if models.IsErrFileChunkNotExist(err) {
  491. ctx.Error(404)
  492. } else {
  493. ctx.ServerError("GetFileChunkByUUID", err)
  494. }
  495. return
  496. }
  497. fileChunk.CompletedParts = append(fileChunk.CompletedParts, strconv.Itoa(partNumber)+"-"+strings.Replace(etag, "\"", "", -1))
  498. err = models.UpdateFileChunk(fileChunk)
  499. if err != nil {
  500. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  501. return
  502. }
  503. ctx.JSON(200, map[string]string{
  504. "result_code": "0",
  505. })
  506. }
  507. func HandleUnDecompressAttachment() {
  508. attachs, err := models.GetUnDecompressAttachments()
  509. if err != nil {
  510. log.Error("GetUnDecompressAttachments failed:", err.Error())
  511. return
  512. }
  513. for _, attach := range attachs {
  514. err = worker.SendDecompressTask(contexExt.Background(), attach.UUID)
  515. if err != nil {
  516. log.Error("SendDecompressTask(%s) failed:%s", attach.UUID, err.Error())
  517. } else {
  518. attach.DecompressState = models.DecompressStateIng
  519. err = models.UpdateAttachment(attach)
  520. if err != nil {
  521. log.Error("UpdateAttachment state(%s) failed:%s", attach.UUID, err.Error())
  522. }
  523. }
  524. }
  525. return
  526. }
  527. func QueryAllPublicDataset(ctx *context.Context){
  528. attachs, err := models.GetAllPublicAttachments()
  529. if err != nil {
  530. ctx.JSON(200, map[string]string{
  531. "result_code": "-1",
  532. "data": "",
  533. })
  534. return
  535. }
  536. var publicDatasets []PublicDataset
  537. for _, attch := range attachs {
  538. publicDatasets = append(publicDatasets, PublicDataset{attch.Name,
  539. models.AttachmentRelativePath(attch.UUID)})
  540. }
  541. data,err := json.Marshal(publicDatasets)
  542. if err != nil {
  543. log.Error("json.Marshal failed:", err.Error())
  544. ctx.JSON(200, map[string]string{
  545. "result_code": "-1",
  546. "data": "",
  547. })
  548. return
  549. }
  550. ctx.JSON(200, map[string]string{
  551. "result_code": "0",
  552. "data": string(data),
  553. })
  554. }