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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. "mime/multipart"
  9. "os"
  10. "path"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "code.gitea.io/gitea/modules/util"
  14. api "code.gitea.io/sdk/gitea"
  15. "github.com/go-xorm/xorm"
  16. gouuid "github.com/satori/go.uuid"
  17. )
  18. // Attachment represent a attachment of issue/comment/release.
  19. type Attachment struct {
  20. ID int64 `xorm:"pk autoincr"`
  21. UUID string `xorm:"uuid UNIQUE"`
  22. IssueID int64 `xorm:"INDEX"`
  23. ReleaseID int64 `xorm:"INDEX"`
  24. CommentID int64
  25. Name string
  26. DownloadCount int64 `xorm:"DEFAULT 0"`
  27. CreatedUnix util.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. size, _ := a.Size()
  40. return &api.Attachment{
  41. ID: a.ID,
  42. Name: a.Name,
  43. Created: a.CreatedUnix.AsTime(),
  44. DownloadCount: a.DownloadCount,
  45. Size: size,
  46. UUID: a.UUID,
  47. DownloadURL: a.DownloadURL(),
  48. }
  49. }
  50. // AttachmentLocalPath returns where attachment is stored in local file
  51. // system based on given UUID.
  52. func AttachmentLocalPath(uuid string) string {
  53. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  54. }
  55. // LocalPath returns where attachment is stored in local file system.
  56. func (a *Attachment) LocalPath() string {
  57. return AttachmentLocalPath(a.UUID)
  58. }
  59. // Size returns the file's size of the attachment
  60. func (a *Attachment) Size() (int64, error) {
  61. fi, err := os.Stat(a.LocalPath())
  62. if err != nil {
  63. return 0, err
  64. }
  65. return fi.Size(), nil
  66. }
  67. // MustSize returns the result of a.Size() by ignoring errors
  68. func (a *Attachment) MustSize() int64 {
  69. size, err := a.Size()
  70. if err != nil {
  71. log.Error(4, "size: %v", err)
  72. return 0
  73. }
  74. return size
  75. }
  76. // DownloadURL returns the download url of the attached file
  77. func (a *Attachment) DownloadURL() string {
  78. return fmt.Sprintf("%sattachments/%s", setting.AppURL, a.UUID)
  79. }
  80. // NewAttachment creates a new attachment object.
  81. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  82. attach := &Attachment{
  83. UUID: gouuid.NewV4().String(),
  84. Name: name,
  85. }
  86. localPath := attach.LocalPath()
  87. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  88. return nil, fmt.Errorf("MkdirAll: %v", err)
  89. }
  90. fw, err := os.Create(localPath)
  91. if err != nil {
  92. return nil, fmt.Errorf("Create: %v", err)
  93. }
  94. defer fw.Close()
  95. if _, err = fw.Write(buf); err != nil {
  96. return nil, fmt.Errorf("Write: %v", err)
  97. } else if _, err = io.Copy(fw, file); err != nil {
  98. return nil, fmt.Errorf("Copy: %v", err)
  99. }
  100. if _, err := x.Insert(attach); err != nil {
  101. return nil, err
  102. }
  103. return attach, nil
  104. }
  105. // GetAttachmentByID returns attachment by given id
  106. func GetAttachmentByID(id int64) (*Attachment, error) {
  107. return getAttachmentByID(x, id)
  108. }
  109. func getAttachmentByID(e Engine, id int64) (*Attachment, error) {
  110. attach := &Attachment{ID: id}
  111. if has, err := e.Get(attach); err != nil {
  112. return nil, err
  113. } else if !has {
  114. return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
  115. }
  116. return attach, nil
  117. }
  118. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  119. attach := &Attachment{UUID: uuid}
  120. has, err := e.Get(attach)
  121. if err != nil {
  122. return nil, err
  123. } else if !has {
  124. return nil, ErrAttachmentNotExist{0, uuid}
  125. }
  126. return attach, nil
  127. }
  128. func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
  129. if len(uuids) == 0 {
  130. return []*Attachment{}, nil
  131. }
  132. // Silently drop invalid uuids.
  133. attachments := make([]*Attachment, 0, len(uuids))
  134. return attachments, e.In("uuid", uuids).Find(&attachments)
  135. }
  136. // GetAttachmentByUUID returns attachment by given UUID.
  137. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  138. return getAttachmentByUUID(x, uuid)
  139. }
  140. func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
  141. attachments := make([]*Attachment, 0, 10)
  142. return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  143. }
  144. // GetAttachmentsByIssueID returns all attachments of an issue.
  145. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  146. return getAttachmentsByIssueID(x, issueID)
  147. }
  148. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  149. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  150. return getAttachmentsByCommentID(x, commentID)
  151. }
  152. func getAttachmentsByCommentID(e Engine, commentID int64) ([]*Attachment, error) {
  153. attachments := make([]*Attachment, 0, 10)
  154. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  155. }
  156. // DeleteAttachment deletes the given attachment and optionally the associated file.
  157. func DeleteAttachment(a *Attachment, remove bool) error {
  158. _, err := DeleteAttachments([]*Attachment{a}, remove)
  159. return err
  160. }
  161. // DeleteAttachments deletes the given attachments and optionally the associated files.
  162. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  163. if len(attachments) == 0 {
  164. return 0, nil
  165. }
  166. var ids = make([]int64, 0, len(attachments))
  167. for _, a := range attachments {
  168. ids = append(ids, a.ID)
  169. }
  170. cnt, err := x.In("id", ids).NoAutoCondition().Delete(attachments[0])
  171. if err != nil {
  172. return 0, err
  173. }
  174. if remove {
  175. for i, a := range attachments {
  176. if err := os.Remove(a.LocalPath()); err != nil {
  177. return i, err
  178. }
  179. }
  180. }
  181. return int(cnt), nil
  182. }
  183. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  184. func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
  185. attachments, err := GetAttachmentsByIssueID(issueID)
  186. if err != nil {
  187. return 0, err
  188. }
  189. return DeleteAttachments(attachments, remove)
  190. }
  191. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  192. func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
  193. attachments, err := GetAttachmentsByCommentID(commentID)
  194. if err != nil {
  195. return 0, err
  196. }
  197. return DeleteAttachments(attachments, remove)
  198. }
  199. // UpdateAttachment updates the given attachment in database
  200. func UpdateAttachment(atta *Attachment) error {
  201. return updateAttachment(x, atta)
  202. }
  203. func updateAttachment(e Engine, atta *Attachment) error {
  204. var sess *xorm.Session
  205. if atta.ID != 0 && atta.UUID == "" {
  206. sess = e.ID(atta.ID)
  207. } else {
  208. // Use uuid only if id is not set and uuid is set
  209. sess = e.Where("uuid = ?", atta.UUID)
  210. }
  211. _, err := sess.Cols("name", "issue_id", "release_id", "comment_id", "download_count").Update(atta)
  212. return err
  213. }