gitea源码

attachment.go 8.7KB

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