You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

action.go 14 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
3 years ago
2 years ago
2 years ago
2 years ago
11 years ago
8 years ago
11 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
9 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
8 years ago
11 years ago
11 years ago
8 years ago
11 years ago
11 years ago
8 years ago
8 years ago
8 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
9 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
3 years ago
2 years ago
2 years ago
2 years ago
3 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
5 years ago
11 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/timeutil"
  16. "github.com/unknwon/com"
  17. "xorm.io/builder"
  18. )
  19. // ActionType represents the type of an action.
  20. type ActionType int
  21. // Possible action types.
  22. const (
  23. ActionCreateRepo ActionType = iota + 1 // 1
  24. ActionRenameRepo // 2
  25. ActionStarRepo // 3
  26. ActionWatchRepo // 4
  27. ActionCommitRepo // 5
  28. ActionCreateIssue // 6
  29. ActionCreatePullRequest // 7
  30. ActionTransferRepo // 8
  31. ActionPushTag // 9
  32. ActionCommentIssue // 10
  33. ActionMergePullRequest // 11
  34. ActionCloseIssue // 12
  35. ActionReopenIssue // 13
  36. ActionClosePullRequest // 14
  37. ActionReopenPullRequest // 15
  38. ActionDeleteTag // 16
  39. ActionDeleteBranch // 17
  40. ActionMirrorSyncPush // 18
  41. ActionMirrorSyncCreate // 19
  42. ActionMirrorSyncDelete // 20
  43. ActionApprovePullRequest // 21
  44. ActionRejectPullRequest // 22
  45. ActionCommentPull // 23
  46. ActionUploadAttachment //24
  47. ActionCreateDebugGPUTask //25
  48. ActionCreateDebugNPUTask //26
  49. ActionCreateTrainTask //27
  50. ActionCreateInferenceTask // 28
  51. ActionCreateBenchMarkTask //29
  52. ActionCreateNewModelTask //30
  53. ActionCreateGPUTrainTask //31
  54. ActionCreateGrampusNPUTrainTask //32
  55. ActionCreateGrampusGPUTrainTask //33
  56. ActionBindWechat //34
  57. ActionDatasetRecommended //35
  58. ActionCreateImage //36
  59. ActionImageRecommend //37
  60. ActionChangeUserAvatar //38
  61. ActionCreateGrampusNPUDebugTask //39
  62. ActionCreateGrampusGPUDebugTask //40
  63. ActionCreateGrampusGCUDebugTask //41
  64. )
  65. // Action represents user operation type and other information to
  66. // repository. It implemented interface base.Actioner so that can be
  67. // used in template render.
  68. type Action struct {
  69. ID int64 `xorm:"pk autoincr"`
  70. UserID int64 `xorm:"INDEX"` // Receiver user id.
  71. OpType ActionType
  72. ActUserID int64 `xorm:"INDEX"` // Action user id.
  73. ActUser *User `xorm:"-"`
  74. RepoID int64 `xorm:"INDEX"`
  75. Repo *Repository `xorm:"-"`
  76. CommentID int64 `xorm:"INDEX"`
  77. Comment *Comment `xorm:"-"`
  78. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  79. RefName string
  80. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  81. IsTransformed bool `xorm:"INDEX NOT NULL DEFAULT false"`
  82. Content string `xorm:"TEXT"`
  83. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  84. Cloudbrain *Cloudbrain `xorm:"-"`
  85. }
  86. type ActionShow struct {
  87. OpType ActionType
  88. TaskType TaskType
  89. RepoLink string
  90. ShortRepoFullDisplayName string
  91. Content string
  92. RefName string
  93. IssueInfos []string
  94. CommentLink string
  95. Cloudbrain *CloudbrainShow4Action
  96. }
  97. // GetOpType gets the ActionType of this action.
  98. func (a *Action) GetOpType() ActionType {
  99. return a.OpType
  100. }
  101. func (a *Action) loadActUser() {
  102. if a.ActUser != nil {
  103. return
  104. }
  105. var err error
  106. a.ActUser, err = GetUserByID(a.ActUserID)
  107. if err == nil {
  108. return
  109. } else if IsErrUserNotExist(err) {
  110. a.ActUser = NewGhostUser()
  111. } else {
  112. log.Error("GetUserByID(%d): %v", a.ActUserID, err)
  113. }
  114. }
  115. func (a *Action) loadRepo() {
  116. if a.Repo != nil {
  117. return
  118. }
  119. var err error
  120. a.Repo, err = GetRepositoryByID(a.RepoID)
  121. if err != nil {
  122. log.Error("GetRepositoryByID(%d): %v", a.RepoID, err)
  123. }
  124. }
  125. // GetActFullName gets the action's user full name.
  126. func (a *Action) GetActFullName() string {
  127. a.loadActUser()
  128. return a.ActUser.FullName
  129. }
  130. // GetActUserName gets the action's user name.
  131. func (a *Action) GetActUserName() string {
  132. a.loadActUser()
  133. return a.ActUser.Name
  134. }
  135. // ShortActUserName gets the action's user name trimmed to max 20
  136. // chars.
  137. func (a *Action) ShortActUserName() string {
  138. return base.EllipsisString(a.GetActUserName(), 20)
  139. }
  140. // GetDisplayName gets the action's display name based on DEFAULT_SHOW_FULL_NAME, or falls back to the username if it is blank.
  141. func (a *Action) GetDisplayName() string {
  142. if setting.UI.DefaultShowFullName {
  143. trimmedFullName := strings.TrimSpace(a.GetActFullName())
  144. if len(trimmedFullName) > 0 {
  145. return trimmedFullName
  146. }
  147. }
  148. return a.ShortActUserName()
  149. }
  150. // GetDisplayNameTitle gets the action's display name used for the title (tooltip) based on DEFAULT_SHOW_FULL_NAME
  151. func (a *Action) GetDisplayNameTitle() string {
  152. if setting.UI.DefaultShowFullName {
  153. return a.ShortActUserName()
  154. }
  155. return a.GetActFullName()
  156. }
  157. // GetActAvatar the action's user's avatar link
  158. func (a *Action) GetActAvatar() string {
  159. a.loadActUser()
  160. return a.ActUser.RelAvatarLink()
  161. }
  162. // GetRepoUserName returns the name of the action repository owner.
  163. func (a *Action) GetRepoUserName() string {
  164. a.loadRepo()
  165. return a.Repo.OwnerName
  166. }
  167. // ShortRepoUserName returns the name of the action repository owner
  168. // trimmed to max 20 chars.
  169. func (a *Action) ShortRepoUserName() string {
  170. return base.EllipsisString(a.GetRepoUserName(), 20)
  171. }
  172. // GetRepoName returns the name of the action repository.
  173. func (a *Action) GetRepoName() string {
  174. a.loadRepo()
  175. return a.Repo.Name
  176. }
  177. // GetRepoName returns the name of the action repository.
  178. func (a *Action) GetRepoDisplayName() string {
  179. a.loadRepo()
  180. return a.Repo.DisplayName()
  181. }
  182. // ShortRepoName returns the name of the action repository
  183. // trimmed to max 33 chars.
  184. func (a *Action) ShortRepoName() string {
  185. return base.EllipsisString(a.GetRepoName(), 33)
  186. }
  187. // ShortRepoName returns the name of the action repository
  188. // trimmed to max 33 chars.
  189. func (a *Action) ShortRepoDisplayName() string {
  190. return base.EllipsisString(a.GetRepoDisplayName(), 33)
  191. }
  192. // GetRepoPath returns the virtual path to the action repository.
  193. func (a *Action) GetRepoPath() string {
  194. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  195. }
  196. // ShortRepoPath returns the virtual path to the action repository
  197. // trimmed to max 20 + 1 + 33 chars.
  198. func (a *Action) ShortRepoPath() string {
  199. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  200. }
  201. // ShortRepoPath returns the virtual path to the action repository
  202. // trimmed to max 20 + 1 + 33 chars.
  203. func (a *Action) ShortRepoFullDisplayName() string {
  204. return path.Join(a.ShortRepoUserName(), a.ShortRepoDisplayName())
  205. }
  206. // GetRepoLink returns relative link to action repository.
  207. func (a *Action) GetRepoLink() string {
  208. if len(setting.AppSubURL) > 0 {
  209. return path.Join(setting.AppSubURL, a.GetRepoPath())
  210. }
  211. return "/" + a.GetRepoPath()
  212. }
  213. func (a *Action) ToShow() *ActionShow {
  214. actionShow := &ActionShow{}
  215. actionShow.OpType = a.OpType
  216. actionShow.TaskType = GetTaskTypeFromAction(a.OpType)
  217. actionShow.Content = a.Content
  218. actionShow.RefName = a.RefName
  219. if strings.Contains(a.Content, "|") && a.IsIssueAction() {
  220. actionShow.IssueInfos = a.GetIssueInfos()
  221. }
  222. if a.Repo != nil {
  223. actionShow.RepoLink = a.GetRepoLink()
  224. actionShow.ShortRepoFullDisplayName = a.ShortRepoFullDisplayName()
  225. }
  226. if a.Comment != nil {
  227. actionShow.CommentLink = a.GetCommentLink()
  228. }
  229. if a.Cloudbrain != nil {
  230. c := &CloudbrainShow4Action{
  231. ID: a.Cloudbrain.ID,
  232. JobID: a.Cloudbrain.JobID,
  233. Type: a.Cloudbrain.Type,
  234. JobType: a.Cloudbrain.JobType,
  235. DisplayJobName: a.Cloudbrain.DisplayJobName,
  236. ComputeResource: a.Cloudbrain.ComputeResource,
  237. }
  238. actionShow.Cloudbrain = c
  239. }
  240. return actionShow
  241. }
  242. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  243. func GetRepositoryFromMatch(ownerName string, repoName string) (*Repository, error) {
  244. var err error
  245. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  246. if err != nil {
  247. if IsErrRepoNotExist(err) {
  248. log.Warn("Repository referenced in commit but does not exist: %v", err)
  249. return nil, err
  250. }
  251. log.Error("GetRepositoryByOwnerAndName: %v", err)
  252. return nil, err
  253. }
  254. return refRepo, nil
  255. }
  256. // GetCommentLink returns link to action comment.
  257. func (a *Action) GetCommentLink() string {
  258. return a.getCommentLink(x)
  259. }
  260. func (a *Action) getCommentLink(e Engine) string {
  261. if a == nil {
  262. return "#"
  263. }
  264. if a.Comment == nil && a.CommentID != 0 {
  265. a.Comment, _ = getCommentByID(e, a.CommentID)
  266. }
  267. if a.Comment != nil {
  268. return a.Comment.HTMLURL()
  269. }
  270. if len(a.GetIssueInfos()) == 0 {
  271. return "#"
  272. }
  273. //Return link to issue
  274. issueIDString := a.GetIssueInfos()[0]
  275. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  276. if err != nil {
  277. return "#"
  278. }
  279. issue, err := getIssueByID(e, issueID)
  280. if err != nil {
  281. return "#"
  282. }
  283. if err = issue.loadRepo(e); err != nil {
  284. return "#"
  285. }
  286. return issue.HTMLURL()
  287. }
  288. // GetBranch returns the action's repository branch.
  289. func (a *Action) GetBranch() string {
  290. return a.RefName
  291. }
  292. // GetContent returns the action's content.
  293. func (a *Action) GetContent() string {
  294. return a.Content
  295. }
  296. // GetCreate returns the action creation time.
  297. func (a *Action) GetCreate() time.Time {
  298. return a.CreatedUnix.AsTime()
  299. }
  300. // GetIssueInfos returns a list of issues associated with
  301. // the action.
  302. func (a *Action) GetIssueInfos() []string {
  303. return strings.SplitN(a.Content, "|", 2)
  304. }
  305. // GetIssueTitle returns the title of first issue associated
  306. // with the action.
  307. func (a *Action) GetIssueTitle() string {
  308. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  309. issue, err := GetIssueByIndex(a.RepoID, index)
  310. if err != nil {
  311. log.Error("GetIssueByIndex: %v", err)
  312. return "500 when get issue"
  313. }
  314. return issue.Title
  315. }
  316. // GetIssueContent returns the content of first issue associated with
  317. // this action.
  318. func (a *Action) GetIssueContent() string {
  319. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  320. issue, err := GetIssueByIndex(a.RepoID, index)
  321. if err != nil {
  322. log.Error("GetIssueByIndex: %v", err)
  323. return "500 when get issue"
  324. }
  325. return issue.Content
  326. }
  327. func (a *Action) IsCloudbrainAction() bool {
  328. switch a.OpType {
  329. case ActionCreateDebugGPUTask,
  330. ActionCreateDebugNPUTask,
  331. ActionCreateTrainTask,
  332. ActionCreateInferenceTask,
  333. ActionCreateBenchMarkTask,
  334. ActionCreateGPUTrainTask,
  335. ActionCreateGrampusGPUDebugTask,
  336. ActionCreateGrampusNPUDebugTask,
  337. ActionCreateGrampusNPUTrainTask,
  338. ActionCreateGrampusGPUTrainTask,
  339. ActionCreateGrampusGCUDebugTask:
  340. return true
  341. }
  342. return false
  343. }
  344. func (a *Action) IsIssueAction() bool {
  345. switch a.OpType {
  346. case ActionCreateIssue,
  347. ActionCloseIssue,
  348. ActionClosePullRequest,
  349. ActionReopenIssue,
  350. ActionReopenPullRequest,
  351. ActionCommentPull,
  352. ActionCommentIssue,
  353. ActionCreatePullRequest,
  354. ActionApprovePullRequest,
  355. ActionRejectPullRequest,
  356. ActionMergePullRequest:
  357. return true
  358. }
  359. return false
  360. }
  361. // GetFeedsOptions options for retrieving feeds
  362. type GetFeedsOptions struct {
  363. RequestedUser *User // the user we want activity for
  364. Actor *User // the user viewing the activity
  365. IncludePrivate bool // include private actions
  366. OnlyPerformedBy bool // only actions performed by requested user
  367. IncludeDeleted bool // include deleted actions
  368. }
  369. // GetFeeds returns actions according to the provided options
  370. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  371. cond := builder.NewCond()
  372. var repoIDs []int64
  373. var actorID int64
  374. if opts.Actor != nil {
  375. actorID = opts.Actor.ID
  376. }
  377. if opts.RequestedUser.IsOrganization() {
  378. env, err := opts.RequestedUser.AccessibleReposEnv(actorID)
  379. if err != nil {
  380. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  381. }
  382. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  383. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  384. }
  385. cond = cond.And(builder.In("repo_id", repoIDs))
  386. } else {
  387. cond = cond.And(builder.In("repo_id", AccessibleRepoIDsQuery(opts.Actor)))
  388. }
  389. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  390. if opts.OnlyPerformedBy {
  391. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  392. }
  393. if !opts.IncludePrivate {
  394. cond = cond.And(builder.Eq{"is_private": false})
  395. }
  396. if !opts.IncludeDeleted {
  397. cond = cond.And(builder.Eq{"is_deleted": false})
  398. }
  399. actions := make([]*Action, 0, 20)
  400. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  401. return nil, fmt.Errorf("Find: %v", err)
  402. }
  403. if err := ActionList(actions).LoadAttributes(); err != nil {
  404. return nil, fmt.Errorf("LoadAttributes: %v", err)
  405. }
  406. return actions, nil
  407. }
  408. func GetLast20PublicFeeds(opTypes []int) ([]*Action, error) {
  409. cond := builder.NewCond()
  410. cond = cond.And(builder.Eq{"is_private": false})
  411. cond = cond.And(builder.Eq{"is_deleted": false})
  412. cond = cond.And(builder.Expr("user_id=act_user_id"))
  413. cond = cond.And(builder.In("op_type", opTypes))
  414. actions := make([]*Action, 0, 20)
  415. if err := x.Limit(30).Desc("id").Where(cond).Find(&actions); err != nil {
  416. return nil, fmt.Errorf("Find: %v", err)
  417. }
  418. if err := ActionList(actions).LoadAttributes(); err != nil {
  419. return nil, fmt.Errorf("LoadAttributes: %v", err)
  420. }
  421. return actions, nil
  422. }
  423. func GetUnTransformedActions() ([]*Action, error) {
  424. actions := make([]*Action, 0, 10)
  425. err := x.Where("op_type = ?", ActionCommitRepo).
  426. And("content != ''").
  427. And("is_transformed = ?", false).
  428. And("to_timestamp(created_unix) >= ?", setting.CommitValidDate).
  429. Find(&actions)
  430. return actions, err
  431. }
  432. func GetActionByIds(ids []int64) ([]*Action, error) {
  433. if len(ids) == 0 {
  434. return nil, nil
  435. }
  436. actions := make([]*Action, 0)
  437. err := x.In("id", ids).Find(&actions)
  438. if err != nil {
  439. return nil, err
  440. }
  441. if err := ActionList(actions).LoadAllAttributes(); err != nil {
  442. return nil, fmt.Errorf("ActionList loadAttributes: %v", err)
  443. }
  444. return actions, nil
  445. }