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.

issue.go 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "regexp"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/structs"
  16. api "code.gitea.io/gitea/modules/structs"
  17. "code.gitea.io/gitea/modules/timeutil"
  18. "code.gitea.io/gitea/modules/util"
  19. "github.com/unknwon/com"
  20. "xorm.io/builder"
  21. "xorm.io/xorm"
  22. )
  23. // Issue represents an issue or pull request of repository.
  24. type Issue struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  27. Repo *Repository `xorm:"-"`
  28. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  29. PosterID int64 `xorm:"INDEX"`
  30. Poster *User `xorm:"-"`
  31. OriginalAuthor string
  32. OriginalAuthorID int64 `xorm:"index"`
  33. Title string `xorm:"name"`
  34. Content string `xorm:"TEXT"`
  35. RenderedContent string `xorm:"-"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneID int64 `xorm:"INDEX"`
  38. Milestone *Milestone `xorm:"-"`
  39. Priority int
  40. AssigneeID int64 `xorm:"-"`
  41. Assignee *User `xorm:"-"`
  42. IsClosed bool `xorm:"INDEX"`
  43. IsRead bool `xorm:"-"`
  44. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  45. PullRequest *PullRequest `xorm:"-"`
  46. NumComments int
  47. Ref string
  48. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  49. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  50. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  51. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  52. Attachments []*Attachment `xorm:"-"`
  53. Comments []*Comment `xorm:"-"`
  54. Reactions ReactionList `xorm:"-"`
  55. TotalTrackedTime int64 `xorm:"-"`
  56. Assignees []*User `xorm:"-"`
  57. // IsLocked limits commenting abilities to users on an issue
  58. // with write access
  59. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  60. }
  61. var (
  62. issueTasksPat *regexp.Regexp
  63. issueTasksDonePat *regexp.Regexp
  64. )
  65. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sx]\]\s.)|(\n\s*[-*]\s\[[\sx]\]\s.)`
  66. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[x]\]\s.)|(\n\s*[-*]\s\[[x]\]\s.)`
  67. const issueMaxDupIndexAttempts = 3
  68. const maxIssueIDs = 950
  69. func init() {
  70. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  71. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  72. }
  73. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  74. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  75. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  76. if err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. // IsOverdue checks if the issue is overdue
  82. func (issue *Issue) IsOverdue() bool {
  83. return timeutil.TimeStampNow() >= issue.DeadlineUnix
  84. }
  85. // LoadRepo loads issue's repository
  86. func (issue *Issue) LoadRepo() error {
  87. return issue.loadRepo(x)
  88. }
  89. func (issue *Issue) loadRepo(e Engine) (err error) {
  90. if issue.Repo == nil {
  91. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  92. if err != nil {
  93. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  94. }
  95. }
  96. return nil
  97. }
  98. // IsTimetrackerEnabled returns true if the repo enables timetracking
  99. func (issue *Issue) IsTimetrackerEnabled() bool {
  100. return issue.isTimetrackerEnabled(x)
  101. }
  102. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  103. if err := issue.loadRepo(e); err != nil {
  104. log.Error(fmt.Sprintf("loadRepo: %v", err))
  105. return false
  106. }
  107. return issue.Repo.IsTimetrackerEnabled()
  108. }
  109. // GetPullRequest returns the issue pull request
  110. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  111. if !issue.IsPull {
  112. return nil, fmt.Errorf("Issue is not a pull request")
  113. }
  114. pr, err = getPullRequestByIssueID(x, issue.ID)
  115. if err != nil {
  116. return nil, err
  117. }
  118. pr.Issue = issue
  119. return
  120. }
  121. // LoadLabels loads labels
  122. func (issue *Issue) LoadLabels() error {
  123. return issue.loadLabels(x)
  124. }
  125. func (issue *Issue) loadLabels(e Engine) (err error) {
  126. if issue.Labels == nil {
  127. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  128. if err != nil {
  129. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  130. }
  131. }
  132. return nil
  133. }
  134. // LoadPoster loads poster
  135. func (issue *Issue) LoadPoster() error {
  136. return issue.loadPoster(x)
  137. }
  138. func (issue *Issue) loadPoster(e Engine) (err error) {
  139. if issue.Poster == nil {
  140. issue.Poster, err = getUserByID(e, issue.PosterID)
  141. if err != nil {
  142. issue.PosterID = -1
  143. issue.Poster = NewGhostUser()
  144. if !IsErrUserNotExist(err) {
  145. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  146. }
  147. err = nil
  148. return
  149. }
  150. }
  151. return
  152. }
  153. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  154. if issue.IsPull && issue.PullRequest == nil {
  155. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  156. if err != nil {
  157. if IsErrPullRequestNotExist(err) {
  158. return err
  159. }
  160. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  161. }
  162. issue.PullRequest.Issue = issue
  163. }
  164. return nil
  165. }
  166. // LoadPullRequest loads pull request info
  167. func (issue *Issue) LoadPullRequest() error {
  168. return issue.loadPullRequest(x)
  169. }
  170. func (issue *Issue) loadComments(e Engine) (err error) {
  171. return issue.loadCommentsByType(e, CommentTypeUnknown)
  172. }
  173. // LoadDiscussComments loads discuss comments
  174. func (issue *Issue) LoadDiscussComments() error {
  175. return issue.loadCommentsByType(x, CommentTypeComment)
  176. }
  177. func (issue *Issue) loadCommentsByType(e Engine, tp CommentType) (err error) {
  178. if issue.Comments != nil {
  179. return nil
  180. }
  181. issue.Comments, err = findComments(e, FindCommentsOptions{
  182. IssueID: issue.ID,
  183. Type: tp,
  184. })
  185. return err
  186. }
  187. func (issue *Issue) loadReactions(e Engine) (err error) {
  188. if issue.Reactions != nil {
  189. return nil
  190. }
  191. reactions, err := findReactions(e, FindReactionsOptions{
  192. IssueID: issue.ID,
  193. })
  194. if err != nil {
  195. return err
  196. }
  197. if err = issue.loadRepo(e); err != nil {
  198. return err
  199. }
  200. // Load reaction user data
  201. if _, err := ReactionList(reactions).loadUsers(e, issue.Repo); err != nil {
  202. return err
  203. }
  204. // Cache comments to map
  205. comments := make(map[int64]*Comment)
  206. for _, comment := range issue.Comments {
  207. comments[comment.ID] = comment
  208. }
  209. // Add reactions either to issue or comment
  210. for _, react := range reactions {
  211. if react.CommentID == 0 {
  212. issue.Reactions = append(issue.Reactions, react)
  213. } else if comment, ok := comments[react.CommentID]; ok {
  214. comment.Reactions = append(comment.Reactions, react)
  215. }
  216. }
  217. return nil
  218. }
  219. func (issue *Issue) loadMilestone(e Engine) (err error) {
  220. if issue.Milestone == nil && issue.MilestoneID > 0 {
  221. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  222. if err != nil && !IsErrMilestoneNotExist(err) {
  223. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  224. }
  225. }
  226. return nil
  227. }
  228. func (issue *Issue) loadAttributes(e Engine) (err error) {
  229. if err = issue.loadRepo(e); err != nil {
  230. return
  231. }
  232. if err = issue.loadPoster(e); err != nil {
  233. return
  234. }
  235. if err = issue.loadLabels(e); err != nil {
  236. return
  237. }
  238. if err = issue.loadMilestone(e); err != nil {
  239. return
  240. }
  241. if err = issue.loadAssignees(e); err != nil {
  242. return
  243. }
  244. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  245. // It is possible pull request is not yet created.
  246. return err
  247. }
  248. if issue.Attachments == nil {
  249. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  250. if err != nil {
  251. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  252. }
  253. }
  254. if err = issue.loadComments(e); err != nil {
  255. return err
  256. }
  257. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  258. return err
  259. }
  260. if issue.isTimetrackerEnabled(e) {
  261. if err = issue.loadTotalTimes(e); err != nil {
  262. return err
  263. }
  264. }
  265. return issue.loadReactions(e)
  266. }
  267. // LoadAttributes loads the attribute of this issue.
  268. func (issue *Issue) LoadAttributes() error {
  269. return issue.loadAttributes(x)
  270. }
  271. // LoadMilestone load milestone of this issue.
  272. func (issue *Issue) LoadMilestone() error {
  273. return issue.loadMilestone(x)
  274. }
  275. // GetIsRead load the `IsRead` field of the issue
  276. func (issue *Issue) GetIsRead(userID int64) error {
  277. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  278. if has, err := x.Get(issueUser); err != nil {
  279. return err
  280. } else if !has {
  281. issue.IsRead = false
  282. return nil
  283. }
  284. issue.IsRead = issueUser.IsRead
  285. return nil
  286. }
  287. // APIURL returns the absolute APIURL to this issue.
  288. func (issue *Issue) APIURL() string {
  289. return fmt.Sprintf("%s/issues/%d", issue.Repo.APIURL(), issue.Index)
  290. }
  291. // HTMLURL returns the absolute URL to this issue.
  292. func (issue *Issue) HTMLURL() string {
  293. var path string
  294. if issue.IsPull {
  295. path = "pulls"
  296. } else {
  297. path = "issues"
  298. }
  299. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  300. }
  301. // DiffURL returns the absolute URL to this diff
  302. func (issue *Issue) DiffURL() string {
  303. if issue.IsPull {
  304. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  305. }
  306. return ""
  307. }
  308. // PatchURL returns the absolute URL to this patch
  309. func (issue *Issue) PatchURL() string {
  310. if issue.IsPull {
  311. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  312. }
  313. return ""
  314. }
  315. // State returns string representation of issue status.
  316. func (issue *Issue) State() api.StateType {
  317. if issue.IsClosed {
  318. return api.StateClosed
  319. }
  320. return api.StateOpen
  321. }
  322. // HashTag returns unique hash tag for issue.
  323. func (issue *Issue) HashTag() string {
  324. return "issue-" + com.ToStr(issue.ID)
  325. }
  326. // IsPoster returns true if given user by ID is the poster.
  327. func (issue *Issue) IsPoster(uid int64) bool {
  328. return issue.OriginalAuthorID == 0 && issue.PosterID == uid
  329. }
  330. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  331. return hasIssueLabel(e, issue.ID, labelID)
  332. }
  333. // HasLabel returns true if issue has been labeled by given ID.
  334. func (issue *Issue) HasLabel(labelID int64) bool {
  335. return issue.hasLabel(x, labelID)
  336. }
  337. // ReplyReference returns tokenized address to use for email reply headers
  338. func (issue *Issue) ReplyReference() string {
  339. var path string
  340. if issue.IsPull {
  341. path = "pulls"
  342. } else {
  343. path = "issues"
  344. }
  345. return fmt.Sprintf("%s/%s/%d@%s", issue.Repo.FullName(), path, issue.Index, setting.Domain)
  346. }
  347. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  348. return newIssueLabel(e, issue, label, doer)
  349. }
  350. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  351. return newIssueLabels(e, issue, labels, doer)
  352. }
  353. func (issue *Issue) getLabels(e Engine) (err error) {
  354. if len(issue.Labels) > 0 {
  355. return nil
  356. }
  357. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  358. if err != nil {
  359. return fmt.Errorf("getLabelsByIssueID: %v", err)
  360. }
  361. return nil
  362. }
  363. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  364. return deleteIssueLabel(e, issue, label, doer)
  365. }
  366. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  367. if err = issue.getLabels(e); err != nil {
  368. return fmt.Errorf("getLabels: %v", err)
  369. }
  370. for i := range issue.Labels {
  371. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  372. return fmt.Errorf("removeLabel: %v", err)
  373. }
  374. }
  375. return nil
  376. }
  377. // ClearLabels removes all issue labels as the given user.
  378. // Triggers appropriate WebHooks, if any.
  379. func (issue *Issue) ClearLabels(doer *User) (err error) {
  380. sess := x.NewSession()
  381. defer sess.Close()
  382. if err = sess.Begin(); err != nil {
  383. return err
  384. }
  385. if err := issue.loadRepo(sess); err != nil {
  386. return err
  387. } else if err = issue.loadPullRequest(sess); err != nil {
  388. return err
  389. }
  390. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  391. if err != nil {
  392. return err
  393. }
  394. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  395. return ErrLabelNotExist{}
  396. }
  397. if err = issue.clearLabels(sess, doer); err != nil {
  398. return err
  399. }
  400. if err = sess.Commit(); err != nil {
  401. return fmt.Errorf("Commit: %v", err)
  402. }
  403. return nil
  404. }
  405. type labelSorter []*Label
  406. func (ts labelSorter) Len() int {
  407. return len([]*Label(ts))
  408. }
  409. func (ts labelSorter) Less(i, j int) bool {
  410. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  411. }
  412. func (ts labelSorter) Swap(i, j int) {
  413. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  414. }
  415. // ReplaceLabels removes all current labels and add new labels to the issue.
  416. // Triggers appropriate WebHooks, if any.
  417. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  418. sess := x.NewSession()
  419. defer sess.Close()
  420. if err = sess.Begin(); err != nil {
  421. return err
  422. }
  423. if err = issue.loadLabels(sess); err != nil {
  424. return err
  425. }
  426. sort.Sort(labelSorter(labels))
  427. sort.Sort(labelSorter(issue.Labels))
  428. var toAdd, toRemove []*Label
  429. addIndex, removeIndex := 0, 0
  430. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  431. addLabel := labels[addIndex]
  432. removeLabel := issue.Labels[removeIndex]
  433. if addLabel.ID == removeLabel.ID {
  434. addIndex++
  435. removeIndex++
  436. } else if addLabel.ID < removeLabel.ID {
  437. toAdd = append(toAdd, addLabel)
  438. addIndex++
  439. } else {
  440. toRemove = append(toRemove, removeLabel)
  441. removeIndex++
  442. }
  443. }
  444. toAdd = append(toAdd, labels[addIndex:]...)
  445. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  446. if len(toAdd) > 0 {
  447. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  448. return fmt.Errorf("addLabels: %v", err)
  449. }
  450. }
  451. for _, l := range toRemove {
  452. if err = issue.removeLabel(sess, doer, l); err != nil {
  453. return fmt.Errorf("removeLabel: %v", err)
  454. }
  455. }
  456. return sess.Commit()
  457. }
  458. // ReadBy sets issue to be read by given user.
  459. func (issue *Issue) ReadBy(userID int64) error {
  460. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  461. return err
  462. }
  463. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  464. }
  465. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  466. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  467. return err
  468. }
  469. return nil
  470. }
  471. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (*Comment, error) {
  472. // Reload the issue
  473. currentIssue, err := getIssueByID(e, issue.ID)
  474. if err != nil {
  475. return nil, err
  476. }
  477. // Nothing should be performed if current status is same as target status
  478. if currentIssue.IsClosed == isClosed {
  479. if !issue.IsPull {
  480. return nil, ErrIssueWasClosed{
  481. ID: issue.ID,
  482. }
  483. }
  484. return nil, ErrPullWasClosed{
  485. ID: issue.ID,
  486. }
  487. }
  488. // Check for open dependencies
  489. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  490. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  491. noDeps, err := issueNoDependenciesLeft(e, issue)
  492. if err != nil {
  493. return nil, err
  494. }
  495. if !noDeps {
  496. return nil, ErrDependenciesLeft{issue.ID}
  497. }
  498. }
  499. issue.IsClosed = isClosed
  500. if isClosed {
  501. issue.ClosedUnix = timeutil.TimeStampNow()
  502. } else {
  503. issue.ClosedUnix = 0
  504. }
  505. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  506. return nil, err
  507. }
  508. // Update issue count of labels
  509. if err = issue.getLabels(e); err != nil {
  510. return nil, err
  511. }
  512. for idx := range issue.Labels {
  513. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  514. return nil, err
  515. }
  516. }
  517. // Update issue count of milestone
  518. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  519. return nil, err
  520. }
  521. if err := issue.updateClosedNum(e); err != nil {
  522. return nil, err
  523. }
  524. // New action comment
  525. cmtType := CommentTypeClose
  526. if !issue.IsClosed {
  527. cmtType = CommentTypeReopen
  528. }
  529. return createComment(e, &CreateCommentOptions{
  530. Type: cmtType,
  531. Doer: doer,
  532. Repo: issue.Repo,
  533. Issue: issue,
  534. })
  535. }
  536. // ChangeStatus changes issue status to open or closed.
  537. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) {
  538. sess := x.NewSession()
  539. defer sess.Close()
  540. if err := sess.Begin(); err != nil {
  541. return nil, err
  542. }
  543. if err := issue.loadRepo(sess); err != nil {
  544. return nil, err
  545. }
  546. if err := issue.loadPoster(sess); err != nil {
  547. return nil, err
  548. }
  549. comment, err := issue.changeStatus(sess, doer, isClosed)
  550. if err != nil {
  551. return nil, err
  552. }
  553. if err = sess.Commit(); err != nil {
  554. return nil, fmt.Errorf("Commit: %v", err)
  555. }
  556. return comment, nil
  557. }
  558. // ChangeTitle changes the title of this issue, as the given user.
  559. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  560. sess := x.NewSession()
  561. defer sess.Close()
  562. if err = sess.Begin(); err != nil {
  563. return err
  564. }
  565. if err = updateIssueCols(sess, issue, "name"); err != nil {
  566. return fmt.Errorf("updateIssueCols: %v", err)
  567. }
  568. if err = issue.loadRepo(sess); err != nil {
  569. return fmt.Errorf("loadRepo: %v", err)
  570. }
  571. var opts = &CreateCommentOptions{
  572. Type: CommentTypeChangeTitle,
  573. Doer: doer,
  574. Repo: issue.Repo,
  575. Issue: issue,
  576. OldTitle: oldTitle,
  577. NewTitle: issue.Title,
  578. }
  579. if _, err = createComment(sess, opts); err != nil {
  580. return fmt.Errorf("createComment: %v", err)
  581. }
  582. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  583. return err
  584. }
  585. return sess.Commit()
  586. }
  587. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  588. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  589. issue, err := getIssueByID(x, issueID)
  590. if err != nil {
  591. return err
  592. }
  593. sess := x.NewSession()
  594. defer sess.Close()
  595. if err := sess.Begin(); err != nil {
  596. return err
  597. }
  598. var opts = &CreateCommentOptions{
  599. Type: CommentTypeDeleteBranch,
  600. Doer: doer,
  601. Repo: repo,
  602. Issue: issue,
  603. CommitSHA: branchName,
  604. }
  605. if _, err = createComment(sess, opts); err != nil {
  606. return err
  607. }
  608. return sess.Commit()
  609. }
  610. // UpdateAttachments update attachments by UUIDs for the issue
  611. func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
  612. sess := x.NewSession()
  613. defer sess.Close()
  614. if err = sess.Begin(); err != nil {
  615. return err
  616. }
  617. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  618. if err != nil {
  619. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  620. }
  621. for i := 0; i < len(attachments); i++ {
  622. attachments[i].IssueID = issue.ID
  623. if err := updateAttachment(sess, attachments[i]); err != nil {
  624. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  625. }
  626. }
  627. return sess.Commit()
  628. }
  629. // ChangeContent changes issue content, as the given user.
  630. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  631. issue.Content = content
  632. sess := x.NewSession()
  633. defer sess.Close()
  634. if err = sess.Begin(); err != nil {
  635. return err
  636. }
  637. if err = updateIssueCols(sess, issue, "content"); err != nil {
  638. return fmt.Errorf("UpdateIssueCols: %v", err)
  639. }
  640. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  641. return err
  642. }
  643. return sess.Commit()
  644. }
  645. // GetTasks returns the amount of tasks in the issues content
  646. func (issue *Issue) GetTasks() int {
  647. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  648. }
  649. // GetTasksDone returns the amount of completed tasks in the issues content
  650. func (issue *Issue) GetTasksDone() int {
  651. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  652. }
  653. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  654. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  655. if issue.IsClosed {
  656. return issue.ClosedUnix
  657. }
  658. return issue.CreatedUnix
  659. }
  660. // GetLastEventLabel returns the localization label for the current issue.
  661. func (issue *Issue) GetLastEventLabel() string {
  662. if issue.IsClosed {
  663. if issue.IsPull && issue.PullRequest.HasMerged {
  664. return "repo.pulls.merged_by"
  665. }
  666. return "repo.issues.closed_by"
  667. }
  668. return "repo.issues.opened_by"
  669. }
  670. // GetLastComment return last comment for the current issue.
  671. func (issue *Issue) GetLastComment() (*Comment, error) {
  672. var c Comment
  673. exist, err := x.Where("type = ?", CommentTypeComment).
  674. And("issue_id = ?", issue.ID).Desc("id").Get(&c)
  675. if err != nil {
  676. return nil, err
  677. }
  678. if !exist {
  679. return nil, nil
  680. }
  681. return &c, nil
  682. }
  683. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  684. func (issue *Issue) GetLastEventLabelFake() string {
  685. if issue.IsClosed {
  686. if issue.IsPull && issue.PullRequest.HasMerged {
  687. return "repo.pulls.merged_by_fake"
  688. }
  689. return "repo.issues.closed_by_fake"
  690. }
  691. return "repo.issues.opened_by_fake"
  692. }
  693. // NewIssueOptions represents the options of a new issue.
  694. type NewIssueOptions struct {
  695. Repo *Repository
  696. Issue *Issue
  697. LabelIDs []int64
  698. Attachments []string // In UUID format.
  699. IsPull bool
  700. }
  701. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  702. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  703. if opts.Issue.MilestoneID > 0 {
  704. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  705. if err != nil && !IsErrMilestoneNotExist(err) {
  706. return fmt.Errorf("getMilestoneByID: %v", err)
  707. }
  708. // Assume milestone is invalid and drop silently.
  709. opts.Issue.MilestoneID = 0
  710. if milestone != nil {
  711. opts.Issue.MilestoneID = milestone.ID
  712. opts.Issue.Milestone = milestone
  713. }
  714. }
  715. // Milestone validation should happen before insert actual object.
  716. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  717. Where("repo_id=?", opts.Issue.RepoID).
  718. Insert(opts.Issue); err != nil {
  719. return ErrNewIssueInsert{err}
  720. }
  721. inserted, err := getIssueByID(e, opts.Issue.ID)
  722. if err != nil {
  723. return err
  724. }
  725. // Patch Index with the value calculated by the database
  726. opts.Issue.Index = inserted.Index
  727. if opts.Issue.MilestoneID > 0 {
  728. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  729. return err
  730. }
  731. var opts = &CreateCommentOptions{
  732. Type: CommentTypeMilestone,
  733. Doer: doer,
  734. Repo: opts.Repo,
  735. Issue: opts.Issue,
  736. OldMilestoneID: 0,
  737. MilestoneID: opts.Issue.MilestoneID,
  738. }
  739. if _, err = createComment(e, opts); err != nil {
  740. return err
  741. }
  742. }
  743. if opts.IsPull {
  744. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  745. } else {
  746. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  747. }
  748. if err != nil {
  749. return err
  750. }
  751. if len(opts.LabelIDs) > 0 {
  752. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  753. // So we have to get all needed labels first.
  754. labels := make([]*Label, 0, len(opts.LabelIDs))
  755. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  756. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  757. }
  758. if err = opts.Issue.loadPoster(e); err != nil {
  759. return err
  760. }
  761. for _, label := range labels {
  762. // Silently drop invalid labels.
  763. if label.RepoID != opts.Repo.ID {
  764. continue
  765. }
  766. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  767. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  768. }
  769. }
  770. }
  771. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  772. return err
  773. }
  774. if len(opts.Attachments) > 0 {
  775. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  776. if err != nil {
  777. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  778. }
  779. for i := 0; i < len(attachments); i++ {
  780. attachments[i].IssueID = opts.Issue.ID
  781. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  782. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  783. }
  784. }
  785. }
  786. if err = opts.Issue.loadAttributes(e); err != nil {
  787. return err
  788. }
  789. return opts.Issue.addCrossReferences(e, doer, false)
  790. }
  791. // NewIssue creates new issue with labels for repository.
  792. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  793. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  794. i := 0
  795. for {
  796. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  797. return nil
  798. }
  799. if !IsErrNewIssueInsert(err) {
  800. return err
  801. }
  802. if i++; i == issueMaxDupIndexAttempts {
  803. break
  804. }
  805. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  806. }
  807. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  808. }
  809. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  810. sess := x.NewSession()
  811. defer sess.Close()
  812. if err = sess.Begin(); err != nil {
  813. return err
  814. }
  815. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  816. Repo: repo,
  817. Issue: issue,
  818. LabelIDs: labelIDs,
  819. Attachments: uuids,
  820. }); err != nil {
  821. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  822. return err
  823. }
  824. return fmt.Errorf("newIssue: %v", err)
  825. }
  826. if err = sess.Commit(); err != nil {
  827. return fmt.Errorf("Commit: %v", err)
  828. }
  829. return nil
  830. }
  831. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  832. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  833. issue := &Issue{
  834. RepoID: repoID,
  835. Index: index,
  836. }
  837. has, err := x.Get(issue)
  838. if err != nil {
  839. return nil, err
  840. } else if !has {
  841. return nil, ErrIssueNotExist{0, repoID, index}
  842. }
  843. return issue, nil
  844. }
  845. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  846. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  847. issue, err := GetIssueByIndex(repoID, index)
  848. if err != nil {
  849. return nil, err
  850. }
  851. return issue, issue.LoadAttributes()
  852. }
  853. func getIssueByID(e Engine, id int64) (*Issue, error) {
  854. issue := new(Issue)
  855. has, err := e.ID(id).Get(issue)
  856. if err != nil {
  857. return nil, err
  858. } else if !has {
  859. return nil, ErrIssueNotExist{id, 0, 0}
  860. }
  861. return issue, nil
  862. }
  863. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  864. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  865. issue, err := getIssueByID(x, id)
  866. if err != nil {
  867. return nil, err
  868. }
  869. return issue, issue.loadAttributes(x)
  870. }
  871. // GetIssueByID returns an issue by given ID.
  872. func GetIssueByID(id int64) (*Issue, error) {
  873. return getIssueByID(x, id)
  874. }
  875. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  876. issues := make([]*Issue, 0, 10)
  877. return issues, e.In("id", issueIDs).Find(&issues)
  878. }
  879. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  880. var ids = make([]int64, 0, 10)
  881. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  882. return ids, err
  883. }
  884. // GetIssueIDsByRepoID returns all issue ids by repo id
  885. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  886. return getIssueIDsByRepoID(x, repoID)
  887. }
  888. // GetIssuesByIDs return issues with the given IDs.
  889. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  890. return getIssuesByIDs(x, issueIDs)
  891. }
  892. // IssuesOptions represents options of an issue.
  893. type IssuesOptions struct {
  894. ListOptions
  895. RepoIDs []int64 // include all repos if empty
  896. AssigneeID int64
  897. PosterID int64
  898. MentionedID int64
  899. MilestoneID int64
  900. IsClosed util.OptionalBool
  901. IsPull util.OptionalBool
  902. LabelIDs []int64
  903. SortType string
  904. IssueIDs []int64
  905. // prioritize issues from this repo
  906. PriorityRepoID int64
  907. }
  908. // sortIssuesSession sort an issues-related session based on the provided
  909. // sortType string
  910. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  911. switch sortType {
  912. case "oldest":
  913. sess.Asc("issue.created_unix")
  914. case "recentupdate":
  915. sess.Desc("issue.updated_unix")
  916. case "leastupdate":
  917. sess.Asc("issue.updated_unix")
  918. case "mostcomment":
  919. sess.Desc("issue.num_comments")
  920. case "leastcomment":
  921. sess.Asc("issue.num_comments")
  922. case "priority":
  923. sess.Desc("issue.priority")
  924. case "nearduedate":
  925. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  926. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  927. case "farduedate":
  928. sess.Desc("issue.deadline_unix")
  929. case "priorityrepo":
  930. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  931. default:
  932. sess.Desc("issue.created_unix")
  933. }
  934. }
  935. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  936. if opts.Page >= 0 && opts.PageSize > 0 {
  937. var start int
  938. if opts.Page == 0 {
  939. start = 0
  940. } else {
  941. start = (opts.Page - 1) * opts.PageSize
  942. }
  943. sess.Limit(opts.PageSize, start)
  944. }
  945. if len(opts.IssueIDs) > 0 {
  946. if len(opts.IssueIDs) > maxIssueIDs {
  947. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  948. }
  949. sess.In("issue.id", opts.IssueIDs)
  950. }
  951. if len(opts.RepoIDs) > 0 {
  952. // In case repository IDs are provided but actually no repository has issue.
  953. sess.In("issue.repo_id", opts.RepoIDs)
  954. }
  955. switch opts.IsClosed {
  956. case util.OptionalBoolTrue:
  957. sess.And("issue.is_closed=?", true)
  958. case util.OptionalBoolFalse:
  959. sess.And("issue.is_closed=?", false)
  960. }
  961. if opts.AssigneeID > 0 {
  962. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  963. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  964. }
  965. if opts.PosterID > 0 {
  966. sess.And("issue.poster_id=?", opts.PosterID)
  967. }
  968. if opts.MentionedID > 0 {
  969. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  970. And("issue_user.is_mentioned = ?", true).
  971. And("issue_user.uid = ?", opts.MentionedID)
  972. }
  973. if opts.MilestoneID > 0 {
  974. sess.And("issue.milestone_id=?", opts.MilestoneID)
  975. }
  976. switch opts.IsPull {
  977. case util.OptionalBoolTrue:
  978. sess.And("issue.is_pull=?", true)
  979. case util.OptionalBoolFalse:
  980. sess.And("issue.is_pull=?", false)
  981. }
  982. if opts.LabelIDs != nil {
  983. for i, labelID := range opts.LabelIDs {
  984. if labelID > 0 {
  985. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  986. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  987. } else {
  988. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  989. }
  990. }
  991. }
  992. }
  993. // CountIssuesByRepo map from repoID to number of issues matching the options
  994. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  995. sess := x.NewSession()
  996. defer sess.Close()
  997. opts.setupSession(sess)
  998. countsSlice := make([]*struct {
  999. RepoID int64
  1000. Count int64
  1001. }, 0, 10)
  1002. if err := sess.GroupBy("issue.repo_id").
  1003. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1004. Table("issue").
  1005. Find(&countsSlice); err != nil {
  1006. return nil, err
  1007. }
  1008. countMap := make(map[int64]int64, len(countsSlice))
  1009. for _, c := range countsSlice {
  1010. countMap[c.RepoID] = c.Count
  1011. }
  1012. return countMap, nil
  1013. }
  1014. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1015. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
  1016. repoIDs := make([]int64, 0, 5)
  1017. sess := x.NewSession()
  1018. defer sess.Close()
  1019. opts.setupSession(sess)
  1020. accessCond := accessibleRepositoryCondition(user)
  1021. if err := sess.Where(accessCond).
  1022. Join("INNER", "repository", "`issue`.repo_id = `repository`.id").
  1023. Distinct("issue.repo_id").
  1024. Table("issue").
  1025. Find(&repoIDs); err != nil {
  1026. return nil, err
  1027. }
  1028. return repoIDs, nil
  1029. }
  1030. // Issues returns a list of issues by given conditions.
  1031. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1032. sess := x.NewSession()
  1033. defer sess.Close()
  1034. opts.setupSession(sess)
  1035. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1036. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1037. if err := sess.Find(&issues); err != nil {
  1038. return nil, fmt.Errorf("Find: %v", err)
  1039. }
  1040. sess.Close()
  1041. if err := IssueList(issues).LoadAttributes(); err != nil {
  1042. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1043. }
  1044. return issues, nil
  1045. }
  1046. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1047. // but skips joining with `user` for performance reasons.
  1048. // User permissions must be verified elsewhere if required.
  1049. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1050. userIDs := make([]int64, 0, 5)
  1051. return userIDs, x.Table("comment").
  1052. Cols("poster_id").
  1053. Where("issue_id = ?", issueID).
  1054. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1055. Distinct("poster_id").
  1056. Find(&userIDs)
  1057. }
  1058. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1059. func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
  1060. userIDs, err := issue.getParticipantIDsByIssue(x)
  1061. if err != nil {
  1062. log.Error(err.Error())
  1063. return false
  1064. }
  1065. return util.IsInt64InSlice(user.ID, userIDs)
  1066. }
  1067. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1068. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1069. if len(mentions) == 0 {
  1070. return nil
  1071. }
  1072. ids := make([]int64, len(mentions))
  1073. for i, u := range mentions {
  1074. ids[i] = u.ID
  1075. }
  1076. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1077. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1078. }
  1079. return nil
  1080. }
  1081. // IssueStats represents issue statistic information.
  1082. type IssueStats struct {
  1083. OpenCount, ClosedCount int64
  1084. YourRepositoriesCount int64
  1085. AssignCount int64
  1086. CreateCount int64
  1087. MentionCount int64
  1088. }
  1089. // Filter modes.
  1090. const (
  1091. FilterModeAll = iota
  1092. FilterModeAssign
  1093. FilterModeCreate
  1094. FilterModeMention
  1095. )
  1096. func parseCountResult(results []map[string][]byte) int64 {
  1097. if len(results) == 0 {
  1098. return 0
  1099. }
  1100. for _, result := range results[0] {
  1101. return com.StrTo(string(result)).MustInt64()
  1102. }
  1103. return 0
  1104. }
  1105. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1106. type IssueStatsOptions struct {
  1107. RepoID int64
  1108. Labels string
  1109. MilestoneID int64
  1110. AssigneeID int64
  1111. MentionedID int64
  1112. PosterID int64
  1113. IsPull util.OptionalBool
  1114. IssueIDs []int64
  1115. }
  1116. // GetIssueStats returns issue statistic information by given conditions.
  1117. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1118. if len(opts.IssueIDs) <= maxQueryParameters {
  1119. return getIssueStatsChunk(opts, opts.IssueIDs)
  1120. }
  1121. // If too long a list of IDs is provided, we get the statistics in
  1122. // smaller chunks and get accumulates. Note: this could potentially
  1123. // get us invalid results. The alternative is to insert the list of
  1124. // ids in a temporary table and join from them.
  1125. accum := &IssueStats{}
  1126. for i := 0; i < len(opts.IssueIDs); {
  1127. chunk := i + maxQueryParameters
  1128. if chunk > len(opts.IssueIDs) {
  1129. chunk = len(opts.IssueIDs)
  1130. }
  1131. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1132. if err != nil {
  1133. return nil, err
  1134. }
  1135. accum.OpenCount += stats.OpenCount
  1136. accum.ClosedCount += stats.ClosedCount
  1137. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1138. accum.AssignCount += stats.AssignCount
  1139. accum.CreateCount += stats.CreateCount
  1140. accum.OpenCount += stats.MentionCount
  1141. i = chunk
  1142. }
  1143. return accum, nil
  1144. }
  1145. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1146. stats := &IssueStats{}
  1147. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1148. sess := x.
  1149. Where("issue.repo_id = ?", opts.RepoID)
  1150. if len(opts.IssueIDs) > 0 {
  1151. if len(opts.IssueIDs) > maxIssueIDs {
  1152. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1153. }
  1154. sess.In("issue.id", opts.IssueIDs)
  1155. }
  1156. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1157. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1158. if err != nil {
  1159. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1160. } else {
  1161. for i, labelID := range labelIDs {
  1162. if labelID > 0 {
  1163. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1164. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1165. } else {
  1166. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1167. }
  1168. }
  1169. }
  1170. }
  1171. if opts.MilestoneID > 0 {
  1172. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1173. }
  1174. if opts.AssigneeID > 0 {
  1175. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1176. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1177. }
  1178. if opts.PosterID > 0 {
  1179. sess.And("issue.poster_id = ?", opts.PosterID)
  1180. }
  1181. if opts.MentionedID > 0 {
  1182. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1183. And("issue_user.uid = ?", opts.MentionedID).
  1184. And("issue_user.is_mentioned = ?", true)
  1185. }
  1186. switch opts.IsPull {
  1187. case util.OptionalBoolTrue:
  1188. sess.And("issue.is_pull=?", true)
  1189. case util.OptionalBoolFalse:
  1190. sess.And("issue.is_pull=?", false)
  1191. }
  1192. return sess
  1193. }
  1194. var err error
  1195. stats.OpenCount, err = countSession(opts).
  1196. And("issue.is_closed = ?", false).
  1197. Count(new(Issue))
  1198. if err != nil {
  1199. return stats, err
  1200. }
  1201. stats.ClosedCount, err = countSession(opts).
  1202. And("issue.is_closed = ?", true).
  1203. Count(new(Issue))
  1204. return stats, err
  1205. }
  1206. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1207. type UserIssueStatsOptions struct {
  1208. UserID int64
  1209. RepoIDs []int64
  1210. UserRepoIDs []int64
  1211. FilterMode int
  1212. IsPull bool
  1213. IsClosed bool
  1214. IssueIDs []int64
  1215. }
  1216. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1217. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1218. var err error
  1219. stats := &IssueStats{}
  1220. cond := builder.NewCond()
  1221. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1222. if len(opts.RepoIDs) > 0 {
  1223. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1224. }
  1225. if len(opts.IssueIDs) > 0 {
  1226. if len(opts.IssueIDs) > maxIssueIDs {
  1227. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1228. }
  1229. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1230. }
  1231. switch opts.FilterMode {
  1232. case FilterModeAll:
  1233. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1234. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1235. Count(new(Issue))
  1236. if err != nil {
  1237. return nil, err
  1238. }
  1239. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1240. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1241. Count(new(Issue))
  1242. if err != nil {
  1243. return nil, err
  1244. }
  1245. case FilterModeAssign:
  1246. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1247. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1248. And("issue_assignees.assignee_id = ?", opts.UserID).
  1249. Count(new(Issue))
  1250. if err != nil {
  1251. return nil, err
  1252. }
  1253. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1254. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1255. And("issue_assignees.assignee_id = ?", opts.UserID).
  1256. Count(new(Issue))
  1257. if err != nil {
  1258. return nil, err
  1259. }
  1260. case FilterModeCreate:
  1261. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1262. And("issue.poster_id = ?", opts.UserID).
  1263. Count(new(Issue))
  1264. if err != nil {
  1265. return nil, err
  1266. }
  1267. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1268. And("issue.poster_id = ?", opts.UserID).
  1269. Count(new(Issue))
  1270. if err != nil {
  1271. return nil, err
  1272. }
  1273. case FilterModeMention:
  1274. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1275. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1276. And("issue_user.uid = ?", opts.UserID).
  1277. Count(new(Issue))
  1278. if err != nil {
  1279. return nil, err
  1280. }
  1281. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1282. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1283. And("issue_user.uid = ?", opts.UserID).
  1284. Count(new(Issue))
  1285. if err != nil {
  1286. return nil, err
  1287. }
  1288. }
  1289. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1290. stats.AssignCount, err = x.Where(cond).
  1291. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1292. And("issue_assignees.assignee_id = ?", opts.UserID).
  1293. Count(new(Issue))
  1294. if err != nil {
  1295. return nil, err
  1296. }
  1297. stats.CreateCount, err = x.Where(cond).
  1298. And("poster_id = ?", opts.UserID).
  1299. Count(new(Issue))
  1300. if err != nil {
  1301. return nil, err
  1302. }
  1303. stats.MentionCount, err = x.Where(cond).
  1304. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1305. And("issue_user.uid = ?", opts.UserID).
  1306. Count(new(Issue))
  1307. if err != nil {
  1308. return nil, err
  1309. }
  1310. stats.YourRepositoriesCount, err = x.Where(cond).
  1311. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1312. Count(new(Issue))
  1313. if err != nil {
  1314. return nil, err
  1315. }
  1316. return stats, nil
  1317. }
  1318. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1319. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1320. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1321. sess := x.
  1322. Where("is_closed = ?", isClosed).
  1323. And("is_pull = ?", isPull).
  1324. And("repo_id = ?", repoID)
  1325. return sess
  1326. }
  1327. openCountSession := countSession(false, isPull, repoID)
  1328. closedCountSession := countSession(true, isPull, repoID)
  1329. switch filterMode {
  1330. case FilterModeAssign:
  1331. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1332. And("issue_assignees.assignee_id = ?", uid)
  1333. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1334. And("issue_assignees.assignee_id = ?", uid)
  1335. case FilterModeCreate:
  1336. openCountSession.And("poster_id = ?", uid)
  1337. closedCountSession.And("poster_id = ?", uid)
  1338. }
  1339. openResult, _ := openCountSession.Count(new(Issue))
  1340. closedResult, _ := closedCountSession.Count(new(Issue))
  1341. return openResult, closedResult
  1342. }
  1343. // SearchIssueIDsByKeyword search issues on database
  1344. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1345. var repoCond = builder.In("repo_id", repoIDs)
  1346. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1347. var cond = builder.And(
  1348. repoCond,
  1349. builder.Or(
  1350. builder.Like{"name", kw},
  1351. builder.Like{"content", kw},
  1352. builder.In("id", builder.Select("issue_id").
  1353. From("comment").
  1354. Where(builder.And(
  1355. builder.Eq{"type": CommentTypeComment},
  1356. builder.In("issue_id", subQuery),
  1357. builder.Like{"content", kw},
  1358. )),
  1359. ),
  1360. ),
  1361. )
  1362. var ids = make([]int64, 0, limit)
  1363. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1364. if err != nil {
  1365. return 0, nil, err
  1366. }
  1367. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1368. if err != nil {
  1369. return 0, nil, err
  1370. }
  1371. return total, ids, nil
  1372. }
  1373. // UpdateIssueByAPI updates all allowed fields of given issue.
  1374. func UpdateIssueByAPI(issue *Issue) error {
  1375. sess := x.NewSession()
  1376. defer sess.Close()
  1377. if err := sess.Begin(); err != nil {
  1378. return err
  1379. }
  1380. if _, err := sess.ID(issue.ID).Cols(
  1381. "name", "is_closed", "content", "milestone_id", "priority",
  1382. "deadline_unix", "updated_unix", "closed_unix", "is_locked").
  1383. Update(issue); err != nil {
  1384. return err
  1385. }
  1386. if err := issue.loadPoster(sess); err != nil {
  1387. return err
  1388. }
  1389. if err := issue.addCrossReferences(sess, issue.Poster, true); err != nil {
  1390. return err
  1391. }
  1392. return sess.Commit()
  1393. }
  1394. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1395. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1396. // if the deadline hasn't changed do nothing
  1397. if issue.DeadlineUnix == deadlineUnix {
  1398. return nil
  1399. }
  1400. sess := x.NewSession()
  1401. defer sess.Close()
  1402. if err := sess.Begin(); err != nil {
  1403. return err
  1404. }
  1405. // Update the deadline
  1406. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1407. return err
  1408. }
  1409. // Make the comment
  1410. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1411. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1412. }
  1413. return sess.Commit()
  1414. }
  1415. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1416. type DependencyInfo struct {
  1417. Issue `xorm:"extends"`
  1418. Repository `xorm:"extends"`
  1419. }
  1420. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1421. func (issue *Issue) getParticipantIDsByIssue(e Engine) ([]int64, error) {
  1422. if issue == nil {
  1423. return nil, nil
  1424. }
  1425. userIDs := make([]int64, 0, 5)
  1426. if err := e.Table("comment").Cols("poster_id").
  1427. Where("`comment`.issue_id = ?", issue.ID).
  1428. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1429. And("`user`.is_active = ?", true).
  1430. And("`user`.prohibit_login = ?", false).
  1431. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1432. Distinct("poster_id").
  1433. Find(&userIDs); err != nil {
  1434. return nil, fmt.Errorf("get poster IDs: %v", err)
  1435. }
  1436. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1437. return append(userIDs, issue.PosterID), nil
  1438. }
  1439. return userIDs, nil
  1440. }
  1441. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1442. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1443. return issueDeps, e.
  1444. Table("issue").
  1445. Join("INNER", "repository", "repository.id = issue.repo_id").
  1446. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1447. Where("issue_id = ?", issue.ID).
  1448. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1449. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1450. Find(&issueDeps)
  1451. }
  1452. // Get Blocking Dependencies, aka all issues this issue blocks.
  1453. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1454. return issueDeps, e.
  1455. Table("issue").
  1456. Join("INNER", "repository", "repository.id = issue.repo_id").
  1457. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1458. Where("dependency_id = ?", issue.ID).
  1459. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1460. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1461. Find(&issueDeps)
  1462. }
  1463. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1464. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
  1465. return issue.getBlockedByDependencies(x)
  1466. }
  1467. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1468. func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
  1469. return issue.getBlockingDependencies(x)
  1470. }
  1471. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1472. if issue.IsPull {
  1473. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1474. issue.RepoID,
  1475. true,
  1476. true,
  1477. issue.RepoID,
  1478. )
  1479. } else {
  1480. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1481. issue.RepoID,
  1482. false,
  1483. true,
  1484. issue.RepoID,
  1485. )
  1486. }
  1487. return
  1488. }
  1489. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1490. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1491. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1492. if len(mentions) == 0 {
  1493. return
  1494. }
  1495. if err = issue.loadRepo(ctx.e); err != nil {
  1496. return
  1497. }
  1498. resolved := make(map[string]bool, 20)
  1499. names := make([]string, 0, 20)
  1500. resolved[doer.LowerName] = true
  1501. for _, name := range mentions {
  1502. name := strings.ToLower(name)
  1503. if _, ok := resolved[name]; ok {
  1504. continue
  1505. }
  1506. resolved[name] = false
  1507. names = append(names, name)
  1508. }
  1509. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1510. return nil, err
  1511. }
  1512. if issue.Repo.Owner.IsOrganization() {
  1513. // Since there can be users with names that match the name of a team,
  1514. // if the team exists and can read the issue, the team takes precedence.
  1515. teams := make([]*Team, 0, len(names))
  1516. if err := ctx.e.
  1517. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1518. Where("team_repo.repo_id=?", issue.Repo.ID).
  1519. In("team.lower_name", names).
  1520. Find(&teams); err != nil {
  1521. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1522. }
  1523. if len(teams) != 0 {
  1524. checked := make([]int64, 0, len(teams))
  1525. unittype := UnitTypeIssues
  1526. if issue.IsPull {
  1527. unittype = UnitTypePullRequests
  1528. }
  1529. for _, team := range teams {
  1530. if team.Authorize >= AccessModeOwner {
  1531. checked = append(checked, team.ID)
  1532. resolved[team.LowerName] = true
  1533. continue
  1534. }
  1535. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1536. if err != nil {
  1537. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1538. }
  1539. if has {
  1540. checked = append(checked, team.ID)
  1541. resolved[team.LowerName] = true
  1542. }
  1543. }
  1544. if len(checked) != 0 {
  1545. teamusers := make([]*User, 0, 20)
  1546. if err := ctx.e.
  1547. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1548. In("`team_user`.team_id", checked).
  1549. And("`user`.is_active = ?", true).
  1550. And("`user`.prohibit_login = ?", false).
  1551. Find(&teamusers); err != nil {
  1552. return nil, fmt.Errorf("get teams users: %v", err)
  1553. }
  1554. if len(teamusers) > 0 {
  1555. users = make([]*User, 0, len(teamusers))
  1556. for _, user := range teamusers {
  1557. if already, ok := resolved[user.LowerName]; !ok || !already {
  1558. users = append(users, user)
  1559. resolved[user.LowerName] = true
  1560. }
  1561. }
  1562. }
  1563. }
  1564. }
  1565. // Remove names already in the list to avoid querying the database if pending names remain
  1566. names = make([]string, 0, len(resolved))
  1567. for name, already := range resolved {
  1568. if !already {
  1569. names = append(names, name)
  1570. }
  1571. }
  1572. if len(names) == 0 {
  1573. return
  1574. }
  1575. }
  1576. unchecked := make([]*User, 0, len(names))
  1577. if err := ctx.e.
  1578. Where("`user`.is_active = ?", true).
  1579. And("`user`.prohibit_login = ?", false).
  1580. In("`user`.lower_name", names).
  1581. Find(&unchecked); err != nil {
  1582. return nil, fmt.Errorf("find mentioned users: %v", err)
  1583. }
  1584. for _, user := range unchecked {
  1585. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1586. continue
  1587. }
  1588. // Normal users must have read access to the referencing issue
  1589. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1590. if err != nil {
  1591. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1592. }
  1593. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1594. continue
  1595. }
  1596. users = append(users, user)
  1597. }
  1598. return
  1599. }
  1600. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1601. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1602. _, err := x.Table("issue").
  1603. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1604. And("original_author_id = ?", originalAuthorID).
  1605. Update(map[string]interface{}{
  1606. "poster_id": posterID,
  1607. "original_author": "",
  1608. "original_author_id": 0,
  1609. })
  1610. return err
  1611. }
  1612. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  1613. func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
  1614. _, err := x.Table("reaction").
  1615. Where("original_author_id = ?", originalAuthorID).
  1616. And(migratedIssueCond(gitServiceType)).
  1617. Update(map[string]interface{}{
  1618. "user_id": userID,
  1619. "original_author": "",
  1620. "original_author_id": 0,
  1621. })
  1622. return err
  1623. }