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 50KB

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