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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. "fmt"
  7. "io"
  8. "os"
  9. "path"
  10. "code.gitea.io/gitea/modules/setting"
  11. api "code.gitea.io/gitea/modules/structs"
  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. // APIFormat converts models.Attachment to api.Attachment
  38. func (a *Attachment) APIFormat() *api.Attachment {
  39. return &api.Attachment{
  40. ID: a.ID,
  41. Name: a.Name,
  42. Created: a.CreatedUnix.AsTime(),
  43. DownloadCount: a.DownloadCount,
  44. Size: a.Size,
  45. UUID: a.UUID,
  46. DownloadURL: a.DownloadURL(),
  47. }
  48. }
  49. // AttachmentLocalPath returns where attachment is stored in local file
  50. // system based on given UUID.
  51. func AttachmentLocalPath(uuid string) string {
  52. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  53. }
  54. // LocalPath returns where attachment is stored in local file system.
  55. func (a *Attachment) LocalPath() string {
  56. return AttachmentLocalPath(a.UUID)
  57. }
  58. // DownloadURL returns the download url of the attached file
  59. func (a *Attachment) DownloadURL() string {
  60. return fmt.Sprintf("%sattachments/%s", setting.AppURL, a.UUID)
  61. }
  62. // LinkedRepository returns the linked repo if any
  63. func (a *Attachment) LinkedRepository() (*Repository, UnitType, error) {
  64. if a.IssueID != 0 {
  65. iss, err := GetIssueByID(a.IssueID)
  66. if err != nil {
  67. return nil, UnitTypeIssues, err
  68. }
  69. repo, err := GetRepositoryByID(iss.RepoID)
  70. unitType := UnitTypeIssues
  71. if iss.IsPull {
  72. unitType = UnitTypePullRequests
  73. }
  74. return repo, unitType, err
  75. } else if a.ReleaseID != 0 {
  76. rel, err := GetReleaseByID(a.ReleaseID)
  77. if err != nil {
  78. return nil, UnitTypeReleases, err
  79. }
  80. repo, err := GetRepositoryByID(rel.RepoID)
  81. return repo, UnitTypeReleases, err
  82. }
  83. return nil, -1, nil
  84. }
  85. // NewAttachment creates a new attachment object.
  86. func NewAttachment(attach *Attachment, buf []byte, file io.Reader) (_ *Attachment, err error) {
  87. attach.UUID = gouuid.New().String()
  88. localPath := attach.LocalPath()
  89. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  90. return nil, fmt.Errorf("MkdirAll: %v", err)
  91. }
  92. fw, err := os.Create(localPath)
  93. if err != nil {
  94. return nil, fmt.Errorf("Create: %v", err)
  95. }
  96. defer fw.Close()
  97. if _, err = fw.Write(buf); err != nil {
  98. return nil, fmt.Errorf("Write: %v", err)
  99. } else if _, err = io.Copy(fw, file); err != nil {
  100. return nil, fmt.Errorf("Copy: %v", err)
  101. }
  102. // Update file size
  103. var fi os.FileInfo
  104. if fi, err = fw.Stat(); err != nil {
  105. return nil, fmt.Errorf("file size: %v", err)
  106. }
  107. attach.Size = fi.Size()
  108. if _, err := x.Insert(attach); err != nil {
  109. return nil, err
  110. }
  111. return attach, nil
  112. }
  113. // GetAttachmentByID returns attachment by given id
  114. func GetAttachmentByID(id int64) (*Attachment, error) {
  115. return getAttachmentByID(x, id)
  116. }
  117. func getAttachmentByID(e Engine, id int64) (*Attachment, error) {
  118. attach := &Attachment{}
  119. if has, err := e.ID(id).Get(attach); err != nil {
  120. return nil, err
  121. } else if !has {
  122. return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
  123. }
  124. return attach, nil
  125. }
  126. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  127. attach := &Attachment{}
  128. has, err := e.Where("uuid=?", uuid).Get(attach)
  129. if err != nil {
  130. return nil, err
  131. } else if !has {
  132. return nil, ErrAttachmentNotExist{0, uuid}
  133. }
  134. return attach, nil
  135. }
  136. // GetAttachmentsByUUIDs returns attachment by given UUID list.
  137. func GetAttachmentsByUUIDs(uuids []string) ([]*Attachment, error) {
  138. return getAttachmentsByUUIDs(x, uuids)
  139. }
  140. func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
  141. if len(uuids) == 0 {
  142. return []*Attachment{}, nil
  143. }
  144. // Silently drop invalid uuids.
  145. attachments := make([]*Attachment, 0, len(uuids))
  146. return attachments, e.In("uuid", uuids).Find(&attachments)
  147. }
  148. // GetAttachmentByUUID returns attachment by given UUID.
  149. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  150. return getAttachmentByUUID(x, uuid)
  151. }
  152. // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
  153. func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) {
  154. return getAttachmentByReleaseIDFileName(x, releaseID, fileName)
  155. }
  156. func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
  157. attachments := make([]*Attachment, 0, 10)
  158. return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  159. }
  160. // GetAttachmentsByIssueID returns all attachments of an issue.
  161. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  162. return getAttachmentsByIssueID(x, issueID)
  163. }
  164. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  165. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  166. return getAttachmentsByCommentID(x, commentID)
  167. }
  168. func getAttachmentsByCommentID(e Engine, commentID int64) ([]*Attachment, error) {
  169. attachments := make([]*Attachment, 0, 10)
  170. return attachments, e.Where("comment_id=?", commentID).Find(&attachments)
  171. }
  172. // getAttachmentByReleaseIDFileName return a file based on the the following infos:
  173. func getAttachmentByReleaseIDFileName(e Engine, releaseID int64, fileName string) (*Attachment, error) {
  174. attach := &Attachment{ReleaseID: releaseID, Name: fileName}
  175. has, err := e.Get(attach)
  176. if err != nil {
  177. return nil, err
  178. } else if !has {
  179. return nil, err
  180. }
  181. return attach, nil
  182. }
  183. // DeleteAttachment deletes the given attachment and optionally the associated file.
  184. func DeleteAttachment(a *Attachment, remove bool) error {
  185. _, err := DeleteAttachments([]*Attachment{a}, remove)
  186. return err
  187. }
  188. // DeleteAttachments deletes the given attachments and optionally the associated files.
  189. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  190. if len(attachments) == 0 {
  191. return 0, nil
  192. }
  193. var ids = make([]int64, 0, len(attachments))
  194. for _, a := range attachments {
  195. ids = append(ids, a.ID)
  196. }
  197. cnt, err := x.In("id", ids).NoAutoCondition().Delete(attachments[0])
  198. if err != nil {
  199. return 0, err
  200. }
  201. if remove {
  202. for i, a := range attachments {
  203. if err := os.Remove(a.LocalPath()); err != nil {
  204. return i, err
  205. }
  206. }
  207. }
  208. return int(cnt), nil
  209. }
  210. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  211. func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
  212. attachments, err := GetAttachmentsByIssueID(issueID)
  213. if err != nil {
  214. return 0, err
  215. }
  216. return DeleteAttachments(attachments, remove)
  217. }
  218. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  219. func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
  220. attachments, err := GetAttachmentsByCommentID(commentID)
  221. if err != nil {
  222. return 0, err
  223. }
  224. return DeleteAttachments(attachments, remove)
  225. }
  226. // UpdateAttachment updates the given attachment in database
  227. func UpdateAttachment(atta *Attachment) error {
  228. return updateAttachment(x, atta)
  229. }
  230. func updateAttachment(e Engine, atta *Attachment) error {
  231. var sess *xorm.Session
  232. if atta.ID != 0 && atta.UUID == "" {
  233. sess = e.ID(atta.ID)
  234. } else {
  235. // Use uuid only if id is not set and uuid is set
  236. sess = e.Where("uuid = ?", atta.UUID)
  237. }
  238. _, err := sess.Cols("name", "issue_id", "release_id", "comment_id", "download_count").Update(atta)
  239. return err
  240. }
  241. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
  242. func DeleteAttachmentsByRelease(releaseID int64) error {
  243. _, err := x.Where("release_id = ?", releaseID).Delete(&Attachment{})
  244. return err
  245. }