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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. "context"
  7. "fmt"
  8. "net/url"
  9. "path"
  10. "code.gitea.io/gitea/models/db"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/storage"
  13. "code.gitea.io/gitea/modules/timeutil"
  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: %v", 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. // GetAttachmentByID returns attachment by given id
  72. func GetAttachmentByID(ctx context.Context, id int64) (*Attachment, error) {
  73. attach := &Attachment{}
  74. if has, err := db.GetEngine(ctx).ID(id).Get(attach); err != nil {
  75. return nil, err
  76. } else if !has {
  77. return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
  78. }
  79. return attach, nil
  80. }
  81. // GetAttachmentByUUID returns attachment by given UUID.
  82. func GetAttachmentByUUID(ctx context.Context, uuid string) (*Attachment, error) {
  83. attach := &Attachment{}
  84. has, err := db.GetEngine(ctx).Where("uuid=?", uuid).Get(attach)
  85. if err != nil {
  86. return nil, err
  87. } else if !has {
  88. return nil, ErrAttachmentNotExist{0, uuid}
  89. }
  90. return attach, nil
  91. }
  92. // GetAttachmentsByUUIDs returns attachment by given UUID list.
  93. func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, error) {
  94. if len(uuids) == 0 {
  95. return []*Attachment{}, nil
  96. }
  97. // Silently drop invalid uuids.
  98. attachments := make([]*Attachment, 0, len(uuids))
  99. return attachments, db.GetEngine(ctx).In("uuid", uuids).Find(&attachments)
  100. }
  101. // ExistAttachmentsByUUID returns true if attachment is exist by given UUID
  102. func ExistAttachmentsByUUID(uuid string) (bool, error) {
  103. return db.GetEngine(db.DefaultContext).Where("`uuid`=?", uuid).Exist(new(Attachment))
  104. }
  105. // GetAttachmentsByIssueID returns all attachments of an issue.
  106. func GetAttachmentsByIssueID(ctx context.Context, issueID int64) ([]*Attachment, error) {
  107. attachments := make([]*Attachment, 0, 10)
  108. return attachments, db.GetEngine(ctx).Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  109. }
  110. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  111. func GetAttachmentsByCommentID(ctx context.Context, commentID int64) ([]*Attachment, error) {
  112. attachments := make([]*Attachment, 0, 10)
  113. return attachments, db.GetEngine(ctx).Where("comment_id=?", commentID).Find(&attachments)
  114. }
  115. // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
  116. func GetAttachmentByReleaseIDFileName(ctx context.Context, releaseID int64, fileName string) (*Attachment, error) {
  117. attach := &Attachment{ReleaseID: releaseID, Name: fileName}
  118. has, err := db.GetEngine(ctx).Get(attach)
  119. if err != nil {
  120. return nil, err
  121. } else if !has {
  122. return nil, err
  123. }
  124. return attach, nil
  125. }
  126. // DeleteAttachment deletes the given attachment and optionally the associated file.
  127. func DeleteAttachment(a *Attachment, remove bool) error {
  128. _, err := DeleteAttachments(db.DefaultContext, []*Attachment{a}, remove)
  129. return err
  130. }
  131. // DeleteAttachments deletes the given attachments and optionally the associated files.
  132. func DeleteAttachments(ctx context.Context, attachments []*Attachment, remove bool) (int, error) {
  133. if len(attachments) == 0 {
  134. return 0, nil
  135. }
  136. ids := make([]int64, 0, len(attachments))
  137. for _, a := range attachments {
  138. ids = append(ids, a.ID)
  139. }
  140. cnt, err := db.GetEngine(ctx).In("id", ids).NoAutoCondition().Delete(attachments[0])
  141. if err != nil {
  142. return 0, err
  143. }
  144. if remove {
  145. for i, a := range attachments {
  146. if err := storage.Attachments.Delete(a.RelativePath()); err != nil {
  147. return i, err
  148. }
  149. }
  150. }
  151. return int(cnt), nil
  152. }
  153. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  154. func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
  155. attachments, err := GetAttachmentsByIssueID(db.DefaultContext, issueID)
  156. if err != nil {
  157. return 0, err
  158. }
  159. return DeleteAttachments(db.DefaultContext, attachments, remove)
  160. }
  161. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  162. func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
  163. attachments, err := GetAttachmentsByCommentID(db.DefaultContext, commentID)
  164. if err != nil {
  165. return 0, err
  166. }
  167. return DeleteAttachments(db.DefaultContext, attachments, remove)
  168. }
  169. // UpdateAttachmentByUUID Updates attachment via uuid
  170. func UpdateAttachmentByUUID(ctx context.Context, attach *Attachment, cols ...string) error {
  171. if attach.UUID == "" {
  172. return fmt.Errorf("attachment uuid should be not blank")
  173. }
  174. _, err := db.GetEngine(ctx).Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
  175. return err
  176. }
  177. // UpdateAttachment updates the given attachment in database
  178. func UpdateAttachment(ctx context.Context, atta *Attachment) error {
  179. sess := db.GetEngine(ctx).Cols("name", "issue_id", "release_id", "comment_id", "download_count")
  180. if atta.ID != 0 && atta.UUID == "" {
  181. sess = sess.ID(atta.ID)
  182. } else {
  183. // Use uuid only if id is not set and uuid is set
  184. sess = sess.Where("uuid = ?", atta.UUID)
  185. }
  186. _, err := sess.Update(atta)
  187. return err
  188. }
  189. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
  190. func DeleteAttachmentsByRelease(releaseID int64) error {
  191. _, err := db.GetEngine(db.DefaultContext).Where("release_id = ?", releaseID).Delete(&Attachment{})
  192. return err
  193. }
  194. // IterateAttachment iterates attachments; it should not be used when Gitea is servicing users.
  195. func IterateAttachment(f func(attach *Attachment) error) error {
  196. var start int
  197. const batchSize = 100
  198. for {
  199. attachments := make([]*Attachment, 0, batchSize)
  200. if err := db.GetEngine(db.DefaultContext).Limit(batchSize, start).Find(&attachments); err != nil {
  201. return err
  202. }
  203. if len(attachments) == 0 {
  204. return nil
  205. }
  206. start += len(attachments)
  207. for _, attach := range attachments {
  208. if err := f(attach); err != nil {
  209. return err
  210. }
  211. }
  212. }
  213. }
  214. // CountOrphanedAttachments returns the number of bad attachments
  215. func CountOrphanedAttachments() (int64, error) {
  216. return db.GetEngine(db.DefaultContext).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. Count(new(Attachment))
  218. }
  219. // DeleteOrphanedAttachments delete all bad attachments
  220. func DeleteOrphanedAttachments() error {
  221. _, err := db.GetEngine(db.DefaultContext).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`))").
  222. Delete(new(Attachment))
  223. return err
  224. }