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

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