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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 models
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "path"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/storage"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. gouuid "github.com/google/uuid"
  14. "xorm.io/xorm"
  15. )
  16. // Attachment represent a attachment of issue/comment/release.
  17. type Attachment struct {
  18. ID int64 `xorm:"pk autoincr"`
  19. UUID string `xorm:"uuid UNIQUE"`
  20. IssueID int64 `xorm:"INDEX"`
  21. ReleaseID int64 `xorm:"INDEX"`
  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. // IncreaseDownloadCount is update download count + 1
  30. func (a *Attachment) IncreaseDownloadCount() error {
  31. // Update download count.
  32. if _, err := x.Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
  33. return fmt.Errorf("increase attachment count: %v", err)
  34. }
  35. return nil
  36. }
  37. // AttachmentRelativePath returns the relative path
  38. func AttachmentRelativePath(uuid string) string {
  39. return path.Join(uuid[0:1], uuid[1:2], uuid)
  40. }
  41. // RelativePath returns the relative path of the attachment
  42. func (a *Attachment) RelativePath() string {
  43. return AttachmentRelativePath(a.UUID)
  44. }
  45. // DownloadURL returns the download url of the attached file
  46. func (a *Attachment) DownloadURL() string {
  47. return fmt.Sprintf("%sattachments/%s", setting.AppURL, a.UUID)
  48. }
  49. // LinkedRepository returns the linked repo if any
  50. func (a *Attachment) LinkedRepository() (*Repository, UnitType, error) {
  51. if a.IssueID != 0 {
  52. iss, err := GetIssueByID(a.IssueID)
  53. if err != nil {
  54. return nil, UnitTypeIssues, err
  55. }
  56. repo, err := GetRepositoryByID(iss.RepoID)
  57. unitType := UnitTypeIssues
  58. if iss.IsPull {
  59. unitType = UnitTypePullRequests
  60. }
  61. return repo, unitType, err
  62. } else if a.ReleaseID != 0 {
  63. rel, err := GetReleaseByID(a.ReleaseID)
  64. if err != nil {
  65. return nil, UnitTypeReleases, err
  66. }
  67. repo, err := GetRepositoryByID(rel.RepoID)
  68. return repo, UnitTypeReleases, err
  69. }
  70. return nil, -1, nil
  71. }
  72. // NewAttachment creates a new attachment object.
  73. func NewAttachment(attach *Attachment, buf []byte, file io.Reader) (_ *Attachment, err error) {
  74. attach.UUID = gouuid.New().String()
  75. size, err := storage.Attachments.Save(attach.RelativePath(), io.MultiReader(bytes.NewReader(buf), file), -1)
  76. if err != nil {
  77. return nil, fmt.Errorf("Create: %v", err)
  78. }
  79. attach.Size = size
  80. if _, err := x.Insert(attach); err != nil {
  81. return nil, err
  82. }
  83. return attach, nil
  84. }
  85. // GetAttachmentByID returns attachment by given id
  86. func GetAttachmentByID(id int64) (*Attachment, error) {
  87. return getAttachmentByID(x, id)
  88. }
  89. func getAttachmentByID(e Engine, id int64) (*Attachment, error) {
  90. attach := &Attachment{}
  91. if has, err := e.ID(id).Get(attach); err != nil {
  92. return nil, err
  93. } else if !has {
  94. return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
  95. }
  96. return attach, nil
  97. }
  98. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  99. attach := &Attachment{}
  100. has, err := e.Where("uuid=?", uuid).Get(attach)
  101. if err != nil {
  102. return nil, err
  103. } else if !has {
  104. return nil, ErrAttachmentNotExist{0, uuid}
  105. }
  106. return attach, nil
  107. }
  108. // GetAttachmentsByUUIDs returns attachment by given UUID list.
  109. func GetAttachmentsByUUIDs(ctx DBContext, uuids []string) ([]*Attachment, error) {
  110. return getAttachmentsByUUIDs(ctx.e, uuids)
  111. }
  112. func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
  113. if len(uuids) == 0 {
  114. return []*Attachment{}, nil
  115. }
  116. // Silently drop invalid uuids.
  117. attachments := make([]*Attachment, 0, len(uuids))
  118. return attachments, e.In("uuid", uuids).Find(&attachments)
  119. }
  120. // GetAttachmentByUUID returns attachment by given UUID.
  121. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  122. return getAttachmentByUUID(x, uuid)
  123. }
  124. // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
  125. func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) {
  126. return getAttachmentByReleaseIDFileName(x, releaseID, fileName)
  127. }
  128. func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
  129. attachments := make([]*Attachment, 0, 10)
  130. return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  131. }
  132. // GetAttachmentsByIssueID returns all attachments of an issue.
  133. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  134. return getAttachmentsByIssueID(x, issueID)
  135. }
  136. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  137. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  138. return getAttachmentsByCommentID(x, commentID)
  139. }
  140. func getAttachmentsByCommentID(e Engine, commentID int64) ([]*Attachment, error) {
  141. attachments := make([]*Attachment, 0, 10)
  142. return attachments, e.Where("comment_id=?", commentID).Find(&attachments)
  143. }
  144. // getAttachmentByReleaseIDFileName return a file based on the the following infos:
  145. func getAttachmentByReleaseIDFileName(e Engine, releaseID int64, fileName string) (*Attachment, error) {
  146. attach := &Attachment{ReleaseID: releaseID, Name: fileName}
  147. has, err := e.Get(attach)
  148. if err != nil {
  149. return nil, err
  150. } else if !has {
  151. return nil, err
  152. }
  153. return attach, nil
  154. }
  155. // DeleteAttachment deletes the given attachment and optionally the associated file.
  156. func DeleteAttachment(a *Attachment, remove bool) error {
  157. _, err := DeleteAttachments(DefaultDBContext(), []*Attachment{a}, remove)
  158. return err
  159. }
  160. // DeleteAttachments deletes the given attachments and optionally the associated files.
  161. func DeleteAttachments(ctx DBContext, attachments []*Attachment, remove bool) (int, error) {
  162. if len(attachments) == 0 {
  163. return 0, nil
  164. }
  165. ids := make([]int64, 0, len(attachments))
  166. for _, a := range attachments {
  167. ids = append(ids, a.ID)
  168. }
  169. cnt, err := ctx.e.In("id", ids).NoAutoCondition().Delete(attachments[0])
  170. if err != nil {
  171. return 0, err
  172. }
  173. if remove {
  174. for i, a := range attachments {
  175. if err := storage.Attachments.Delete(a.RelativePath()); err != nil {
  176. return i, err
  177. }
  178. }
  179. }
  180. return int(cnt), nil
  181. }
  182. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  183. func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
  184. attachments, err := GetAttachmentsByIssueID(issueID)
  185. if err != nil {
  186. return 0, err
  187. }
  188. return DeleteAttachments(DefaultDBContext(), attachments, remove)
  189. }
  190. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  191. func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
  192. attachments, err := GetAttachmentsByCommentID(commentID)
  193. if err != nil {
  194. return 0, err
  195. }
  196. return DeleteAttachments(DefaultDBContext(), attachments, remove)
  197. }
  198. // UpdateAttachment updates the given attachment in database
  199. func UpdateAttachment(atta *Attachment) error {
  200. return updateAttachment(x, atta)
  201. }
  202. // UpdateAttachmentByUUID Updates attachment via uuid
  203. func UpdateAttachmentByUUID(ctx DBContext, attach *Attachment, cols ...string) error {
  204. if attach.UUID == "" {
  205. return fmt.Errorf("Attachement uuid should not blank")
  206. }
  207. _, err := ctx.e.Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
  208. return err
  209. }
  210. func updateAttachment(e Engine, atta *Attachment) error {
  211. var sess *xorm.Session
  212. if atta.ID != 0 && atta.UUID == "" {
  213. sess = e.ID(atta.ID)
  214. } else {
  215. // Use uuid only if id is not set and uuid is set
  216. sess = e.Where("uuid = ?", atta.UUID)
  217. }
  218. _, err := sess.Cols("name", "issue_id", "release_id", "comment_id", "download_count").Update(atta)
  219. return err
  220. }
  221. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
  222. func DeleteAttachmentsByRelease(releaseID int64) error {
  223. _, err := x.Where("release_id = ?", releaseID).Delete(&Attachment{})
  224. return err
  225. }
  226. // IterateAttachment iterates attachments; it should not be used when Gitea is servicing users.
  227. func IterateAttachment(f func(attach *Attachment) error) error {
  228. var start int
  229. const batchSize = 100
  230. for {
  231. attachments := make([]*Attachment, 0, batchSize)
  232. if err := x.Limit(batchSize, start).Find(&attachments); err != nil {
  233. return err
  234. }
  235. if len(attachments) == 0 {
  236. return nil
  237. }
  238. start += len(attachments)
  239. for _, attach := range attachments {
  240. if err := f(attach); err != nil {
  241. return err
  242. }
  243. }
  244. }
  245. }