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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. api "code.gitea.io/gitea/modules/structs"
  17. "code.gitea.io/gitea/modules/timeutil"
  18. "github.com/unknwon/com"
  19. "xorm.io/builder"
  20. )
  21. // ActionType represents the type of an action.
  22. type ActionType int
  23. // Possible action types.
  24. const (
  25. ActionCreateRepo ActionType = iota + 1 // 1
  26. ActionRenameRepo // 2
  27. ActionStarRepo // 3
  28. ActionWatchRepo // 4
  29. ActionCommitRepo // 5
  30. ActionCreateIssue // 6
  31. ActionCreatePullRequest // 7
  32. ActionTransferRepo // 8
  33. ActionPushTag // 9
  34. ActionCommentIssue // 10
  35. ActionMergePullRequest // 11
  36. ActionCloseIssue // 12
  37. ActionReopenIssue // 13
  38. ActionClosePullRequest // 14
  39. ActionReopenPullRequest // 15
  40. ActionDeleteTag // 16
  41. ActionDeleteBranch // 17
  42. ActionMirrorSyncPush // 18
  43. ActionMirrorSyncCreate // 19
  44. ActionMirrorSyncDelete // 20
  45. ActionApprovePullRequest // 21
  46. ActionRejectPullRequest // 22
  47. ActionCommentPull // 23
  48. )
  49. // Action represents user operation type and other information to
  50. // repository. It implemented interface base.Actioner so that can be
  51. // used in template render.
  52. type Action struct {
  53. ID int64 `xorm:"pk autoincr"`
  54. UserID int64 `xorm:"INDEX"` // Receiver user id.
  55. OpType ActionType
  56. ActUserID int64 `xorm:"INDEX"` // Action user id.
  57. ActUser *User `xorm:"-"`
  58. RepoID int64 `xorm:"INDEX"`
  59. Repo *Repository `xorm:"-"`
  60. CommentID int64 `xorm:"INDEX"`
  61. Comment *Comment `xorm:"-"`
  62. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  63. RefName string
  64. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  65. Content string `xorm:"TEXT"`
  66. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  67. }
  68. // GetOpType gets the ActionType of this action.
  69. func (a *Action) GetOpType() ActionType {
  70. return a.OpType
  71. }
  72. func (a *Action) loadActUser() {
  73. if a.ActUser != nil {
  74. return
  75. }
  76. var err error
  77. a.ActUser, err = GetUserByID(a.ActUserID)
  78. if err == nil {
  79. return
  80. } else if IsErrUserNotExist(err) {
  81. a.ActUser = NewGhostUser()
  82. } else {
  83. log.Error("GetUserByID(%d): %v", a.ActUserID, err)
  84. }
  85. }
  86. func (a *Action) loadRepo() {
  87. if a.Repo != nil {
  88. return
  89. }
  90. var err error
  91. a.Repo, err = GetRepositoryByID(a.RepoID)
  92. if err != nil {
  93. log.Error("GetRepositoryByID(%d): %v", a.RepoID, err)
  94. }
  95. }
  96. // GetActFullName gets the action's user full name.
  97. func (a *Action) GetActFullName() string {
  98. a.loadActUser()
  99. return a.ActUser.FullName
  100. }
  101. // GetActUserName gets the action's user name.
  102. func (a *Action) GetActUserName() string {
  103. a.loadActUser()
  104. return a.ActUser.Name
  105. }
  106. // ShortActUserName gets the action's user name trimmed to max 20
  107. // chars.
  108. func (a *Action) ShortActUserName() string {
  109. return base.EllipsisString(a.GetActUserName(), 20)
  110. }
  111. // GetDisplayName gets the action's display name based on DEFAULT_SHOW_FULL_NAME
  112. func (a *Action) GetDisplayName() string {
  113. if setting.UI.DefaultShowFullName {
  114. return a.GetActFullName()
  115. }
  116. return a.ShortActUserName()
  117. }
  118. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  119. func (a *Action) GetDisplayNameTitle() string {
  120. if setting.UI.DefaultShowFullName {
  121. return a.ShortActUserName()
  122. }
  123. return a.GetActFullName()
  124. }
  125. // GetActAvatar the action's user's avatar link
  126. func (a *Action) GetActAvatar() string {
  127. a.loadActUser()
  128. return a.ActUser.RelAvatarLink()
  129. }
  130. // GetRepoUserName returns the name of the action repository owner.
  131. func (a *Action) GetRepoUserName() string {
  132. a.loadRepo()
  133. return a.Repo.MustOwner().Name
  134. }
  135. // ShortRepoUserName returns the name of the action repository owner
  136. // trimmed to max 20 chars.
  137. func (a *Action) ShortRepoUserName() string {
  138. return base.EllipsisString(a.GetRepoUserName(), 20)
  139. }
  140. // GetRepoName returns the name of the action repository.
  141. func (a *Action) GetRepoName() string {
  142. a.loadRepo()
  143. return a.Repo.Name
  144. }
  145. // ShortRepoName returns the name of the action repository
  146. // trimmed to max 33 chars.
  147. func (a *Action) ShortRepoName() string {
  148. return base.EllipsisString(a.GetRepoName(), 33)
  149. }
  150. // GetRepoPath returns the virtual path to the action repository.
  151. func (a *Action) GetRepoPath() string {
  152. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  153. }
  154. // ShortRepoPath returns the virtual path to the action repository
  155. // trimmed to max 20 + 1 + 33 chars.
  156. func (a *Action) ShortRepoPath() string {
  157. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  158. }
  159. // GetRepoLink returns relative link to action repository.
  160. func (a *Action) GetRepoLink() string {
  161. if len(setting.AppSubURL) > 0 {
  162. return path.Join(setting.AppSubURL, a.GetRepoPath())
  163. }
  164. return "/" + a.GetRepoPath()
  165. }
  166. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  167. func GetRepositoryFromMatch(ownerName string, repoName string) (*Repository, error) {
  168. var err error
  169. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  170. if err != nil {
  171. if IsErrRepoNotExist(err) {
  172. log.Warn("Repository referenced in commit but does not exist: %v", err)
  173. return nil, err
  174. }
  175. log.Error("GetRepositoryByOwnerAndName: %v", err)
  176. return nil, err
  177. }
  178. return refRepo, nil
  179. }
  180. // GetCommentLink returns link to action comment.
  181. func (a *Action) GetCommentLink() string {
  182. return a.getCommentLink(x)
  183. }
  184. func (a *Action) getCommentLink(e Engine) string {
  185. if a == nil {
  186. return "#"
  187. }
  188. if a.Comment == nil && a.CommentID != 0 {
  189. a.Comment, _ = GetCommentByID(a.CommentID)
  190. }
  191. if a.Comment != nil {
  192. return a.Comment.HTMLURL()
  193. }
  194. if len(a.GetIssueInfos()) == 0 {
  195. return "#"
  196. }
  197. //Return link to issue
  198. issueIDString := a.GetIssueInfos()[0]
  199. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  200. if err != nil {
  201. return "#"
  202. }
  203. issue, err := getIssueByID(e, issueID)
  204. if err != nil {
  205. return "#"
  206. }
  207. if err = issue.loadRepo(e); err != nil {
  208. return "#"
  209. }
  210. return issue.HTMLURL()
  211. }
  212. // GetBranch returns the action's repository branch.
  213. func (a *Action) GetBranch() string {
  214. return a.RefName
  215. }
  216. // GetContent returns the action's content.
  217. func (a *Action) GetContent() string {
  218. return a.Content
  219. }
  220. // GetCreate returns the action creation time.
  221. func (a *Action) GetCreate() time.Time {
  222. return a.CreatedUnix.AsTime()
  223. }
  224. // GetIssueInfos returns a list of issues associated with
  225. // the action.
  226. func (a *Action) GetIssueInfos() []string {
  227. return strings.SplitN(a.Content, "|", 2)
  228. }
  229. // GetIssueTitle returns the title of first issue associated
  230. // with the action.
  231. func (a *Action) GetIssueTitle() string {
  232. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  233. issue, err := GetIssueByIndex(a.RepoID, index)
  234. if err != nil {
  235. log.Error("GetIssueByIndex: %v", err)
  236. return "500 when get issue"
  237. }
  238. return issue.Title
  239. }
  240. // GetIssueContent returns the content of first issue associated with
  241. // this action.
  242. func (a *Action) GetIssueContent() string {
  243. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  244. issue, err := GetIssueByIndex(a.RepoID, index)
  245. if err != nil {
  246. log.Error("GetIssueByIndex: %v", err)
  247. return "500 when get issue"
  248. }
  249. return issue.Content
  250. }
  251. // PushCommit represents a commit in a push operation.
  252. type PushCommit struct {
  253. Sha1 string
  254. Message string
  255. AuthorEmail string
  256. AuthorName string
  257. CommitterEmail string
  258. CommitterName string
  259. Timestamp time.Time
  260. }
  261. // PushCommits represents list of commits in a push operation.
  262. type PushCommits struct {
  263. Len int
  264. Commits []*PushCommit
  265. CompareURL string
  266. avatars map[string]string
  267. emailUsers map[string]*User
  268. }
  269. // NewPushCommits creates a new PushCommits object.
  270. func NewPushCommits() *PushCommits {
  271. return &PushCommits{
  272. avatars: make(map[string]string),
  273. emailUsers: make(map[string]*User),
  274. }
  275. }
  276. // ToAPIPayloadCommits converts a PushCommits object to
  277. // api.PayloadCommit format.
  278. func (pc *PushCommits) ToAPIPayloadCommits(repoPath, repoLink string) ([]*api.PayloadCommit, error) {
  279. commits := make([]*api.PayloadCommit, len(pc.Commits))
  280. if pc.emailUsers == nil {
  281. pc.emailUsers = make(map[string]*User)
  282. }
  283. var err error
  284. for i, commit := range pc.Commits {
  285. authorUsername := ""
  286. author, ok := pc.emailUsers[commit.AuthorEmail]
  287. if !ok {
  288. author, err = GetUserByEmail(commit.AuthorEmail)
  289. if err == nil {
  290. authorUsername = author.Name
  291. pc.emailUsers[commit.AuthorEmail] = author
  292. }
  293. } else {
  294. authorUsername = author.Name
  295. }
  296. committerUsername := ""
  297. committer, ok := pc.emailUsers[commit.CommitterEmail]
  298. if !ok {
  299. committer, err = GetUserByEmail(commit.CommitterEmail)
  300. if err == nil {
  301. // TODO: check errors other than email not found.
  302. committerUsername = committer.Name
  303. pc.emailUsers[commit.CommitterEmail] = committer
  304. }
  305. } else {
  306. committerUsername = committer.Name
  307. }
  308. fileStatus, err := git.GetCommitFileStatus(repoPath, commit.Sha1)
  309. if err != nil {
  310. return nil, fmt.Errorf("FileStatus [commit_sha1: %s]: %v", commit.Sha1, err)
  311. }
  312. commits[i] = &api.PayloadCommit{
  313. ID: commit.Sha1,
  314. Message: commit.Message,
  315. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  316. Author: &api.PayloadUser{
  317. Name: commit.AuthorName,
  318. Email: commit.AuthorEmail,
  319. UserName: authorUsername,
  320. },
  321. Committer: &api.PayloadUser{
  322. Name: commit.CommitterName,
  323. Email: commit.CommitterEmail,
  324. UserName: committerUsername,
  325. },
  326. Added: fileStatus.Added,
  327. Removed: fileStatus.Removed,
  328. Modified: fileStatus.Modified,
  329. Timestamp: commit.Timestamp,
  330. }
  331. }
  332. return commits, nil
  333. }
  334. // AvatarLink tries to match user in database with e-mail
  335. // in order to show custom avatar, and falls back to general avatar link.
  336. func (pc *PushCommits) AvatarLink(email string) string {
  337. if pc.avatars == nil {
  338. pc.avatars = make(map[string]string)
  339. }
  340. avatar, ok := pc.avatars[email]
  341. if ok {
  342. return avatar
  343. }
  344. u, ok := pc.emailUsers[email]
  345. if !ok {
  346. var err error
  347. u, err = GetUserByEmail(email)
  348. if err != nil {
  349. pc.avatars[email] = base.AvatarLink(email)
  350. if !IsErrUserNotExist(err) {
  351. log.Error("GetUserByEmail: %v", err)
  352. return ""
  353. }
  354. } else {
  355. pc.emailUsers[email] = u
  356. }
  357. }
  358. if u != nil {
  359. pc.avatars[email] = u.RelAvatarLink()
  360. }
  361. return pc.avatars[email]
  362. }
  363. // GetFeedsOptions options for retrieving feeds
  364. type GetFeedsOptions struct {
  365. RequestedUser *User
  366. RequestingUserID int64
  367. IncludePrivate bool // include private actions
  368. OnlyPerformedBy bool // only actions performed by requested user
  369. IncludeDeleted bool // include deleted actions
  370. }
  371. // GetFeeds returns actions according to the provided options
  372. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  373. cond := builder.NewCond()
  374. var repoIDs []int64
  375. if opts.RequestedUser.IsOrganization() {
  376. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  377. if err != nil {
  378. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  379. }
  380. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  381. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  382. }
  383. cond = cond.And(builder.In("repo_id", repoIDs))
  384. }
  385. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  386. if opts.OnlyPerformedBy {
  387. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  388. }
  389. if !opts.IncludePrivate {
  390. cond = cond.And(builder.Eq{"is_private": false})
  391. }
  392. if !opts.IncludeDeleted {
  393. cond = cond.And(builder.Eq{"is_deleted": false})
  394. }
  395. actions := make([]*Action, 0, 20)
  396. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  397. return nil, fmt.Errorf("Find: %v", err)
  398. }
  399. if err := ActionList(actions).LoadAttributes(); err != nil {
  400. return nil, fmt.Errorf("LoadAttributes: %v", err)
  401. }
  402. return actions, nil
  403. }