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.

attachment.go 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repo
  4. import (
  5. "context"
  6. "fmt"
  7. "net/url"
  8. "path"
  9. "code.gitea.io/gitea/models/db"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/storage"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. )
  15. // Attachment represent a attachment of issue/comment/release.
  16. type Attachment struct {
  17. ID int64 `xorm:"pk autoincr"`
  18. UUID string `xorm:"uuid UNIQUE"`
  19. RepoID int64 `xorm:"INDEX"` // this should not be zero
  20. IssueID int64 `xorm:"INDEX"` // maybe zero when creating
  21. ReleaseID int64 `xorm:"INDEX"` // maybe zero when creating
  22. UploaderID int64 `xorm:"INDEX DEFAULT 0"` // Notice: will be zero before this column added
  23. CommentID int64
  24. Name string
  25. DownloadCount int64 `xorm:"DEFAULT 0"`
  26. Size int64 `xorm:"DEFAULT 0"`
  27. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  28. CustomDownloadURL string `xorm:"-"`
  29. }
  30. func init() {
  31. db.RegisterModel(new(Attachment))
  32. }
  33. // IncreaseDownloadCount is update download count + 1
  34. func (a *Attachment) IncreaseDownloadCount(ctx context.Context) error {
  35. // Update download count.
  36. if _, err := db.GetEngine(ctx).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
  37. return fmt.Errorf("increase attachment count: %w", err)
  38. }
  39. return nil
  40. }
  41. // AttachmentRelativePath returns the relative path
  42. func AttachmentRelativePath(uuid string) string {
  43. return path.Join(uuid[0:1], uuid[1:2], uuid)
  44. }
  45. // RelativePath returns the relative path of the attachment
  46. func (a *Attachment) RelativePath() string {
  47. return AttachmentRelativePath(a.UUID)
  48. }
  49. // DownloadURL returns the download url of the attached file
  50. func (a *Attachment) DownloadURL() string {
  51. if a.CustomDownloadURL != "" {
  52. return a.CustomDownloadURL
  53. }
  54. return setting.AppURL + "attachments/" + url.PathEscape(a.UUID)
  55. }
  56. // ErrAttachmentNotExist represents a "AttachmentNotExist" kind of error.
  57. type ErrAttachmentNotExist struct {
  58. ID int64
  59. UUID string
  60. }
  61. // IsErrAttachmentNotExist checks if an error is a ErrAttachmentNotExist.
  62. func IsErrAttachmentNotExist(err error) bool {
  63. _, ok := err.(ErrAttachmentNotExist)
  64. return ok
  65. }
  66. func (err ErrAttachmentNotExist) Error() string {
  67. return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID)
  68. }
  69. func (err ErrAttachmentNotExist) Unwrap() error {
  70. return util.ErrNotExist
  71. }
  72. // GetAttachmentByID returns attachment by given id
  73. func GetAttachmentByID(ctx context.Context, id int64) (*Attachment, error) {
  74. attach := &Attachment{}
  75. if has, err := db.GetEngine(ctx).ID(id).Get(attach); err != nil {
  76. return nil, err
  77. } else if !has {
  78. return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
  79. }
  80. return attach, nil
  81. }
  82. // GetAttachmentByUUID returns attachment by given UUID.
  83. func GetAttachmentByUUID(ctx context.Context, uuid string) (*Attachment, error) {
  84. attach := &Attachment{}
  85. has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(attach)
  86. if err != nil {
  87. return nil, err
  88. } else if !has {
  89. return nil, ErrAttachmentNotExist{0, uuid}
  90. }
  91. return attach, nil
  92. }
  93. // GetAttachmentsByUUIDs returns attachment by given UUID list.
  94. func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) {
  95. if len(uuids) == 0 {
  96. return []*Attachment{}, nil
  97. }
  98. // Silently drop invalid uuids.
  99. attachments := make([]*Attachment, 0, len(uuids))
  100. return attachments, db.GetEngine(ctx).In("uuid", uuids).Find(&attachments)
  101. }
  102. // ExistAttachmentsByUUID returns true if attachment exists with the given UUID
  103. func ExistAttachmentsByUUID(ctx context.Context, uuid string) (bool, error) {
  104. return db.GetEngine(ctx).Where("`uuid`=?", uuid).Exist(new(Attachment))
  105. }
  106. // GetAttachmentsByIssueID returns all attachments of an issue.
  107. func GetAttachmentsByIssueID(ctx context.Context, issueID int64) ([]*Attachment, error) {
  108. attachments := make([]*Attachment, 0, 10)
  109. return attachments, db.GetEngine(ctx).Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  110. }
  111. // GetAttachmentsByIssueIDImagesLatest returns the latest image attachments of an issue.
  112. func GetAttachmentsByIssueIDImagesLatest(ctx context.Context, issueID int64) ([]*Attachment, error) {
  113. attachments := make([]*Attachment, 0, 5)
  114. return attachments, db.GetEngine(ctx).Where(`issue_id = ? AND (name like '%.apng'
  115. OR name like '%.avif'
  116. OR name like '%.bmp'
  117. OR name like '%.gif'
  118. OR name like '%.jpg'
  119. OR name like '%.jpeg'
  120. OR name like '%.jxl'
  121. OR name like '%.png'
  122. OR name like '%.svg'
  123. OR name like '%.webp')`, issueID).Desc("comment_id").Limit(5).Find(&attachments)
  124. }
  125. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  126. func GetAttachmentsByCommentID(ctx context.Context, commentID int64) ([]*Attachment, error) {
  127. attachments := make([]*Attachment, 0, 10)
  128. return attachments, db.GetEngine(ctx).Where("comment_id=?", commentID).Find(&attachments)
  129. }
  130. // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
  131. func GetAttachmentByReleaseIDFileName(ctx context.Context, releaseID int64, fileName string) (*Attachment, error) {
  132. attach := &Attachment{ReleaseID: releaseID, Name: fileName}
  133. has, err := db.GetEngine(ctx).Get(attach)
  134. if err != nil {
  135. return nil, err
  136. } else if !has {
  137. return nil, err
  138. }
  139. return attach, nil
  140. }
  141. // DeleteAttachment deletes the given attachment and optionally the associated file.
  142. func DeleteAttachment(ctx context.Context, a *Attachment, remove bool) error {
  143. _, err := DeleteAttachments(ctx, []*Attachment{a}, remove)
  144. return err
  145. }
  146. // DeleteAttachments deletes the given attachments and optionally the associated files.
  147. func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bool) (int, error) {
  148. if len(attachments) == 0 {
  149. return 0, nil
  150. }
  151. ids := make([]int64, 0, len(attachments))
  152. for _, a := range attachments {
  153. ids = append(ids, a.ID)
  154. }
  155. cnt, err := db.GetEngine(ctx).In("id", ids).NoAutoCondition().Delete(attachments[0])
  156. if err != nil {
  157. return 0, err
  158. }
  159. if remove {
  160. for i, a := range attachments {
  161. if err := storage.Attachments.Delete(a.RelativePath()); err != nil {
  162. return i, err
  163. }
  164. }
  165. }
  166. return int(cnt), nil
  167. }
  168. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  169. func DeleteAttachmentsByIssue(ctx context.Context, issueID int64, remove bool) (int, error) {
  170. attachments, err := GetAttachmentsByIssueID(ctx, issueID)
  171. if err != nil {
  172. return 0, err
  173. }
  174. return DeleteAttachments(ctx, attachments, remove)
  175. }
  176. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  177. func DeleteAttachmentsByComment(ctx context.Context, commentID int64, remove bool) (int, error) {
  178. attachments, err := GetAttachmentsByCommentID(ctx, commentID)
  179. if err != nil {
  180. return 0, err
  181. }
  182. return DeleteAttachments(ctx, attachments, remove)
  183. }
  184. // UpdateAttachmentByUUID Updates attachment via uuid
  185. func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error {
  186. if attach.UUID == "" {
  187. return fmt.Errorf("attachment uuid should be not blank")
  188. }
  189. _, err := db.GetEngine(ctx).Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
  190. return err
  191. }
  192. // UpdateAttachment updates the given attachment in database
  193. func UpdateAttachment(ctx context.Context, atta *Attachment) error {
  194. sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
  195. if atta.ID != 0 && atta.UUID == "" {
  196. sess = sess.ID(atta.ID)
  197. } else {
  198. // Use uuid only if id is not set and uuid is set
  199. sess = sess.Where("uuid = ?", atta.UUID)
  200. }
  201. _, err := sess.Update(atta)
  202. return err
  203. }
  204. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
  205. func DeleteAttachmentsByRelease(ctx context.Context, releaseID int64) error {
  206. _, err := db.GetEngine(ctx).Where("release_id = ?", releaseID).Delete(&Attachment{})
  207. return err
  208. }
  209. // CountOrphanedAttachments returns the number of bad attachments
  210. func CountOrphanedAttachments(ctx context.Context) (int64, error) {
  211. return db.GetEngine(ctx).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
  212. Count(new(Attachment))
  213. }
  214. // DeleteOrphanedAttachments delete all bad attachments
  215. func DeleteOrphanedAttachments(ctx context.Context) error {
  216. _, err := db.GetEngine(ctx).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
  217. Delete(new(Attachment))
  218. return err
  219. }