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