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.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. }
  29. func init() {
  30. db.RegisterModel(new(Attachment))
  31. }
  32. // IncreaseDownloadCount is update download count + 1
  33. func (a *Attachment) IncreaseDownloadCount() error {
  34. // Update download count.
  35. if _, err := db.GetEngine(db.DefaultContext).Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
  36. return fmt.Errorf("increase attachment count: %w", err)
  37. }
  38. return nil
  39. }
  40. // AttachmentRelativePath returns the relative path
  41. func AttachmentRelativePath(uuid string) string {
  42. return path.Join(uuid[0:1], uuid[1:2], uuid)
  43. }
  44. // RelativePath returns the relative path of the attachment
  45. func (a *Attachment) RelativePath() string {
  46. return AttachmentRelativePath(a.UUID)
  47. }
  48. // DownloadURL returns the download url of the attached file
  49. func (a *Attachment) DownloadURL() string {
  50. return setting.AppURL + "attachments/" + url.PathEscape(a.UUID)
  51. }
  52. // _____ __ __ .__ __
  53. // / _ \_/ |__/ |______ ____ | |__ _____ ____ _____/ |_
  54. // / /_\ \ __\ __\__ \ _/ ___\| | \ / \_/ __ \ / \ __\
  55. // / | \ | | | / __ \\ \___| Y \ Y Y \ ___/| | \ |
  56. // \____|__ /__| |__| (____ /\___ >___| /__|_| /\___ >___| /__|
  57. // \/ \/ \/ \/ \/ \/ \/
  58. // ErrAttachmentNotExist represents a "AttachmentNotExist" kind of error.
  59. type ErrAttachmentNotExist struct {
  60. ID int64
  61. UUID string
  62. }
  63. // IsErrAttachmentNotExist checks if an error is a ErrAttachmentNotExist.
  64. func IsErrAttachmentNotExist(err error) bool {
  65. _, ok := err.(ErrAttachmentNotExist)
  66. return ok
  67. }
  68. func (err ErrAttachmentNotExist) Error() string {
  69. return fmt.Sprintf("attachment does not exist [id: %d, uuid: %s]", err.ID, err.UUID)
  70. }
  71. func (err ErrAttachmentNotExist) Unwrap() error {
  72. return util.ErrNotExist
  73. }
  74. // GetAttachmentByID returns attachment by given id
  75. func GetAttachmentByID(ctx context.Context, id int64) (*Attachment, error) {
  76. attach := &Attachment{}
  77. if has, err := db.GetEngine(ctx).ID(id).Get(attach); err != nil {
  78. return nil, err
  79. } else if !has {
  80. return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
  81. }
  82. return attach, nil
  83. }
  84. // GetAttachmentByUUID returns attachment by given UUID.
  85. func GetAttachmentByUUID(ctx context.Context, uuid string) (*Attachment, error) {
  86. attach := &Attachment{}
  87. has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(attach)
  88. if err != nil {
  89. return nil, err
  90. } else if !has {
  91. return nil, ErrAttachmentNotExist{0, uuid}
  92. }
  93. return attach, nil
  94. }
  95. // GetAttachmentsByUUIDs returns attachment by given UUID list.
  96. func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) {
  97. if len(uuids) == 0 {
  98. return []*Attachment{}, nil
  99. }
  100. // Silently drop invalid uuids.
  101. attachments := make([]*Attachment, 0, len(uuids))
  102. return attachments, db.GetEngine(ctx).In("uuid", uuids).Find(&attachments)
  103. }
  104. // ExistAttachmentsByUUID returns true if attachment exists with the given UUID
  105. func ExistAttachmentsByUUID(ctx context.Context, uuid string) (bool, error) {
  106. return db.GetEngine(ctx).Where("`uuid`=?", uuid).Exist(new(Attachment))
  107. }
  108. // GetAttachmentsByIssueID returns all attachments of an issue.
  109. func GetAttachmentsByIssueID(ctx context.Context, issueID int64) ([]*Attachment, error) {
  110. attachments := make([]*Attachment, 0, 10)
  111. return attachments, db.GetEngine(ctx).Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  112. }
  113. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  114. func GetAttachmentsByCommentID(ctx context.Context, commentID int64) ([]*Attachment, error) {
  115. attachments := make([]*Attachment, 0, 10)
  116. return attachments, db.GetEngine(ctx).Where("comment_id=?", commentID).Find(&attachments)
  117. }
  118. // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
  119. func GetAttachmentByReleaseIDFileName(ctx context.Context, releaseID int64, fileName string) (*Attachment, error) {
  120. attach := &Attachment{ReleaseID: releaseID, Name: fileName}
  121. has, err := db.GetEngine(ctx).Get(attach)
  122. if err != nil {
  123. return nil, err
  124. } else if !has {
  125. return nil, err
  126. }
  127. return attach, nil
  128. }
  129. // DeleteAttachment deletes the given attachment and optionally the associated file.
  130. func DeleteAttachment(a *Attachment, remove bool) error {
  131. _, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove)
  132. return err
  133. }
  134. // DeleteAttachments deletes the given attachments and optionally the associated files.
  135. func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bool) (int, error) {
  136. if len(attachments) == 0 {
  137. return 0, nil
  138. }
  139. ids := make([]int64, 0, len(attachments))
  140. for _, a := range attachments {
  141. ids = append(ids, a.ID)
  142. }
  143. cnt, err := db.GetEngine(ctx).In("id", ids).NoAutoCondition().Delete(attachments[0])
  144. if err != nil {
  145. return 0, err
  146. }
  147. if remove {
  148. for i, a := range attachments {
  149. if err := storage.Attachments.Delete(a.RelativePath()); err != nil {
  150. return i, err
  151. }
  152. }
  153. }
  154. return int(cnt), nil
  155. }
  156. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  157. func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
  158. attachments, err := GetAttachmentsByIssueID(db.DefaultContext, issueID)
  159. if err != nil {
  160. return 0, err
  161. }
  162. return DeleteAttachments(db.DefaultContext, attachments, remove)
  163. }
  164. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  165. func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
  166. attachments, err := GetAttachmentsByCommentID(db.DefaultContext, commentID)
  167. if err != nil {
  168. return 0, err
  169. }
  170. return DeleteAttachments(db.DefaultContext, attachments, remove)
  171. }
  172. // UpdateAttachmentByUUID Updates attachment via uuid
  173. func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error {
  174. if attach.UUID == "" {
  175. return fmt.Errorf("attachment uuid should be not blank")
  176. }
  177. _, err := db.GetEngine(ctx).Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
  178. return err
  179. }
  180. // UpdateAttachment updates the given attachment in database
  181. func UpdateAttachment(ctx context.Context, atta *Attachment) error {
  182. sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
  183. if atta.ID != 0 && atta.UUID == "" {
  184. sess = sess.ID(atta.ID)
  185. } else {
  186. // Use uuid only if id is not set and uuid is set
  187. sess = sess.Where("uuid = ?", atta.UUID)
  188. }
  189. _, err := sess.Update(atta)
  190. return err
  191. }
  192. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
  193. func DeleteAttachmentsByRelease(ctx context.Context, releaseID int64) error {
  194. _, err := db.GetEngine(ctx).Where("release_id = ?", releaseID).Delete(&Attachment{})
  195. return err
  196. }
  197. // CountOrphanedAttachments returns the number of bad attachments
  198. func CountOrphanedAttachments(ctx context.Context) (int64, error) {
  199. 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`))").
  200. Count(new(Attachment))
  201. }
  202. // DeleteOrphanedAttachments delete all bad attachments
  203. func DeleteOrphanedAttachments(ctx context.Context) error {
  204. _, 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`))").
  205. Delete(new(Attachment))
  206. return err
  207. }