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.

310 lines
8.3 KiB

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