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 8.9 kB

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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. // Watch is connection request for receiving repository notification.
  23. type Watch struct {
  24. ID int64 `xorm:"pk autoincr"`
  25. UserID int64 `xorm:"UNIQUE(watch)"`
  26. RepoID int64 `xorm:"UNIQUE(watch)"`
  27. Mode RepoWatchMode `xorm:"SMALLINT NOT NULL DEFAULT 1"`
  28. CreatedUnix int64 `xorm:"created"`
  29. }
  30. // getWatch gets what kind of subscription a user has on a given repository; returns dummy record if none found
  31. func getWatch(e Engine, userID, repoID int64) (Watch, error) {
  32. watch := Watch{UserID: userID, RepoID: repoID}
  33. has, err := e.Get(&watch)
  34. if err != nil {
  35. return watch, err
  36. }
  37. if !has {
  38. watch.Mode = RepoWatchModeNone
  39. }
  40. return watch, nil
  41. }
  42. // Decodes watchability of RepoWatchMode
  43. func isWatchMode(mode RepoWatchMode) bool {
  44. return mode != RepoWatchModeNone && mode != RepoWatchModeDont
  45. }
  46. // IsWatching checks if user has watched given repository.
  47. func IsWatching(userID, repoID int64) bool {
  48. watch, err := getWatch(x, userID, repoID)
  49. return err == nil && isWatchMode(watch.Mode)
  50. }
  51. func watchRepoMode(e Engine, watch Watch, mode RepoWatchMode) (err error) {
  52. if watch.Mode == mode {
  53. return nil
  54. }
  55. if mode == RepoWatchModeAuto && (watch.Mode == RepoWatchModeDont || isWatchMode(watch.Mode)) {
  56. // Don't auto watch if already watching or deliberately not watching
  57. return nil
  58. }
  59. hadrec := watch.Mode != RepoWatchModeNone
  60. needsrec := mode != RepoWatchModeNone
  61. repodiff := 0
  62. if isWatchMode(mode) && !isWatchMode(watch.Mode) {
  63. repodiff = 1
  64. } else if !isWatchMode(mode) && isWatchMode(watch.Mode) {
  65. repodiff = -1
  66. }
  67. watch.Mode = mode
  68. if !hadrec && needsrec {
  69. watch.Mode = mode
  70. if _, err = e.Insert(watch); err != nil {
  71. return err
  72. }
  73. } else if needsrec {
  74. watch.Mode = mode
  75. if _, err := e.ID(watch.ID).AllCols().Update(watch); err != nil {
  76. return err
  77. }
  78. } else if _, err = e.Delete(Watch{ID: watch.ID}); err != nil {
  79. return err
  80. }
  81. if repodiff != 0 {
  82. _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + ? WHERE id = ?", repodiff, watch.RepoID)
  83. }
  84. return err
  85. }
  86. // WatchRepoMode watch repository in specific mode.
  87. func WatchRepoMode(userID, repoID int64, mode RepoWatchMode) (err error) {
  88. var watch Watch
  89. if watch, err = getWatch(x, userID, repoID); err != nil {
  90. return err
  91. }
  92. return watchRepoMode(x, watch, mode)
  93. }
  94. func watchRepo(e Engine, userID, repoID int64, doWatch bool) (err error) {
  95. var watch Watch
  96. if watch, err = getWatch(e, userID, repoID); err != nil {
  97. return err
  98. }
  99. if !doWatch && watch.Mode == RepoWatchModeAuto {
  100. err = watchRepoMode(e, watch, RepoWatchModeDont)
  101. } else if !doWatch {
  102. err = watchRepoMode(e, watch, RepoWatchModeNone)
  103. } else {
  104. err = watchRepoMode(e, watch, RepoWatchModeNormal)
  105. }
  106. return err
  107. }
  108. // WatchRepo watch or unwatch repository.
  109. func WatchRepo(userID, repoID int64, watch bool) (err error) {
  110. return watchRepo(x, userID, repoID, watch)
  111. }
  112. func getWatchers(e Engine, repoID int64) ([]*Watch, error) {
  113. watches := make([]*Watch, 0, 10)
  114. return watches, e.Where("`watch`.repo_id=?", repoID).
  115. And("`watch`.mode<>?", RepoWatchModeDont).
  116. And("`user`.is_active=?", true).
  117. And("`user`.prohibit_login=?", false).
  118. Join("INNER", "`user`", "`user`.id = `watch`.user_id").
  119. Find(&watches)
  120. }
  121. // GetWatchers returns all watchers of given repository.
  122. func GetWatchers(repoID int64) ([]*Watch, error) {
  123. return getWatchers(x, repoID)
  124. }
  125. // GetRepoWatchersIDs returns IDs of watchers for a given repo ID
  126. // but avoids joining with `user` for performance reasons
  127. // User permissions must be verified elsewhere if required
  128. func GetRepoWatchersIDs(repoID int64) ([]int64, error) {
  129. return getRepoWatchersIDs(x, repoID)
  130. }
  131. func getRepoWatchersIDs(e Engine, repoID int64) ([]int64, error) {
  132. ids := make([]int64, 0, 64)
  133. return ids, e.Table("watch").
  134. Where("watch.repo_id=?", repoID).
  135. And("watch.mode<>?", RepoWatchModeDont).
  136. Select("user_id").
  137. Find(&ids)
  138. }
  139. // GetWatchers returns range of users watching given repository.
  140. func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) {
  141. sess := x.Where("watch.repo_id=?", repo.ID).
  142. Join("LEFT", "watch", "`user`.id=`watch`.user_id").
  143. And("`watch`.mode<>?", RepoWatchModeDont)
  144. if opts.Page > 0 {
  145. sess = opts.setSessionPagination(sess)
  146. users := make([]*User, 0, opts.PageSize)
  147. return users, sess.Find(&users)
  148. }
  149. users := make([]*User, 0, 8)
  150. return users, sess.Find(&users)
  151. }
  152. func notifyWatchers(e Engine, actions ...*Action) error {
  153. var watchers []*Watch
  154. var repo *Repository
  155. var err error
  156. var permCode []bool
  157. var permIssue []bool
  158. var permPR []bool
  159. for _, act := range actions {
  160. repoChanged := repo == nil || repo.ID != act.RepoID
  161. if repoChanged {
  162. // Add feeds for user self and all watchers.
  163. watchers, err = getWatchers(e, act.RepoID)
  164. if err != nil {
  165. return fmt.Errorf("get watchers: %v", err)
  166. }
  167. }
  168. // Add feed for actioner.
  169. act.UserID = act.ActUserID
  170. if _, err = e.InsertOne(act); err != nil {
  171. return fmt.Errorf("insert new actioner: %v", err)
  172. }
  173. if repoChanged {
  174. act.loadRepo()
  175. repo = act.Repo
  176. // check repo owner exist.
  177. if err := act.Repo.getOwner(e); err != nil {
  178. return fmt.Errorf("can't get repo owner: %v", err)
  179. }
  180. } else if act.Repo == nil {
  181. act.Repo = repo
  182. }
  183. // Add feed for organization
  184. if act.Repo.Owner.IsOrganization() && act.ActUserID != act.Repo.Owner.ID {
  185. act.ID = 0
  186. act.UserID = act.Repo.Owner.ID
  187. if _, err = e.InsertOne(act); err != nil {
  188. return fmt.Errorf("insert new actioner: %v", err)
  189. }
  190. }
  191. if repoChanged {
  192. permCode = make([]bool, len(watchers))
  193. permIssue = make([]bool, len(watchers))
  194. permPR = make([]bool, len(watchers))
  195. for i, watcher := range watchers {
  196. user, err := getUserByID(e, watcher.UserID)
  197. if err != nil {
  198. permCode[i] = false
  199. permIssue[i] = false
  200. permPR[i] = false
  201. continue
  202. }
  203. perm, err := getUserRepoPermission(e, repo, user)
  204. if err != nil {
  205. permCode[i] = false
  206. permIssue[i] = false
  207. permPR[i] = false
  208. continue
  209. }
  210. permCode[i] = perm.CanRead(UnitTypeCode)
  211. permIssue[i] = perm.CanRead(UnitTypeIssues)
  212. permPR[i] = perm.CanRead(UnitTypePullRequests)
  213. }
  214. }
  215. for i, watcher := range watchers {
  216. if act.ActUserID == watcher.UserID {
  217. continue
  218. }
  219. act.ID = 0
  220. act.UserID = watcher.UserID
  221. act.Repo.Units = nil
  222. switch act.OpType {
  223. case ActionCommitRepo, ActionPushTag, ActionDeleteTag, ActionDeleteBranch:
  224. if !permCode[i] {
  225. continue
  226. }
  227. case ActionCreateIssue, ActionCommentIssue, ActionCloseIssue, ActionReopenIssue:
  228. if !permIssue[i] {
  229. continue
  230. }
  231. case ActionCreatePullRequest, ActionCommentPull, ActionMergePullRequest, ActionClosePullRequest, ActionReopenPullRequest:
  232. if !permPR[i] {
  233. continue
  234. }
  235. }
  236. if _, err = e.InsertOne(act); err != nil {
  237. return fmt.Errorf("insert new action: %v", err)
  238. }
  239. }
  240. }
  241. return nil
  242. }
  243. // NotifyWatchers creates batch of actions for every watcher.
  244. func NotifyWatchers(actions ...*Action) error {
  245. error := notifyWatchers(x, actions...)
  246. producer(actions...)
  247. return error
  248. }
  249. func producer(actions ...*Action) {
  250. for _, action := range actions {
  251. if !action.IsPrivate{
  252. ActionChan <- action
  253. }
  254. }
  255. }
  256. // NotifyWatchersActions creates batch of actions for every watcher.
  257. func NotifyWatchersActions(acts []*Action) error {
  258. sess := x.NewSession()
  259. defer sess.Close()
  260. if err := sess.Begin(); err != nil {
  261. return err
  262. }
  263. for _, act := range acts {
  264. if err := notifyWatchers(sess, act); err != nil {
  265. return err
  266. }
  267. }
  268. err := sess.Commit()
  269. producer(acts...)
  270. return err
  271. }
  272. func watchIfAuto(e Engine, userID, repoID int64, isWrite bool) error {
  273. if !isWrite || !setting.Service.AutoWatchOnChanges {
  274. return nil
  275. }
  276. watch, err := getWatch(e, userID, repoID)
  277. if err != nil {
  278. return err
  279. }
  280. if watch.Mode != RepoWatchModeNone {
  281. return nil
  282. }
  283. return watchRepoMode(e, watch, RepoWatchModeAuto)
  284. }
  285. // WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
  286. func WatchIfAuto(userID int64, repoID int64, isWrite bool) error {
  287. return watchIfAuto(x, userID, repoID, isWrite)
  288. }