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.0 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 repoChanged {
  178. act.loadRepo()
  179. repo = act.Repo
  180. // check repo owner exist.
  181. if err := act.Repo.getOwner(e); err != nil {
  182. return fmt.Errorf("can't get repo owner: %v", err)
  183. }
  184. } else if act.Repo == nil {
  185. act.Repo = repo
  186. }
  187. // Add feed for organization
  188. if act.Repo.Owner.IsOrganization() && act.ActUserID != act.Repo.Owner.ID {
  189. act.ID = 0
  190. act.UserID = act.Repo.Owner.ID
  191. if _, err = e.InsertOne(act); err != nil {
  192. return fmt.Errorf("insert new actioner: %v", err)
  193. }
  194. }
  195. if repoChanged {
  196. permCode = make([]bool, len(watchers))
  197. permIssue = make([]bool, len(watchers))
  198. permPR = make([]bool, len(watchers))
  199. for i, watcher := range watchers {
  200. user, err := getUserByID(e, watcher.UserID)
  201. if err != nil {
  202. permCode[i] = false
  203. permIssue[i] = false
  204. permPR[i] = false
  205. continue
  206. }
  207. perm, err := getUserRepoPermission(e, repo, user)
  208. if err != nil {
  209. permCode[i] = false
  210. permIssue[i] = false
  211. permPR[i] = false
  212. continue
  213. }
  214. permCode[i] = perm.CanRead(UnitTypeCode)
  215. permIssue[i] = perm.CanRead(UnitTypeIssues)
  216. permPR[i] = perm.CanRead(UnitTypePullRequests)
  217. }
  218. }
  219. for i, watcher := range watchers {
  220. if act.ActUserID == watcher.UserID {
  221. continue
  222. }
  223. act.ID = 0
  224. act.UserID = watcher.UserID
  225. act.Repo.Units = nil
  226. switch act.OpType {
  227. case ActionCommitRepo, ActionPushTag, ActionDeleteTag, ActionDeleteBranch:
  228. if !permCode[i] {
  229. continue
  230. }
  231. case ActionCreateIssue, ActionCommentIssue, ActionCloseIssue, ActionReopenIssue:
  232. if !permIssue[i] {
  233. continue
  234. }
  235. case ActionCreatePullRequest, ActionCommentPull, ActionMergePullRequest, ActionClosePullRequest, ActionReopenPullRequest:
  236. if !permPR[i] {
  237. continue
  238. }
  239. }
  240. if _, err = e.InsertOne(act); err != nil {
  241. return fmt.Errorf("insert new action: %v", err)
  242. }
  243. }
  244. }
  245. return nil
  246. }
  247. // NotifyWatchers creates batch of actions for every watcher.
  248. func NotifyWatchers(actions ...*Action) error {
  249. error := notifyWatchers(x, actions...)
  250. producer(actions...)
  251. return error
  252. }
  253. func producer(actions ...*Action) {
  254. for _, action := range actions {
  255. if !action.IsPrivate {
  256. ActionChan <- action
  257. }
  258. }
  259. }
  260. // NotifyWatchersActions creates batch of actions for every watcher.
  261. func NotifyWatchersActions(acts []*Action) error {
  262. sess := x.NewSession()
  263. defer sess.Close()
  264. if err := sess.Begin(); err != nil {
  265. return err
  266. }
  267. for _, act := range acts {
  268. if err := notifyWatchers(sess, act); err != nil {
  269. return err
  270. }
  271. }
  272. err := sess.Commit()
  273. producer(acts...)
  274. return err
  275. }
  276. func watchIfAuto(e Engine, userID, repoID int64, isWrite bool) error {
  277. if !isWrite || !setting.Service.AutoWatchOnChanges {
  278. return nil
  279. }
  280. watch, err := getWatch(e, userID, repoID)
  281. if err != nil {
  282. return err
  283. }
  284. if watch.Mode != RepoWatchModeNone {
  285. return nil
  286. }
  287. return watchRepoMode(e, watch, RepoWatchModeAuto)
  288. }
  289. // WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
  290. func WatchIfAuto(userID int64, repoID int64, isWrite bool) error {
  291. return watchIfAuto(x, userID, repoID, isWrite)
  292. }