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