You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.1 KiB

  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. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/context"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/upload"
  13. )
  14. func renderAttachmentSettings(ctx *context.Context) {
  15. ctx.Data["RequireDropzone"] = true
  16. ctx.Data["IsAttachmentEnabled"] = setting.AttachmentEnabled
  17. ctx.Data["AttachmentAllowedTypes"] = setting.AttachmentAllowedTypes
  18. ctx.Data["AttachmentMaxSize"] = setting.AttachmentMaxSize
  19. ctx.Data["AttachmentMaxFiles"] = setting.AttachmentMaxFiles
  20. }
  21. // UploadAttachment response for uploading issue's attachment
  22. func UploadAttachment(ctx *context.Context) {
  23. if !setting.AttachmentEnabled {
  24. ctx.Error(404, "attachment is not enabled")
  25. return
  26. }
  27. file, header, err := ctx.Req.FormFile("file")
  28. if err != nil {
  29. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  30. return
  31. }
  32. defer file.Close()
  33. buf := make([]byte, 1024)
  34. n, _ := file.Read(buf)
  35. if n > 0 {
  36. buf = buf[:n]
  37. }
  38. err = upload.VerifyAllowedContentType(buf, strings.Split(setting.AttachmentAllowedTypes, ","))
  39. if err != nil {
  40. ctx.Error(400, err.Error())
  41. return
  42. }
  43. attach, err := models.NewAttachment(&models.Attachment{
  44. UploaderID: ctx.User.ID,
  45. Name: header.Filename,
  46. }, buf, file)
  47. if err != nil {
  48. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  49. return
  50. }
  51. log.Trace("New attachment uploaded: %s", attach.UUID)
  52. ctx.JSON(200, map[string]string{
  53. "uuid": attach.UUID,
  54. })
  55. }
  56. // DeleteAttachment response for deleting issue's attachment
  57. func DeleteAttachment(ctx *context.Context) {
  58. file := ctx.Query("file")
  59. attach, err := models.GetAttachmentByUUID(file)
  60. if !ctx.IsSigned || (ctx.User.ID != attach.UploaderID) {
  61. ctx.Error(403)
  62. return
  63. }
  64. if err != nil {
  65. ctx.Error(400, err.Error())
  66. return
  67. }
  68. err = models.DeleteAttachment(attach, true)
  69. if err != nil {
  70. ctx.Error(500, fmt.Sprintf("DeleteAttachment: %v", err))
  71. return
  72. }
  73. ctx.JSON(200, map[string]string{
  74. "uuid": attach.UUID,
  75. })
  76. }