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
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. if attach == nil {
  350. ctx.JSON(200, map[string]string{
  351. "uuid": fileChunk.UUID,
  352. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  353. "uploadID": fileChunk.UploadID,
  354. "chunks": string(chunks),
  355. "attachID": "0",
  356. "datasetID": "0",
  357. "fileName": "",
  358. "datasetName": "",
  359. })
  360. return
  361. }
  362. dataset, err := models.GetDatasetByID(attach.DatasetID)
  363. if err != nil {
  364. ctx.ServerError("GetDatasetByID", err)
  365. return
  366. }
  367. ctx.JSON(200, map[string]string{
  368. "uuid": fileChunk.UUID,
  369. "uploaded": strconv.Itoa(fileChunk.IsUploaded),
  370. "uploadID": fileChunk.UploadID,
  371. "chunks": string(chunks),
  372. "attachID": strconv.Itoa(int(attachID)),
  373. "datasetID": strconv.Itoa(int(attach.DatasetID)),
  374. "fileName": attach.Name,
  375. "datasetName": dataset.Title,
  376. })
  377. }
  378. func NewMultipart(ctx *context.Context) {
  379. if !setting.Attachment.Enabled {
  380. ctx.Error(404, "attachment is not enabled")
  381. return
  382. }
  383. err := upload.VerifyFileType(ctx.Query("fileType"), strings.Split(setting.Attachment.AllowedTypes, ","))
  384. if err != nil {
  385. ctx.Error(400, err.Error())
  386. return
  387. }
  388. if setting.Attachment.StoreType == storage.MinioStorageType {
  389. totalChunkCounts := ctx.QueryInt("totalChunkCounts")
  390. if totalChunkCounts > minio_ext.MaxPartsCount {
  391. ctx.Error(400, fmt.Sprintf("chunk counts(%d) is too much", totalChunkCounts))
  392. return
  393. }
  394. fileSize := ctx.QueryInt64("size")
  395. if fileSize > minio_ext.MaxMultipartPutObjectSize {
  396. ctx.Error(400, fmt.Sprintf("file size(%d) is too big", fileSize))
  397. return
  398. }
  399. uuid := gouuid.NewV4().String()
  400. uploadID, err := storage.NewMultiPartUpload(uuid)
  401. if err != nil {
  402. ctx.ServerError("NewMultipart", err)
  403. return
  404. }
  405. _, err = models.InsertFileChunk(&models.FileChunk{
  406. UUID: uuid,
  407. UserID: ctx.User.ID,
  408. UploadID: uploadID,
  409. Md5: ctx.Query("md5"),
  410. Size: fileSize,
  411. TotalChunks: totalChunkCounts,
  412. })
  413. if err != nil {
  414. ctx.Error(500, fmt.Sprintf("InsertFileChunk: %v", err))
  415. return
  416. }
  417. ctx.JSON(200, map[string]string{
  418. "uuid": uuid,
  419. "uploadID": uploadID,
  420. })
  421. } else {
  422. ctx.Error(404, "storage type is not enabled")
  423. return
  424. }
  425. }
  426. func GetMultipartUploadUrl(ctx *context.Context) {
  427. uuid := ctx.Query("uuid")
  428. uploadID := ctx.Query("uploadID")
  429. partNumber := ctx.QueryInt("chunkNumber")
  430. size := ctx.QueryInt64("size")
  431. if size > minio_ext.MinPartSize {
  432. ctx.Error(400, fmt.Sprintf("chunk size(%d) is too big", size))
  433. return
  434. }
  435. url, err := storage.GenMultiPartSignedUrl(uuid, uploadID, partNumber, size)
  436. if err != nil {
  437. ctx.Error(500, fmt.Sprintf("GenMultiPartSignedUrl failed: %v", err))
  438. return
  439. }
  440. ctx.JSON(200, map[string]string{
  441. "url": url,
  442. })
  443. }
  444. func CompleteMultipart(ctx *context.Context) {
  445. uuid := ctx.Query("uuid")
  446. uploadID := ctx.Query("uploadID")
  447. fileChunk, err := models.GetFileChunkByUUID(uuid)
  448. if err != nil {
  449. if models.IsErrFileChunkNotExist(err) {
  450. ctx.Error(404)
  451. } else {
  452. ctx.ServerError("GetFileChunkByUUID", err)
  453. }
  454. return
  455. }
  456. _, err = storage.CompleteMultiPartUpload(uuid, uploadID)
  457. if err != nil {
  458. ctx.Error(500, fmt.Sprintf("CompleteMultiPartUpload failed: %v", err))
  459. return
  460. }
  461. fileChunk.IsUploaded = models.FileUploaded
  462. err = models.UpdateFileChunk(fileChunk)
  463. if err != nil {
  464. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  465. return
  466. }
  467. attachment, err := models.InsertAttachment(&models.Attachment{
  468. UUID: uuid,
  469. UploaderID: ctx.User.ID,
  470. IsPrivate: true,
  471. Name: ctx.Query("file_name"),
  472. Size: ctx.QueryInt64("size"),
  473. DatasetID: ctx.QueryInt64("dataset_id"),
  474. })
  475. if err != nil {
  476. ctx.Error(500, fmt.Sprintf("InsertAttachment: %v", err))
  477. return
  478. }
  479. if attachment.DatasetID != 0 {
  480. if strings.HasSuffix(attachment.Name, ".zip") {
  481. err = worker.SendDecompressTask(contexExt.Background(), uuid)
  482. if err != nil {
  483. log.Error("SendDecompressTask(%s) failed:%s", uuid, err.Error())
  484. } else {
  485. attachment.DecompressState = models.DecompressStateIng
  486. err = models.UpdateAttachment(attachment)
  487. if err != nil {
  488. log.Error("UpdateAttachment state(%s) failed:%s", uuid, err.Error())
  489. }
  490. }
  491. }
  492. }
  493. ctx.JSON(200, map[string]string{
  494. "result_code": "0",
  495. })
  496. }
  497. func UpdateMultipart(ctx *context.Context) {
  498. uuid := ctx.Query("uuid")
  499. partNumber := ctx.QueryInt("chunkNumber")
  500. etag := ctx.Query("etag")
  501. fileChunk, err := models.GetFileChunkByUUID(uuid)
  502. if err != nil {
  503. if models.IsErrFileChunkNotExist(err) {
  504. ctx.Error(404)
  505. } else {
  506. ctx.ServerError("GetFileChunkByUUID", err)
  507. }
  508. return
  509. }
  510. fileChunk.CompletedParts = append(fileChunk.CompletedParts, strconv.Itoa(partNumber)+"-"+strings.Replace(etag, "\"", "", -1))
  511. err = models.UpdateFileChunk(fileChunk)
  512. if err != nil {
  513. ctx.Error(500, fmt.Sprintf("UpdateFileChunk: %v", err))
  514. return
  515. }
  516. ctx.JSON(200, map[string]string{
  517. "result_code": "0",
  518. })
  519. }
  520. func HandleUnDecompressAttachment() {
  521. attachs, err := models.GetUnDecompressAttachments()
  522. if err != nil {
  523. log.Error("GetUnDecompressAttachments failed:", err.Error())
  524. return
  525. }
  526. for _, attach := range attachs {
  527. err = worker.SendDecompressTask(contexExt.Background(), attach.UUID)
  528. if err != nil {
  529. log.Error("SendDecompressTask(%s) failed:%s", attach.UUID, err.Error())
  530. } else {
  531. attach.DecompressState = models.DecompressStateIng
  532. err = models.UpdateAttachment(attach)
  533. if err != nil {
  534. log.Error("UpdateAttachment state(%s) failed:%s", attach.UUID, err.Error())
  535. }
  536. }
  537. }
  538. return
  539. }
  540. func QueryAllPublicDataset(ctx *context.Context){
  541. attachs, err := models.GetAllPublicAttachments()
  542. if err != nil {
  543. ctx.JSON(200, map[string]string{
  544. "result_code": "-1",
  545. "data": "",
  546. })
  547. return
  548. }
  549. var publicDatasets []PublicDataset
  550. for _, attch := range attachs {
  551. publicDatasets = append(publicDatasets, PublicDataset{attch.Name,
  552. models.AttachmentRelativePath(attch.UUID)})
  553. }
  554. data,err := json.Marshal(publicDatasets)
  555. if err != nil {
  556. log.Error("json.Marshal failed:", err.Error())
  557. ctx.JSON(200, map[string]string{
  558. "result_code": "-1",
  559. "data": "",
  560. })
  561. return
  562. }
  563. ctx.JSON(200, map[string]string{
  564. "result_code": "0",
  565. "data": string(data),
  566. })
  567. }