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.

repo_watch.go 9.1 kB

3 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. "code.gitea.io/gitea/modules/setting"
  8. )
  9. // RepoWatchMode specifies what kind of watch the user has on a repository
  10. type RepoWatchMode int8
  11. const (
  12. // RepoWatchModeNone don't watch
  13. RepoWatchModeNone RepoWatchMode = iota // 0
  14. // RepoWatchModeNormal watch repository (from other sources)
  15. RepoWatchModeNormal // 1
  16. // RepoWatchModeDont explicit don't auto-watch
  17. RepoWatchModeDont // 2
  18. // RepoWatchModeAuto watch repository (from AutoWatchOnChanges)
  19. RepoWatchModeAuto // 3
  20. )
  21. var ActionChan = make(chan *Action, 200)
  22. var ActionChan4Task = make(chan Action, 200)
  23. // Watch is connection request for receiving repository notification.
  24. type Watch struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. UserID int64 `xorm:"UNIQUE(watch)"`
  27. RepoID int64 `xorm:"UNIQUE(watch)"`
  28. Mode RepoWatchMode `xorm:"SMALLINT NOT NULL DEFAULT 1"`
  29. CreatedUnix int64 `xorm:"created"`
  30. }
  31. // getWatch gets what kind of subscription a user has on a given repository; returns dummy record if none found
  32. func getWatch(e Engine, userID, repoID int64) (Watch, error) {
  33. watch := Watch{UserID: userID, RepoID: repoID}
  34. has, err := e.Get(&watch)
  35. if err != nil {
  36. return watch, err
  37. }
  38. if !has {
  39. watch.Mode = RepoWatchModeNone
  40. }
  41. return watch, nil
  42. }
  43. // Decodes watchability of RepoWatchMode
  44. func isWatchMode(mode RepoWatchMode) bool {
  45. return mode != RepoWatchModeNone && mode != RepoWatchModeDont
  46. }
  47. // IsWatching checks if user has watched given repository.
  48. func IsWatching(userID, repoID int64) bool {
  49. watch, err := getWatch(x, userID, repoID)
  50. return err == nil && isWatchMode(watch.Mode)
  51. }
  52. func watchRepoMode(e Engine, watch Watch, mode RepoWatchMode) (err error) {
  53. if watch.Mode == mode {
  54. return nil
  55. }
  56. if mode == RepoWatchModeAuto && (watch.Mode == RepoWatchModeDont || isWatchMode(watch.Mode)) {
  57. // Don't auto watch if already watching or deliberately not watching
  58. return nil
  59. }
  60. hadrec := watch.Mode != RepoWatchModeNone
  61. needsrec := mode != RepoWatchModeNone
  62. repodiff := 0
  63. if isWatchMode(mode) && !isWatchMode(watch.Mode) {
  64. repodiff = 1
  65. } else if !isWatchMode(mode) && isWatchMode(watch.Mode) {
  66. repodiff = -1
  67. }
  68. watch.Mode = mode
  69. if !hadrec && needsrec {
  70. watch.Mode = mode
  71. if _, err = e.Insert(watch); err != nil {
  72. return err
  73. }
  74. } else if needsrec {
  75. watch.Mode = mode
  76. if _, err := e.ID(watch.ID).AllCols().Update(watch); err != nil {
  77. return err
  78. }
  79. } else if _, err = e.Delete(Watch{ID: watch.ID}); err != nil {
  80. return err
  81. }
  82. if repodiff != 0 {
  83. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + ? WHERE id = ?", repodiff, watch.RepoID)
  84. }
  85. return err
  86. }
  87. // WatchRepoMode watch repository in specific mode.
  88. func WatchRepoMode(userID, repoID int64, mode RepoWatchMode) (err error) {
  89. var watch Watch
  90. if watch, err = getWatch(x, userID, repoID); err != nil {
  91. return err
  92. }
  93. return watchRepoMode(x, watch, mode)
  94. }
  95. func watchRepo(e Engine, userID, repoID int64, doWatch bool) (err error) {
  96. var watch Watch
  97. if watch, err = getWatch(e, userID, repoID); err != nil {
  98. return err
  99. }
  100. if !doWatch && watch.Mode == RepoWatchModeAuto {
  101. err = watchRepoMode(e, watch, RepoWatchModeDont)
  102. } else if !doWatch {
  103. err = watchRepoMode(e, watch, RepoWatchModeNone)
  104. } else {
  105. err = watchRepoMode(e, watch, RepoWatchModeNormal)
  106. }
  107. return err
  108. }
  109. // WatchRepo watch or unwatch repository.
  110. func WatchRepo(userID, repoID int64, watch bool) (err error) {
  111. return watchRepo(x, userID, repoID, watch)
  112. }
  113. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  114. watches := make([]*Watch, 0, 10)
  115. return watches, e.Where("`watch`.repo_id=?", repoID).
  116. And("`watch`.mode<>?", RepoWatchModeDont).
  117. And("`user`.is_active=?", true).
  118. And("`user`.prohibit_login=?", false).
  119. Join("INNER", "`user`", "`user`.id = `watch`.user_id").
  120. Find(&watches)
  121. }
  122. // GetWatchers returns all watchers of given repository.
  123. func GetWatchers(repoID int64) ([]*Watch, error) {
  124. return getWatchers(x, repoID)
  125. }
  126. // GetRepoWatchersIDs returns IDs of watchers for a given repo ID
  127. // but avoids joining with `user` for performance reasons
  128. // User permissions must be verified elsewhere if required
  129. func GetRepoWatchersIDs(repoID int64) ([]int64, error) {
  130. return getRepoWatchersIDs(x, repoID)
  131. }
  132. func getRepoWatchersIDs(e Engine, repoID int64) ([]int64, error) {
  133. ids := make([]int64, 0, 64)
  134. return ids, e.Table("watch").
  135. Where("watch.repo_id=?", repoID).
  136. And("watch.mode<>?", RepoWatchModeDont).
  137. Select("user_id").
  138. Find(&ids)
  139. }
  140. // GetWatchers returns range of users watching given repository.
  141. func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) {
  142. sess := x.Where("watch.repo_id=?", repo.ID).
  143. Join("LEFT", "watch", "`user`.id=`watch`.user_id").
  144. And("`watch`.mode<>?", RepoWatchModeDont)
  145. if opts.Page > 0 {
  146. sess = opts.setSessionPagination(sess)
  147. users := make([]*User, 0, opts.PageSize)
  148. return users, sess.Find(&users)
  149. }
  150. users := make([]*User, 0, 8)
  151. return users, sess.Find(&users)
  152. }
  153. func notifyWatchers(e Engine, actions ...*Action) error {
  154. var watchers []*Watch
  155. var repo *Repository
  156. var err error
  157. var permCode []bool
  158. var permIssue []bool
  159. var permPR []bool
  160. for _, act := range actions {
  161. repoChanged := repo == nil || repo.ID != act.RepoID
  162. if repoChanged {
  163. // Add feeds for user self and all watchers.
  164. watchers, err = getWatchers(e, act.RepoID)
  165. if err != nil {
  166. return fmt.Errorf("get watchers: %v", err)
  167. }
  168. }
  169. // Add feed for actioner.
  170. act.UserID = act.ActUserID
  171. if _, err = e.InsertOne(act); err != nil {
  172. return fmt.Errorf("insert new actioner: %v", err)
  173. }
  174. // After InsertOne(act),the act has ID
  175. // Send the act to task chan
  176. ActionChan4Task <- *act
  177. // If it has nothing to do with repo, return directly
  178. if act.Repo == nil && act.RepoID == 0 {
  179. return nil
  180. }
  181. if repoChanged {
  182. act.loadRepo()
  183. repo = act.Repo
  184. // check repo owner exist.
  185. if err := act.Repo.getOwner(e); err != nil {
  186. return fmt.Errorf("can't get repo owner: %v", err)
  187. }
  188. } else if act.Repo == nil {
  189. act.Repo = repo
  190. }
  191. // Add feed for organization
  192. if act.Repo.Owner.IsOrganization() && act.ActUserID != act.Repo.Owner.ID {
  193. act.ID = 0
  194. act.UserID = act.Repo.Owner.ID
  195. if _, err = e.InsertOne(act); err != nil {
  196. return fmt.Errorf("insert new actioner: %v", err)
  197. }
  198. }
  199. if repoChanged {
  200. permCode = make([]bool, len(watchers))
  201. permIssue = make([]bool, len(watchers))
  202. permPR = make([]bool, len(watchers))
  203. for i, watcher := range watchers {
  204. user, err := getUserByID(e, watcher.UserID)
  205. if err != nil {
  206. permCode[i] = false
  207. permIssue[i] = false
  208. permPR[i] = false
  209. continue
  210. }
  211. perm, err := getUserRepoPermission(e, repo, user)
  212. if err != nil {
  213. permCode[i] = false
  214. permIssue[i] = false
  215. permPR[i] = false
  216. continue
  217. }
  218. permCode[i] = perm.CanRead(UnitTypeCode)
  219. permIssue[i] = perm.CanRead(UnitTypeIssues)
  220. permPR[i] = perm.CanRead(UnitTypePullRequests)
  221. }
  222. }
  223. for i, watcher := range watchers {
  224. if act.ActUserID == watcher.UserID {
  225. continue
  226. }
  227. act.ID = 0
  228. act.UserID = watcher.UserID
  229. act.Repo.Units = nil
  230. switch act.OpType {
  231. case ActionCommitRepo, ActionPushTag, ActionDeleteTag, ActionDeleteBranch:
  232. if !permCode[i] {
  233. continue
  234. }
  235. case ActionCreateIssue, ActionCommentIssue, ActionCloseIssue, ActionReopenIssue:
  236. if !permIssue[i] {
  237. continue
  238. }
  239. case ActionCreatePullRequest, ActionCommentPull, ActionMergePullRequest, ActionClosePullRequest, ActionReopenPullRequest:
  240. if !permPR[i] {
  241. continue
  242. }
  243. }
  244. if _, err = e.InsertOne(act); err != nil {
  245. return fmt.Errorf("insert new action: %v", err)
  246. }
  247. }
  248. }
  249. return nil
  250. }
  251. // NotifyWatchers creates batch of actions for every watcher.
  252. func NotifyWatchers(actions ...*Action) error {
  253. error := notifyWatchers(x, actions...)
  254. producer(actions...)
  255. return error
  256. }
  257. func producer(actions ...*Action) {
  258. for _, action := range actions {
  259. if !action.IsPrivate {
  260. ActionChan <- action
  261. }
  262. }
  263. }
  264. // NotifyWatchersActions creates batch of actions for every watcher.
  265. func NotifyWatchersActions(acts []*Action) error {
  266. sess := x.NewSession()
  267. defer sess.Close()
  268. if err := sess.Begin(); err != nil {
  269. return err
  270. }
  271. for _, act := range acts {
  272. if err := notifyWatchers(sess, act); err != nil {
  273. return err
  274. }
  275. }
  276. err := sess.Commit()
  277. producer(acts...)
  278. return err
  279. }
  280. func watchIfAuto(e Engine, userID, repoID int64, isWrite bool) error {
  281. if !isWrite || !setting.Service.AutoWatchOnChanges {
  282. return nil
  283. }
  284. watch, err := getWatch(e, userID, repoID)
  285. if err != nil {
  286. return err
  287. }
  288. if watch.Mode != RepoWatchModeNone {
  289. return nil
  290. }
  291. return watchRepoMode(e, watch, RepoWatchModeAuto)
  292. }
  293. // WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
  294. func WatchIfAuto(userID int64, repoID int64, isWrite bool) error {
  295. return watchIfAuto(x, userID, repoID, isWrite)
  296. }