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.

action.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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, or falls back to the username if it is blank.
  112. func (a *Action) GetDisplayName() string {
  113. if setting.UI.DefaultShowFullName {
  114. trimmedFullName := strings.TrimSpace(a.GetActFullName())
  115. if len(trimmedFullName) > 0 {
  116. return trimmedFullName
  117. }
  118. }
  119. return a.ShortActUserName()
  120. }
  121. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  122. func (a *Action) GetDisplayNameTitle() string {
  123. if setting.UI.DefaultShowFullName {
  124. return a.ShortActUserName()
  125. }
  126. return a.GetActFullName()
  127. }
  128. // GetActAvatar the action's user's avatar link
  129. func (a *Action) GetActAvatar() string {
  130. a.loadActUser()
  131. return a.ActUser.RelAvatarLink()
  132. }
  133. // GetRepoUserName returns the name of the action repository owner.
  134. func (a *Action) GetRepoUserName() string {
  135. a.loadRepo()
  136. return a.Repo.MustOwner().Name
  137. }
  138. // ShortRepoUserName returns the name of the action repository owner
  139. // trimmed to max 20 chars.
  140. func (a *Action) ShortRepoUserName() string {
  141. return base.EllipsisString(a.GetRepoUserName(), 20)
  142. }
  143. // GetRepoName returns the name of the action repository.
  144. func (a *Action) GetRepoName() string {
  145. a.loadRepo()
  146. return a.Repo.Name
  147. }
  148. // ShortRepoName returns the name of the action repository
  149. // trimmed to max 33 chars.
  150. func (a *Action) ShortRepoName() string {
  151. return base.EllipsisString(a.GetRepoName(), 33)
  152. }
  153. // GetRepoPath returns the virtual path to the action repository.
  154. func (a *Action) GetRepoPath() string {
  155. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  156. }
  157. // ShortRepoPath returns the virtual path to the action repository
  158. // trimmed to max 20 + 1 + 33 chars.
  159. func (a *Action) ShortRepoPath() string {
  160. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  161. }
  162. // GetRepoLink returns relative link to action repository.
  163. func (a *Action) GetRepoLink() string {
  164. if len(setting.AppSubURL) > 0 {
  165. return path.Join(setting.AppSubURL, a.GetRepoPath())
  166. }
  167. return "/" + a.GetRepoPath()
  168. }
  169. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  170. func GetRepositoryFromMatch(ownerName string, repoName string) (*Repository, error) {
  171. var err error
  172. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  173. if err != nil {
  174. if IsErrRepoNotExist(err) {
  175. log.Warn("Repository referenced in commit but does not exist: %v", err)
  176. return nil, err
  177. }
  178. log.Error("GetRepositoryByOwnerAndName: %v", err)
  179. return nil, err
  180. }
  181. return refRepo, nil
  182. }
  183. // GetCommentLink returns link to action comment.
  184. func (a *Action) GetCommentLink() string {
  185. return a.getCommentLink(x)
  186. }
  187. func (a *Action) getCommentLink(e Engine) string {
  188. if a == nil {
  189. return "#"
  190. }
  191. if a.Comment == nil && a.CommentID != 0 {
  192. a.Comment, _ = getCommentByID(e, a.CommentID)
  193. }
  194. if a.Comment != nil {
  195. return a.Comment.HTMLURL()
  196. }
  197. if len(a.GetIssueInfos()) == 0 {
  198. return "#"
  199. }
  200. //Return link to issue
  201. issueIDString := a.GetIssueInfos()[0]
  202. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  203. if err != nil {
  204. return "#"
  205. }
  206. issue, err := getIssueByID(e, issueID)
  207. if err != nil {
  208. return "#"
  209. }
  210. if err = issue.loadRepo(e); err != nil {
  211. return "#"
  212. }
  213. return issue.HTMLURL()
  214. }
  215. // GetBranch returns the action's repository branch.
  216. func (a *Action) GetBranch() string {
  217. return a.RefName
  218. }
  219. // GetContent returns the action's content.
  220. func (a *Action) GetContent() string {
  221. return a.Content
  222. }
  223. // GetCreate returns the action creation time.
  224. func (a *Action) GetCreate() time.Time {
  225. return a.CreatedUnix.AsTime()
  226. }
  227. // GetIssueInfos returns a list of issues associated with
  228. // the action.
  229. func (a *Action) GetIssueInfos() []string {
  230. return strings.SplitN(a.Content, "|", 2)
  231. }
  232. // GetIssueTitle returns the title of first issue associated
  233. // with the action.
  234. func (a *Action) GetIssueTitle() string {
  235. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  236. issue, err := GetIssueByIndex(a.RepoID, index)
  237. if err != nil {
  238. log.Error("GetIssueByIndex: %v", err)
  239. return "500 when get issue"
  240. }
  241. return issue.Title
  242. }
  243. // GetIssueContent returns the content of first issue associated with
  244. // this action.
  245. func (a *Action) GetIssueContent() string {
  246. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  247. issue, err := GetIssueByIndex(a.RepoID, index)
  248. if err != nil {
  249. log.Error("GetIssueByIndex: %v", err)
  250. return "500 when get issue"
  251. }
  252. return issue.Content
  253. }
  254. // PushCommit represents a commit in a push operation.
  255. type PushCommit struct {
  256. Sha1 string
  257. Message string
  258. AuthorEmail string
  259. AuthorName string
  260. CommitterEmail string
  261. CommitterName string
  262. Timestamp time.Time
  263. }
  264. // PushCommits represents list of commits in a push operation.
  265. type PushCommits struct {
  266. Len int
  267. Commits []*PushCommit
  268. CompareURL string
  269. avatars map[string]string
  270. emailUsers map[string]*User
  271. }
  272. // NewPushCommits creates a new PushCommits object.
  273. func NewPushCommits() *PushCommits {
  274. return &PushCommits{
  275. avatars: make(map[string]string),
  276. emailUsers: make(map[string]*User),
  277. }
  278. }
  279. // ToAPIPayloadCommits converts a PushCommits object to
  280. // api.PayloadCommit format.
  281. func (pc *PushCommits) ToAPIPayloadCommits(repoPath, repoLink string) ([]*api.PayloadCommit, error) {
  282. commits := make([]*api.PayloadCommit, len(pc.Commits))
  283. if pc.emailUsers == nil {
  284. pc.emailUsers = make(map[string]*User)
  285. }
  286. var err error
  287. for i, commit := range pc.Commits {
  288. authorUsername := ""
  289. author, ok := pc.emailUsers[commit.AuthorEmail]
  290. if !ok {
  291. author, err = GetUserByEmail(commit.AuthorEmail)
  292. if err == nil {
  293. authorUsername = author.Name
  294. pc.emailUsers[commit.AuthorEmail] = author
  295. }
  296. } else {
  297. authorUsername = author.Name
  298. }
  299. committerUsername := ""
  300. committer, ok := pc.emailUsers[commit.CommitterEmail]
  301. if !ok {
  302. committer, err = GetUserByEmail(commit.CommitterEmail)
  303. if err == nil {
  304. // TODO: check errors other than email not found.
  305. committerUsername = committer.Name
  306. pc.emailUsers[commit.CommitterEmail] = committer
  307. }
  308. } else {
  309. committerUsername = committer.Name
  310. }
  311. fileStatus, err := git.GetCommitFileStatus(repoPath, commit.Sha1)
  312. if err != nil {
  313. return nil, fmt.Errorf("FileStatus [commit_sha1: %s]: %v", commit.Sha1, err)
  314. }
  315. commits[i] = &api.PayloadCommit{
  316. ID: commit.Sha1,
  317. Message: commit.Message,
  318. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  319. Author: &api.PayloadUser{
  320. Name: commit.AuthorName,
  321. Email: commit.AuthorEmail,
  322. UserName: authorUsername,
  323. },
  324. Committer: &api.PayloadUser{
  325. Name: commit.CommitterName,
  326. Email: commit.CommitterEmail,
  327. UserName: committerUsername,
  328. },
  329. Added: fileStatus.Added,
  330. Removed: fileStatus.Removed,
  331. Modified: fileStatus.Modified,
  332. Timestamp: commit.Timestamp,
  333. }
  334. }
  335. return commits, nil
  336. }
  337. // AvatarLink tries to match user in database with e-mail
  338. // in order to show custom avatar, and falls back to general avatar link.
  339. func (pc *PushCommits) AvatarLink(email string) string {
  340. if pc.avatars == nil {
  341. pc.avatars = make(map[string]string)
  342. }
  343. avatar, ok := pc.avatars[email]
  344. if ok {
  345. return avatar
  346. }
  347. u, ok := pc.emailUsers[email]
  348. if !ok {
  349. var err error
  350. u, err = GetUserByEmail(email)
  351. if err != nil {
  352. pc.avatars[email] = base.AvatarLink(email)
  353. if !IsErrUserNotExist(err) {
  354. log.Error("GetUserByEmail: %v", err)
  355. return ""
  356. }
  357. } else {
  358. pc.emailUsers[email] = u
  359. }
  360. }
  361. if u != nil {
  362. pc.avatars[email] = u.RelAvatarLink()
  363. }
  364. return pc.avatars[email]
  365. }
  366. // GetFeedsOptions options for retrieving feeds
  367. type GetFeedsOptions struct {
  368. RequestedUser *User
  369. RequestingUserID int64
  370. IncludePrivate bool // include private actions
  371. OnlyPerformedBy bool // only actions performed by requested user
  372. IncludeDeleted bool // include deleted actions
  373. }
  374. // GetFeeds returns actions according to the provided options
  375. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  376. cond := builder.NewCond()
  377. var repoIDs []int64
  378. if opts.RequestedUser.IsOrganization() {
  379. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  380. if err != nil {
  381. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  382. }
  383. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  384. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  385. }
  386. cond = cond.And(builder.In("repo_id", repoIDs))
  387. } else {
  388. cond = cond.And(builder.In("repo_id", AccessibleRepoIDsQuery(opts.RequestingUserID)))
  389. }
  390. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  391. if opts.OnlyPerformedBy {
  392. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  393. }
  394. if !opts.IncludePrivate {
  395. cond = cond.And(builder.Eq{"is_private": false})
  396. }
  397. if !opts.IncludeDeleted {
  398. cond = cond.And(builder.Eq{"is_deleted": false})
  399. }
  400. actions := make([]*Action, 0, 20)
  401. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  402. return nil, fmt.Errorf("Find: %v", err)
  403. }
  404. if err := ActionList(actions).LoadAttributes(); err != nil {
  405. return nil, fmt.Errorf("LoadAttributes: %v", err)
  406. }
  407. return actions, nil
  408. }