You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_watch.go 9.1KB

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