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