本站源代码
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.

264 lines
7.5KB

  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. // NewAttachment creates a new attachment object.
  63. func NewAttachment(attach *Attachment, buf []byte, file io.Reader) (_ *Attachment, err error) {
  64. attach.UUID = gouuid.NewV4().String()
  65. localPath := attach.LocalPath()
  66. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  67. return nil, fmt.Errorf("MkdirAll: %v", err)
  68. }
  69. fw, err := os.Create(localPath)
  70. if err != nil {
  71. return nil, fmt.Errorf("Create: %v", err)
  72. }
  73. defer fw.Close()
  74. if _, err = fw.Write(buf); err != nil {
  75. return nil, fmt.Errorf("Write: %v", err)
  76. } else if _, err = io.Copy(fw, file); err != nil {
  77. return nil, fmt.Errorf("Copy: %v", err)
  78. }
  79. // Update file size
  80. var fi os.FileInfo
  81. if fi, err = fw.Stat(); err != nil {
  82. return nil, fmt.Errorf("file size: %v", err)
  83. }
  84. attach.Size = fi.Size()
  85. if _, err := x.Insert(attach); err != nil {
  86. return nil, err
  87. }
  88. return attach, nil
  89. }
  90. // GetAttachmentByID returns attachment by given id
  91. func GetAttachmentByID(id int64) (*Attachment, error) {
  92. return getAttachmentByID(x, id)
  93. }
  94. func getAttachmentByID(e Engine, id int64) (*Attachment, error) {
  95. attach := &Attachment{ID: id}
  96. if has, err := e.Get(attach); err != nil {
  97. return nil, err
  98. } else if !has {
  99. return nil, ErrAttachmentNotExist{ID: id, UUID: ""}
  100. }
  101. return attach, nil
  102. }
  103. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  104. attach := &Attachment{UUID: uuid}
  105. has, err := e.Get(attach)
  106. if err != nil {
  107. return nil, err
  108. } else if !has {
  109. return nil, ErrAttachmentNotExist{0, uuid}
  110. }
  111. return attach, nil
  112. }
  113. func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
  114. if len(uuids) == 0 {
  115. return []*Attachment{}, nil
  116. }
  117. // Silently drop invalid uuids.
  118. attachments := make([]*Attachment, 0, len(uuids))
  119. return attachments, e.In("uuid", uuids).Find(&attachments)
  120. }
  121. // GetAttachmentByUUID returns attachment by given UUID.
  122. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  123. return getAttachmentByUUID(x, uuid)
  124. }
  125. // GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
  126. func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) {
  127. return getAttachmentByReleaseIDFileName(x, releaseID, fileName)
  128. }
  129. func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
  130. attachments := make([]*Attachment, 0, 10)
  131. return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  132. }
  133. // GetAttachmentsByIssueID returns all attachments of an issue.
  134. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  135. return getAttachmentsByIssueID(x, issueID)
  136. }
  137. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  138. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  139. return getAttachmentsByCommentID(x, commentID)
  140. }
  141. func getAttachmentsByCommentID(e Engine, commentID int64) ([]*Attachment, error) {
  142. attachments := make([]*Attachment, 0, 10)
  143. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  144. }
  145. // getAttachmentByReleaseIDFileName return a file based on the the following infos:
  146. func getAttachmentByReleaseIDFileName(e Engine, releaseID int64, fileName string) (*Attachment, error) {
  147. attach := &Attachment{ReleaseID: releaseID, Name: fileName}
  148. has, err := e.Get(attach)
  149. if err != nil {
  150. return nil, err
  151. } else if !has {
  152. return nil, err
  153. }
  154. return attach, nil
  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. }
  214. // DeleteAttachmentsByRelease deletes all attachments associated with the given release.
  215. func DeleteAttachmentsByRelease(releaseID int64) error {
  216. _, err := x.Where("release_id = ?", releaseID).Delete(&Attachment{})
  217. return err
  218. }
上海开阖软件有限公司 沪ICP备12045867号-1