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.

314 lines
8.4 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. return getRepoWatchersIDs(x, repoID)
  128. }
  129. func getRepoWatchersIDs(e Engine, repoID int64) ([]int64, error) {
  130. ids := make([]int64, 0, 64)
  131. return ids, e.Table("watch").
  132. Where("watch.repo_id=?", repoID).
  133. And("watch.mode<>?", RepoWatchModeDont).
  134. Select("user_id").
  135. Find(&ids)
  136. }
  137. // GetWatchers returns range of users watching given repository.
  138. func (repo *Repository) GetWatchers(opts ListOptions) ([]*User, error) {
  139. sess := x.Where("watch.repo_id=?", repo.ID).
  140. Join("LEFT", "watch", "`user`.id=`watch`.user_id").
  141. And("`watch`.mode<>?", RepoWatchModeDont)
  142. if opts.Page > 0 {
  143. sess = opts.setSessionPagination(sess)
  144. users := make([]*User, 0, opts.PageSize)
  145. return users, sess.Find(&users)
  146. }
  147. users := make([]*User, 0, 8)
  148. return users, sess.Find(&users)
  149. }
  150. func notifyWatchers(e Engine, actions ...*Action) error {
  151. var watchers []*Watch
  152. var repo *Repository
  153. var err error
  154. var permCode []bool
  155. var permIssue []bool
  156. var permPR []bool
  157. for _, act := range actions {
  158. repoChanged := repo == nil || repo.ID != act.RepoID
  159. if repoChanged {
  160. // Add feeds for user self and all watchers.
  161. watchers, err = getWatchers(e, act.RepoID)
  162. if err != nil {
  163. return fmt.Errorf("get watchers: %v", err)
  164. }
  165. }
  166. // Add feed for actioner.
  167. act.UserID = act.ActUserID
  168. if _, err = e.InsertOne(act); err != nil {
  169. return fmt.Errorf("insert new actioner: %v", err)
  170. }
  171. if repoChanged {
  172. act.loadRepo()
  173. repo = act.Repo
  174. // check repo owner exist.
  175. if err := act.Repo.getOwner(e); err != nil {
  176. return fmt.Errorf("can't get repo owner: %v", err)
  177. }
  178. } else if act.Repo == nil {
  179. act.Repo = repo
  180. }
  181. // Add feed for organization
  182. if act.Repo.Owner.IsOrganization() && act.ActUserID != act.Repo.Owner.ID {
  183. act.ID = 0
  184. act.UserID = act.Repo.Owner.ID
  185. if _, err = e.InsertOne(act); err != nil {
  186. return fmt.Errorf("insert new actioner: %v", err)
  187. }
  188. }
  189. if repoChanged {
  190. permCode = make([]bool, len(watchers))
  191. permIssue = make([]bool, len(watchers))
  192. permPR = make([]bool, len(watchers))
  193. for i, watcher := range watchers {
  194. user, err := getUserByID(e, watcher.UserID)
  195. if err != nil {
  196. permCode[i] = false
  197. permIssue[i] = false
  198. permPR[i] = false
  199. continue
  200. }
  201. perm, err := getUserRepoPermission(e, repo, user)
  202. if err != nil {
  203. permCode[i] = false
  204. permIssue[i] = false
  205. permPR[i] = false
  206. continue
  207. }
  208. permCode[i] = perm.CanRead(UnitTypeCode)
  209. permIssue[i] = perm.CanRead(UnitTypeIssues)
  210. permPR[i] = perm.CanRead(UnitTypePullRequests)
  211. }
  212. }
  213. for i, watcher := range watchers {
  214. if act.ActUserID == watcher.UserID {
  215. continue
  216. }
  217. act.ID = 0
  218. act.UserID = watcher.UserID
  219. act.Repo.Units = nil
  220. switch act.OpType {
  221. case ActionCommitRepo, ActionPushTag, ActionDeleteTag, ActionPublishRelease, ActionDeleteBranch:
  222. if !permCode[i] {
  223. continue
  224. }
  225. case ActionCreateIssue, ActionCommentIssue, ActionCloseIssue, ActionReopenIssue:
  226. if !permIssue[i] {
  227. continue
  228. }
  229. case ActionCreatePullRequest, ActionCommentPull, ActionMergePullRequest, ActionClosePullRequest, ActionReopenPullRequest:
  230. if !permPR[i] {
  231. continue
  232. }
  233. }
  234. if _, err = e.InsertOne(act); err != nil {
  235. return fmt.Errorf("insert new action: %v", err)
  236. }
  237. }
  238. }
  239. return nil
  240. }
  241. // NotifyWatchers creates batch of actions for every watcher.
  242. func NotifyWatchers(actions ...*Action) error {
  243. return notifyWatchers(x, actions...)
  244. }
  245. // NotifyWatchersActions creates batch of actions for every watcher.
  246. func NotifyWatchersActions(acts []*Action) error {
  247. sess := x.NewSession()
  248. defer sess.Close()
  249. if err := sess.Begin(); err != nil {
  250. return err
  251. }
  252. for _, act := range acts {
  253. if err := notifyWatchers(sess, act); err != nil {
  254. return err
  255. }
  256. }
  257. return sess.Commit()
  258. }
  259. func watchIfAuto(e Engine, userID, repoID int64, isWrite bool) error {
  260. if !isWrite || !setting.Service.AutoWatchOnChanges {
  261. return nil
  262. }
  263. watch, err := getWatch(e, userID, repoID)
  264. if err != nil {
  265. return err
  266. }
  267. if watch.Mode != RepoWatchModeNone {
  268. return nil
  269. }
  270. return watchRepoMode(e, watch, RepoWatchModeAuto)
  271. }
  272. // WatchIfAuto subscribes to repo if AutoWatchOnChanges is set
  273. func WatchIfAuto(userID int64, repoID int64, isWrite bool) error {
  274. return watchIfAuto(x, userID, repoID, isWrite)
  275. }