Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

repo_watch.go 9.0KB

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