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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437
  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. "context"
  8. "fmt"
  9. "regexp"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. admin_model "code.gitea.io/gitea/models/admin"
  14. "code.gitea.io/gitea/models/db"
  15. "code.gitea.io/gitea/models/foreignreference"
  16. issues_model "code.gitea.io/gitea/models/issues"
  17. "code.gitea.io/gitea/models/organization"
  18. "code.gitea.io/gitea/models/perm"
  19. access_model "code.gitea.io/gitea/models/perm/access"
  20. project_model "code.gitea.io/gitea/models/project"
  21. repo_model "code.gitea.io/gitea/models/repo"
  22. "code.gitea.io/gitea/models/unit"
  23. user_model "code.gitea.io/gitea/models/user"
  24. "code.gitea.io/gitea/modules/base"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/references"
  28. "code.gitea.io/gitea/modules/setting"
  29. "code.gitea.io/gitea/modules/storage"
  30. api "code.gitea.io/gitea/modules/structs"
  31. "code.gitea.io/gitea/modules/timeutil"
  32. "code.gitea.io/gitea/modules/util"
  33. "xorm.io/builder"
  34. "xorm.io/xorm"
  35. )
  36. // Issue represents an issue or pull request of repository.
  37. type Issue struct {
  38. ID int64 `xorm:"pk autoincr"`
  39. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  40. Repo *repo_model.Repository `xorm:"-"`
  41. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  42. PosterID int64 `xorm:"INDEX"`
  43. Poster *user_model.User `xorm:"-"`
  44. OriginalAuthor string
  45. OriginalAuthorID int64 `xorm:"index"`
  46. Title string `xorm:"name"`
  47. Content string `xorm:"LONGTEXT"`
  48. RenderedContent string `xorm:"-"`
  49. Labels []*Label `xorm:"-"`
  50. MilestoneID int64 `xorm:"INDEX"`
  51. Milestone *issues_model.Milestone `xorm:"-"`
  52. Project *project_model.Project `xorm:"-"`
  53. Priority int
  54. AssigneeID int64 `xorm:"-"`
  55. Assignee *user_model.User `xorm:"-"`
  56. IsClosed bool `xorm:"INDEX"`
  57. IsRead bool `xorm:"-"`
  58. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  59. PullRequest *PullRequest `xorm:"-"`
  60. NumComments int
  61. Ref string
  62. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  63. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  64. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  65. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  66. Attachments []*repo_model.Attachment `xorm:"-"`
  67. Comments []*Comment `xorm:"-"`
  68. Reactions issues_model.ReactionList `xorm:"-"`
  69. TotalTrackedTime int64 `xorm:"-"`
  70. Assignees []*user_model.User `xorm:"-"`
  71. ForeignReference *foreignreference.ForeignReference `xorm:"-"`
  72. // IsLocked limits commenting abilities to users on an issue
  73. // with write access
  74. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  75. // For view issue page.
  76. ShowRole RoleDescriptor `xorm:"-"`
  77. }
  78. var (
  79. issueTasksPat *regexp.Regexp
  80. issueTasksDonePat *regexp.Regexp
  81. )
  82. const (
  83. issueTasksRegexpStr = `(^\s*[-*]\s\[[\sxX]\]\s.)|(\n\s*[-*]\s\[[\sxX]\]\s.)`
  84. issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[xX]\]\s.)|(\n\s*[-*]\s\[[xX]\]\s.)`
  85. )
  86. // IssueIndex represents the issue index table
  87. type IssueIndex db.ResourceIndex
  88. func init() {
  89. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  90. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  91. db.RegisterModel(new(Issue))
  92. db.RegisterModel(new(IssueIndex))
  93. }
  94. func (issue *Issue) loadTotalTimes(ctx context.Context) (err error) {
  95. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  96. issue.TotalTrackedTime, err = opts.toSession(db.GetEngine(ctx)).SumInt(&TrackedTime{}, "time")
  97. if err != nil {
  98. return err
  99. }
  100. return nil
  101. }
  102. // IsOverdue checks if the issue is overdue
  103. func (issue *Issue) IsOverdue() bool {
  104. if issue.IsClosed {
  105. return issue.ClosedUnix >= issue.DeadlineUnix
  106. }
  107. return timeutil.TimeStampNow() >= issue.DeadlineUnix
  108. }
  109. // LoadRepo loads issue's repository
  110. func (issue *Issue) LoadRepo(ctx context.Context) (err error) {
  111. if issue.Repo == nil {
  112. issue.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, issue.RepoID)
  113. if err != nil {
  114. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  115. }
  116. }
  117. return nil
  118. }
  119. // IsTimetrackerEnabled returns true if the repo enables timetracking
  120. func (issue *Issue) IsTimetrackerEnabled() bool {
  121. return issue.isTimetrackerEnabled(db.DefaultContext)
  122. }
  123. func (issue *Issue) isTimetrackerEnabled(ctx context.Context) bool {
  124. if err := issue.LoadRepo(ctx); err != nil {
  125. log.Error(fmt.Sprintf("loadRepo: %v", err))
  126. return false
  127. }
  128. return issue.Repo.IsTimetrackerEnabledCtx(ctx)
  129. }
  130. // GetPullRequest returns the issue pull request
  131. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  132. if !issue.IsPull {
  133. return nil, fmt.Errorf("Issue is not a pull request")
  134. }
  135. pr, err = GetPullRequestByIssueID(db.DefaultContext, issue.ID)
  136. if err != nil {
  137. return nil, err
  138. }
  139. pr.Issue = issue
  140. return
  141. }
  142. // LoadLabels loads labels
  143. func (issue *Issue) LoadLabels(ctx context.Context) (err error) {
  144. if issue.Labels == nil {
  145. issue.Labels, err = GetLabelsByIssueID(ctx, issue.ID)
  146. if err != nil {
  147. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  148. }
  149. }
  150. return nil
  151. }
  152. // LoadPoster loads poster
  153. func (issue *Issue) LoadPoster() error {
  154. return issue.loadPoster(db.DefaultContext)
  155. }
  156. func (issue *Issue) loadPoster(ctx context.Context) (err error) {
  157. if issue.Poster == nil {
  158. issue.Poster, err = user_model.GetUserByIDCtx(ctx, issue.PosterID)
  159. if err != nil {
  160. issue.PosterID = -1
  161. issue.Poster = user_model.NewGhostUser()
  162. if !user_model.IsErrUserNotExist(err) {
  163. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  164. }
  165. err = nil
  166. return
  167. }
  168. }
  169. return
  170. }
  171. func (issue *Issue) loadPullRequest(ctx context.Context) (err error) {
  172. if issue.IsPull && issue.PullRequest == nil {
  173. issue.PullRequest, err = GetPullRequestByIssueID(ctx, issue.ID)
  174. if err != nil {
  175. if IsErrPullRequestNotExist(err) {
  176. return err
  177. }
  178. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  179. }
  180. issue.PullRequest.Issue = issue
  181. }
  182. return nil
  183. }
  184. // LoadPullRequest loads pull request info
  185. func (issue *Issue) LoadPullRequest() error {
  186. return issue.loadPullRequest(db.DefaultContext)
  187. }
  188. func (issue *Issue) loadComments(ctx context.Context) (err error) {
  189. return issue.loadCommentsByType(ctx, CommentTypeUnknown)
  190. }
  191. // LoadDiscussComments loads discuss comments
  192. func (issue *Issue) LoadDiscussComments() error {
  193. return issue.loadCommentsByType(db.DefaultContext, CommentTypeComment)
  194. }
  195. func (issue *Issue) loadCommentsByType(ctx context.Context, tp CommentType) (err error) {
  196. if issue.Comments != nil {
  197. return nil
  198. }
  199. issue.Comments, err = FindComments(ctx, &FindCommentsOptions{
  200. IssueID: issue.ID,
  201. Type: tp,
  202. })
  203. return err
  204. }
  205. func (issue *Issue) loadReactions(ctx context.Context) (err error) {
  206. if issue.Reactions != nil {
  207. return nil
  208. }
  209. reactions, _, err := issues_model.FindReactions(ctx, issues_model.FindReactionsOptions{
  210. IssueID: issue.ID,
  211. })
  212. if err != nil {
  213. return err
  214. }
  215. if err = issue.LoadRepo(ctx); err != nil {
  216. return err
  217. }
  218. // Load reaction user data
  219. if _, err := issues_model.ReactionList(reactions).LoadUsers(ctx, issue.Repo); err != nil {
  220. return err
  221. }
  222. // Cache comments to map
  223. comments := make(map[int64]*Comment)
  224. for _, comment := range issue.Comments {
  225. comments[comment.ID] = comment
  226. }
  227. // Add reactions either to issue or comment
  228. for _, react := range reactions {
  229. if react.CommentID == 0 {
  230. issue.Reactions = append(issue.Reactions, react)
  231. } else if comment, ok := comments[react.CommentID]; ok {
  232. comment.Reactions = append(comment.Reactions, react)
  233. }
  234. }
  235. return nil
  236. }
  237. func (issue *Issue) loadForeignReference(ctx context.Context) (err error) {
  238. if issue.ForeignReference != nil {
  239. return nil
  240. }
  241. reference := &foreignreference.ForeignReference{
  242. RepoID: issue.RepoID,
  243. LocalIndex: issue.Index,
  244. Type: foreignreference.TypeIssue,
  245. }
  246. has, err := db.GetEngine(ctx).Get(reference)
  247. if err != nil {
  248. return err
  249. } else if !has {
  250. return foreignreference.ErrForeignIndexNotExist{
  251. RepoID: issue.RepoID,
  252. LocalIndex: issue.Index,
  253. Type: foreignreference.TypeIssue,
  254. }
  255. }
  256. issue.ForeignReference = reference
  257. return nil
  258. }
  259. func (issue *Issue) loadMilestone(ctx context.Context) (err error) {
  260. if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 {
  261. issue.Milestone, err = issues_model.GetMilestoneByRepoID(ctx, issue.RepoID, issue.MilestoneID)
  262. if err != nil && !issues_model.IsErrMilestoneNotExist(err) {
  263. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  264. }
  265. }
  266. return nil
  267. }
  268. func (issue *Issue) loadAttributes(ctx context.Context) (err error) {
  269. if err = issue.LoadRepo(ctx); err != nil {
  270. return
  271. }
  272. if err = issue.loadPoster(ctx); err != nil {
  273. return
  274. }
  275. if err = issue.LoadLabels(ctx); err != nil {
  276. return
  277. }
  278. if err = issue.loadMilestone(ctx); err != nil {
  279. return
  280. }
  281. if err = issue.loadProject(ctx); err != nil {
  282. return
  283. }
  284. if err = issue.LoadAssignees(ctx); err != nil {
  285. return
  286. }
  287. if err = issue.loadPullRequest(ctx); err != nil && !IsErrPullRequestNotExist(err) {
  288. // It is possible pull request is not yet created.
  289. return err
  290. }
  291. if issue.Attachments == nil {
  292. issue.Attachments, err = repo_model.GetAttachmentsByIssueID(ctx, issue.ID)
  293. if err != nil {
  294. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  295. }
  296. }
  297. if err = issue.loadComments(ctx); err != nil {
  298. return err
  299. }
  300. if err = CommentList(issue.Comments).loadAttributes(ctx); err != nil {
  301. return err
  302. }
  303. if issue.isTimetrackerEnabled(ctx) {
  304. if err = issue.loadTotalTimes(ctx); err != nil {
  305. return err
  306. }
  307. }
  308. if err = issue.loadForeignReference(ctx); err != nil && !foreignreference.IsErrForeignIndexNotExist(err) {
  309. return err
  310. }
  311. return issue.loadReactions(ctx)
  312. }
  313. // LoadAttributes loads the attribute of this issue.
  314. func (issue *Issue) LoadAttributes() error {
  315. return issue.loadAttributes(db.DefaultContext)
  316. }
  317. // LoadMilestone load milestone of this issue.
  318. func (issue *Issue) LoadMilestone() error {
  319. return issue.loadMilestone(db.DefaultContext)
  320. }
  321. // GetIsRead load the `IsRead` field of the issue
  322. func (issue *Issue) GetIsRead(userID int64) error {
  323. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  324. if has, err := db.GetEngine(db.DefaultContext).Get(issueUser); err != nil {
  325. return err
  326. } else if !has {
  327. issue.IsRead = false
  328. return nil
  329. }
  330. issue.IsRead = issueUser.IsRead
  331. return nil
  332. }
  333. // APIURL returns the absolute APIURL to this issue.
  334. func (issue *Issue) APIURL() string {
  335. if issue.Repo == nil {
  336. err := issue.LoadRepo(db.DefaultContext)
  337. if err != nil {
  338. log.Error("Issue[%d].APIURL(): %v", issue.ID, err)
  339. return ""
  340. }
  341. }
  342. return fmt.Sprintf("%s/issues/%d", issue.Repo.APIURL(), issue.Index)
  343. }
  344. // HTMLURL returns the absolute URL to this issue.
  345. func (issue *Issue) HTMLURL() string {
  346. var path string
  347. if issue.IsPull {
  348. path = "pulls"
  349. } else {
  350. path = "issues"
  351. }
  352. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  353. }
  354. // Link returns the Link URL to this issue.
  355. func (issue *Issue) Link() string {
  356. var path string
  357. if issue.IsPull {
  358. path = "pulls"
  359. } else {
  360. path = "issues"
  361. }
  362. return fmt.Sprintf("%s/%s/%d", issue.Repo.Link(), path, issue.Index)
  363. }
  364. // DiffURL returns the absolute URL to this diff
  365. func (issue *Issue) DiffURL() string {
  366. if issue.IsPull {
  367. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  368. }
  369. return ""
  370. }
  371. // PatchURL returns the absolute URL to this patch
  372. func (issue *Issue) PatchURL() string {
  373. if issue.IsPull {
  374. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  375. }
  376. return ""
  377. }
  378. // State returns string representation of issue status.
  379. func (issue *Issue) State() api.StateType {
  380. if issue.IsClosed {
  381. return api.StateClosed
  382. }
  383. return api.StateOpen
  384. }
  385. // HashTag returns unique hash tag for issue.
  386. func (issue *Issue) HashTag() string {
  387. return fmt.Sprintf("issue-%d", issue.ID)
  388. }
  389. // IsPoster returns true if given user by ID is the poster.
  390. func (issue *Issue) IsPoster(uid int64) bool {
  391. return issue.OriginalAuthorID == 0 && issue.PosterID == uid
  392. }
  393. func (issue *Issue) getLabels(ctx context.Context) (err error) {
  394. if len(issue.Labels) > 0 {
  395. return nil
  396. }
  397. issue.Labels, err = GetLabelsByIssueID(ctx, issue.ID)
  398. if err != nil {
  399. return fmt.Errorf("getLabelsByIssueID: %v", err)
  400. }
  401. return nil
  402. }
  403. func clearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User) (err error) {
  404. if err = issue.getLabels(ctx); err != nil {
  405. return fmt.Errorf("getLabels: %v", err)
  406. }
  407. for i := range issue.Labels {
  408. if err = deleteIssueLabel(ctx, issue, issue.Labels[i], doer); err != nil {
  409. return fmt.Errorf("removeLabel: %v", err)
  410. }
  411. }
  412. return nil
  413. }
  414. // ClearIssueLabels removes all issue labels as the given user.
  415. // Triggers appropriate WebHooks, if any.
  416. func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) {
  417. ctx, committer, err := db.TxContext()
  418. if err != nil {
  419. return err
  420. }
  421. defer committer.Close()
  422. if err := issue.LoadRepo(ctx); err != nil {
  423. return err
  424. } else if err = issue.loadPullRequest(ctx); err != nil {
  425. return err
  426. }
  427. perm, err := access_model.GetUserRepoPermission(ctx, issue.Repo, doer)
  428. if err != nil {
  429. return err
  430. }
  431. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  432. return ErrRepoLabelNotExist{}
  433. }
  434. if err = clearIssueLabels(ctx, issue, doer); err != nil {
  435. return err
  436. }
  437. if err = committer.Commit(); err != nil {
  438. return fmt.Errorf("Commit: %v", err)
  439. }
  440. return nil
  441. }
  442. type labelSorter []*Label
  443. func (ts labelSorter) Len() int {
  444. return len([]*Label(ts))
  445. }
  446. func (ts labelSorter) Less(i, j int) bool {
  447. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  448. }
  449. func (ts labelSorter) Swap(i, j int) {
  450. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  451. }
  452. // ReplaceIssueLabels removes all current labels and add new labels to the issue.
  453. // Triggers appropriate WebHooks, if any.
  454. func ReplaceIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err error) {
  455. ctx, committer, err := db.TxContext()
  456. if err != nil {
  457. return err
  458. }
  459. defer committer.Close()
  460. if err = issue.LoadRepo(ctx); err != nil {
  461. return err
  462. }
  463. if err = issue.LoadLabels(ctx); err != nil {
  464. return err
  465. }
  466. sort.Sort(labelSorter(labels))
  467. sort.Sort(labelSorter(issue.Labels))
  468. var toAdd, toRemove []*Label
  469. addIndex, removeIndex := 0, 0
  470. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  471. addLabel := labels[addIndex]
  472. removeLabel := issue.Labels[removeIndex]
  473. if addLabel.ID == removeLabel.ID {
  474. // Silently drop invalid labels
  475. if removeLabel.RepoID != issue.RepoID && removeLabel.OrgID != issue.Repo.OwnerID {
  476. toRemove = append(toRemove, removeLabel)
  477. }
  478. addIndex++
  479. removeIndex++
  480. } else if addLabel.ID < removeLabel.ID {
  481. // Only add if the label is valid
  482. if addLabel.RepoID == issue.RepoID || addLabel.OrgID == issue.Repo.OwnerID {
  483. toAdd = append(toAdd, addLabel)
  484. }
  485. addIndex++
  486. } else {
  487. toRemove = append(toRemove, removeLabel)
  488. removeIndex++
  489. }
  490. }
  491. toAdd = append(toAdd, labels[addIndex:]...)
  492. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  493. if len(toAdd) > 0 {
  494. if err = newIssueLabels(ctx, issue, toAdd, doer); err != nil {
  495. return fmt.Errorf("addLabels: %v", err)
  496. }
  497. }
  498. for _, l := range toRemove {
  499. if err = deleteIssueLabel(ctx, issue, l, doer); err != nil {
  500. return fmt.Errorf("removeLabel: %v", err)
  501. }
  502. }
  503. issue.Labels = nil
  504. if err = issue.LoadLabels(ctx); err != nil {
  505. return err
  506. }
  507. return committer.Commit()
  508. }
  509. // ReadBy sets issue to be read by given user.
  510. func (issue *Issue) ReadBy(ctx context.Context, userID int64) error {
  511. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  512. return err
  513. }
  514. return setIssueNotificationStatusReadIfUnread(ctx, userID, issue.ID)
  515. }
  516. // UpdateIssueCols updates cols of issue
  517. func UpdateIssueCols(ctx context.Context, issue *Issue, cols ...string) error {
  518. if _, err := db.GetEngine(ctx).ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  519. return err
  520. }
  521. return nil
  522. }
  523. func changeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isClosed, isMergePull bool) (*Comment, error) {
  524. // Reload the issue
  525. currentIssue, err := getIssueByID(ctx, issue.ID)
  526. if err != nil {
  527. return nil, err
  528. }
  529. // Nothing should be performed if current status is same as target status
  530. if currentIssue.IsClosed == isClosed {
  531. if !issue.IsPull {
  532. return nil, ErrIssueWasClosed{
  533. ID: issue.ID,
  534. }
  535. }
  536. return nil, ErrPullWasClosed{
  537. ID: issue.ID,
  538. }
  539. }
  540. issue.IsClosed = isClosed
  541. return doChangeIssueStatus(ctx, issue, doer, isMergePull)
  542. }
  543. func doChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isMergePull bool) (*Comment, error) {
  544. // Check for open dependencies
  545. if issue.IsClosed && issue.Repo.IsDependenciesEnabledCtx(ctx) {
  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(ctx, issue)
  548. if err != nil {
  549. return nil, err
  550. }
  551. if !noDeps {
  552. return nil, ErrDependenciesLeft{issue.ID}
  553. }
  554. }
  555. if issue.IsClosed {
  556. issue.ClosedUnix = timeutil.TimeStampNow()
  557. } else {
  558. issue.ClosedUnix = 0
  559. }
  560. if err := UpdateIssueCols(ctx, issue, "is_closed", "closed_unix"); err != nil {
  561. return nil, err
  562. }
  563. // Update issue count of labels
  564. if err := issue.getLabels(ctx); err != nil {
  565. return nil, err
  566. }
  567. for idx := range issue.Labels {
  568. if err := updateLabelCols(ctx, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil {
  569. return nil, err
  570. }
  571. }
  572. // Update issue count of milestone
  573. if issue.MilestoneID > 0 {
  574. if err := issues_model.UpdateMilestoneCounters(ctx, issue.MilestoneID); err != nil {
  575. return nil, err
  576. }
  577. }
  578. if err := updateIssueClosedNum(ctx, issue); err != nil {
  579. return nil, err
  580. }
  581. // New action comment
  582. cmtType := CommentTypeClose
  583. if !issue.IsClosed {
  584. cmtType = CommentTypeReopen
  585. } else if isMergePull {
  586. cmtType = CommentTypeMergePull
  587. }
  588. return CreateCommentCtx(ctx, &CreateCommentOptions{
  589. Type: cmtType,
  590. Doer: doer,
  591. Repo: issue.Repo,
  592. Issue: issue,
  593. })
  594. }
  595. // ChangeIssueStatus changes issue status to open or closed.
  596. func ChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isClosed bool) (*Comment, error) {
  597. if err := issue.LoadRepo(ctx); err != nil {
  598. return nil, err
  599. }
  600. if err := issue.loadPoster(ctx); err != nil {
  601. return nil, err
  602. }
  603. return changeIssueStatus(ctx, issue, doer, isClosed, false)
  604. }
  605. // ChangeIssueTitle changes the title of this issue, as the given user.
  606. func ChangeIssueTitle(issue *Issue, doer *user_model.User, oldTitle string) (err error) {
  607. ctx, committer, err := db.TxContext()
  608. if err != nil {
  609. return err
  610. }
  611. defer committer.Close()
  612. if err = UpdateIssueCols(ctx, issue, "name"); err != nil {
  613. return fmt.Errorf("updateIssueCols: %v", err)
  614. }
  615. if err = issue.LoadRepo(ctx); err != nil {
  616. return fmt.Errorf("loadRepo: %v", err)
  617. }
  618. opts := &CreateCommentOptions{
  619. Type: CommentTypeChangeTitle,
  620. Doer: doer,
  621. Repo: issue.Repo,
  622. Issue: issue,
  623. OldTitle: oldTitle,
  624. NewTitle: issue.Title,
  625. }
  626. if _, err = CreateCommentCtx(ctx, opts); err != nil {
  627. return fmt.Errorf("createComment: %v", err)
  628. }
  629. if err = issue.addCrossReferences(ctx, doer, true); err != nil {
  630. return err
  631. }
  632. return committer.Commit()
  633. }
  634. // ChangeIssueRef changes the branch of this issue, as the given user.
  635. func ChangeIssueRef(issue *Issue, doer *user_model.User, oldRef string) (err error) {
  636. ctx, committer, err := db.TxContext()
  637. if err != nil {
  638. return err
  639. }
  640. defer committer.Close()
  641. if err = UpdateIssueCols(ctx, issue, "ref"); err != nil {
  642. return fmt.Errorf("updateIssueCols: %v", err)
  643. }
  644. if err = issue.LoadRepo(ctx); err != nil {
  645. return fmt.Errorf("loadRepo: %v", err)
  646. }
  647. oldRefFriendly := strings.TrimPrefix(oldRef, git.BranchPrefix)
  648. newRefFriendly := strings.TrimPrefix(issue.Ref, git.BranchPrefix)
  649. opts := &CreateCommentOptions{
  650. Type: CommentTypeChangeIssueRef,
  651. Doer: doer,
  652. Repo: issue.Repo,
  653. Issue: issue,
  654. OldRef: oldRefFriendly,
  655. NewRef: newRefFriendly,
  656. }
  657. if _, err = CreateCommentCtx(ctx, opts); err != nil {
  658. return fmt.Errorf("createComment: %v", err)
  659. }
  660. return committer.Commit()
  661. }
  662. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  663. func AddDeletePRBranchComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issueID int64, branchName string) error {
  664. issue, err := getIssueByID(ctx, issueID)
  665. if err != nil {
  666. return err
  667. }
  668. opts := &CreateCommentOptions{
  669. Type: CommentTypeDeleteBranch,
  670. Doer: doer,
  671. Repo: repo,
  672. Issue: issue,
  673. OldRef: branchName,
  674. }
  675. _, err = CreateCommentCtx(ctx, opts)
  676. return err
  677. }
  678. // UpdateIssueAttachments update attachments by UUIDs for the issue
  679. func UpdateIssueAttachments(issueID int64, uuids []string) (err error) {
  680. ctx, committer, err := db.TxContext()
  681. if err != nil {
  682. return err
  683. }
  684. defer committer.Close()
  685. attachments, err := repo_model.GetAttachmentsByUUIDs(ctx, uuids)
  686. if err != nil {
  687. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  688. }
  689. for i := 0; i < len(attachments); i++ {
  690. attachments[i].IssueID = issueID
  691. if err := repo_model.UpdateAttachment(ctx, attachments[i]); err != nil {
  692. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  693. }
  694. }
  695. return committer.Commit()
  696. }
  697. // ChangeIssueContent changes issue content, as the given user.
  698. func ChangeIssueContent(issue *Issue, doer *user_model.User, content string) (err error) {
  699. ctx, committer, err := db.TxContext()
  700. if err != nil {
  701. return err
  702. }
  703. defer committer.Close()
  704. hasContentHistory, err := issues_model.HasIssueContentHistory(ctx, issue.ID, 0)
  705. if err != nil {
  706. return fmt.Errorf("HasIssueContentHistory: %v", err)
  707. }
  708. if !hasContentHistory {
  709. if err = issues_model.SaveIssueContentHistory(ctx, issue.PosterID, issue.ID, 0,
  710. issue.CreatedUnix, issue.Content, true); err != nil {
  711. return fmt.Errorf("SaveIssueContentHistory: %v", err)
  712. }
  713. }
  714. issue.Content = content
  715. if err = UpdateIssueCols(ctx, issue, "content"); err != nil {
  716. return fmt.Errorf("UpdateIssueCols: %v", err)
  717. }
  718. if err = issues_model.SaveIssueContentHistory(ctx, doer.ID, issue.ID, 0,
  719. timeutil.TimeStampNow(), issue.Content, false); err != nil {
  720. return fmt.Errorf("SaveIssueContentHistory: %v", err)
  721. }
  722. if err = issue.addCrossReferences(ctx, doer, true); err != nil {
  723. return fmt.Errorf("addCrossReferences: %v", err)
  724. }
  725. return committer.Commit()
  726. }
  727. // GetTasks returns the amount of tasks in the issues content
  728. func (issue *Issue) GetTasks() int {
  729. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  730. }
  731. // GetTasksDone returns the amount of completed tasks in the issues content
  732. func (issue *Issue) GetTasksDone() int {
  733. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  734. }
  735. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  736. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  737. if issue.IsClosed {
  738. return issue.ClosedUnix
  739. }
  740. return issue.CreatedUnix
  741. }
  742. // GetLastEventLabel returns the localization label for the current issue.
  743. func (issue *Issue) GetLastEventLabel() string {
  744. if issue.IsClosed {
  745. if issue.IsPull && issue.PullRequest.HasMerged {
  746. return "repo.pulls.merged_by"
  747. }
  748. return "repo.issues.closed_by"
  749. }
  750. return "repo.issues.opened_by"
  751. }
  752. // GetLastComment return last comment for the current issue.
  753. func (issue *Issue) GetLastComment() (*Comment, error) {
  754. var c Comment
  755. exist, err := db.GetEngine(db.DefaultContext).Where("type = ?", CommentTypeComment).
  756. And("issue_id = ?", issue.ID).Desc("created_unix").Get(&c)
  757. if err != nil {
  758. return nil, err
  759. }
  760. if !exist {
  761. return nil, nil
  762. }
  763. return &c, nil
  764. }
  765. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  766. func (issue *Issue) GetLastEventLabelFake() string {
  767. if issue.IsClosed {
  768. if issue.IsPull && issue.PullRequest.HasMerged {
  769. return "repo.pulls.merged_by_fake"
  770. }
  771. return "repo.issues.closed_by_fake"
  772. }
  773. return "repo.issues.opened_by_fake"
  774. }
  775. // NewIssueOptions represents the options of a new issue.
  776. type NewIssueOptions struct {
  777. Repo *repo_model.Repository
  778. Issue *Issue
  779. LabelIDs []int64
  780. Attachments []string // In UUID format.
  781. IsPull bool
  782. }
  783. func newIssue(ctx context.Context, doer *user_model.User, opts NewIssueOptions) (err error) {
  784. e := db.GetEngine(ctx)
  785. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  786. if opts.Issue.MilestoneID > 0 {
  787. milestone, err := issues_model.GetMilestoneByRepoID(ctx, opts.Issue.RepoID, opts.Issue.MilestoneID)
  788. if err != nil && !issues_model.IsErrMilestoneNotExist(err) {
  789. return fmt.Errorf("getMilestoneByID: %v", err)
  790. }
  791. // Assume milestone is invalid and drop silently.
  792. opts.Issue.MilestoneID = 0
  793. if milestone != nil {
  794. opts.Issue.MilestoneID = milestone.ID
  795. opts.Issue.Milestone = milestone
  796. }
  797. }
  798. if opts.Issue.Index <= 0 {
  799. return fmt.Errorf("no issue index provided")
  800. }
  801. if opts.Issue.ID > 0 {
  802. return fmt.Errorf("issue exist")
  803. }
  804. if _, err := e.Insert(opts.Issue); err != nil {
  805. return err
  806. }
  807. if opts.Issue.MilestoneID > 0 {
  808. if err := issues_model.UpdateMilestoneCounters(ctx, opts.Issue.MilestoneID); err != nil {
  809. return err
  810. }
  811. opts := &CreateCommentOptions{
  812. Type: CommentTypeMilestone,
  813. Doer: doer,
  814. Repo: opts.Repo,
  815. Issue: opts.Issue,
  816. OldMilestoneID: 0,
  817. MilestoneID: opts.Issue.MilestoneID,
  818. }
  819. if _, err = CreateCommentCtx(ctx, opts); err != nil {
  820. return err
  821. }
  822. }
  823. if opts.IsPull {
  824. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  825. } else {
  826. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  827. }
  828. if err != nil {
  829. return err
  830. }
  831. if len(opts.LabelIDs) > 0 {
  832. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  833. // So we have to get all needed labels first.
  834. labels := make([]*Label, 0, len(opts.LabelIDs))
  835. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  836. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  837. }
  838. if err = opts.Issue.loadPoster(ctx); err != nil {
  839. return err
  840. }
  841. for _, label := range labels {
  842. // Silently drop invalid labels.
  843. if label.RepoID != opts.Repo.ID && label.OrgID != opts.Repo.OwnerID {
  844. continue
  845. }
  846. if err = newIssueLabel(ctx, opts.Issue, label, opts.Issue.Poster); err != nil {
  847. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  848. }
  849. }
  850. }
  851. if err = newIssueUsers(ctx, opts.Repo, opts.Issue); err != nil {
  852. return err
  853. }
  854. if len(opts.Attachments) > 0 {
  855. attachments, err := repo_model.GetAttachmentsByUUIDs(ctx, opts.Attachments)
  856. if err != nil {
  857. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  858. }
  859. for i := 0; i < len(attachments); i++ {
  860. attachments[i].IssueID = opts.Issue.ID
  861. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  862. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  863. }
  864. }
  865. }
  866. if err = opts.Issue.loadAttributes(ctx); err != nil {
  867. return err
  868. }
  869. return opts.Issue.addCrossReferences(ctx, doer, false)
  870. }
  871. // RecalculateIssueIndexForRepo create issue_index for repo if not exist and
  872. // update it based on highest index of existing issues assigned to a repo
  873. func RecalculateIssueIndexForRepo(repoID int64) error {
  874. ctx, committer, err := db.TxContext()
  875. if err != nil {
  876. return err
  877. }
  878. defer committer.Close()
  879. if err := db.UpsertResourceIndex(db.GetEngine(ctx), "issue_index", repoID); err != nil {
  880. return err
  881. }
  882. var max int64
  883. if _, err := db.GetEngine(ctx).Select(" MAX(`index`)").Table("issue").Where("repo_id=?", repoID).Get(&max); err != nil {
  884. return err
  885. }
  886. if _, err := db.GetEngine(ctx).Exec("UPDATE `issue_index` SET max_index=? WHERE group_id=?", max, repoID); err != nil {
  887. return err
  888. }
  889. return committer.Commit()
  890. }
  891. // NewIssue creates new issue with labels for repository.
  892. func NewIssue(repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  893. idx, err := db.GetNextResourceIndex("issue_index", repo.ID)
  894. if err != nil {
  895. return fmt.Errorf("generate issue index failed: %v", err)
  896. }
  897. issue.Index = idx
  898. ctx, committer, err := db.TxContext()
  899. if err != nil {
  900. return err
  901. }
  902. defer committer.Close()
  903. if err = newIssue(ctx, issue.Poster, NewIssueOptions{
  904. Repo: repo,
  905. Issue: issue,
  906. LabelIDs: labelIDs,
  907. Attachments: uuids,
  908. }); err != nil {
  909. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  910. return err
  911. }
  912. return fmt.Errorf("newIssue: %v", err)
  913. }
  914. if err = committer.Commit(); err != nil {
  915. return fmt.Errorf("Commit: %v", err)
  916. }
  917. return nil
  918. }
  919. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  920. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  921. if index < 1 {
  922. return nil, ErrIssueNotExist{}
  923. }
  924. issue := &Issue{
  925. RepoID: repoID,
  926. Index: index,
  927. }
  928. has, err := db.GetEngine(db.DefaultContext).Get(issue)
  929. if err != nil {
  930. return nil, err
  931. } else if !has {
  932. return nil, ErrIssueNotExist{0, repoID, index}
  933. }
  934. return issue, nil
  935. }
  936. // GetIssueByForeignIndex returns raw issue by foreign ID
  937. func GetIssueByForeignIndex(ctx context.Context, repoID, foreignIndex int64) (*Issue, error) {
  938. reference := &foreignreference.ForeignReference{
  939. RepoID: repoID,
  940. ForeignIndex: strconv.FormatInt(foreignIndex, 10),
  941. Type: foreignreference.TypeIssue,
  942. }
  943. has, err := db.GetEngine(ctx).Get(reference)
  944. if err != nil {
  945. return nil, err
  946. } else if !has {
  947. return nil, foreignreference.ErrLocalIndexNotExist{
  948. RepoID: repoID,
  949. ForeignIndex: foreignIndex,
  950. Type: foreignreference.TypeIssue,
  951. }
  952. }
  953. return GetIssueByIndex(repoID, reference.LocalIndex)
  954. }
  955. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  956. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  957. issue, err := GetIssueByIndex(repoID, index)
  958. if err != nil {
  959. return nil, err
  960. }
  961. return issue, issue.LoadAttributes()
  962. }
  963. func getIssueByID(ctx context.Context, id int64) (*Issue, error) {
  964. issue := new(Issue)
  965. has, err := db.GetEngine(ctx).ID(id).Get(issue)
  966. if err != nil {
  967. return nil, err
  968. } else if !has {
  969. return nil, ErrIssueNotExist{id, 0, 0}
  970. }
  971. return issue, nil
  972. }
  973. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  974. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  975. issue, err := getIssueByID(db.DefaultContext, id)
  976. if err != nil {
  977. return nil, err
  978. }
  979. return issue, issue.loadAttributes(db.DefaultContext)
  980. }
  981. // GetIssueByID returns an issue by given ID.
  982. func GetIssueByID(id int64) (*Issue, error) {
  983. return getIssueByID(db.DefaultContext, id)
  984. }
  985. // GetIssuesByIDs return issues with the given IDs.
  986. func GetIssuesByIDs(ctx context.Context, issueIDs []int64) ([]*Issue, error) {
  987. issues := make([]*Issue, 0, 10)
  988. return issues, db.GetEngine(ctx).In("id", issueIDs).Find(&issues)
  989. }
  990. // GetIssueIDsByRepoID returns all issue ids by repo id
  991. func GetIssueIDsByRepoID(ctx context.Context, repoID int64) ([]int64, error) {
  992. ids := make([]int64, 0, 10)
  993. err := db.GetEngine(ctx).Table("issue").Cols("id").Where("repo_id = ?", repoID).Find(&ids)
  994. return ids, err
  995. }
  996. // IssuesOptions represents options of an issue.
  997. type IssuesOptions struct {
  998. db.ListOptions
  999. RepoID int64 // overwrites RepoCond if not 0
  1000. RepoCond builder.Cond
  1001. AssigneeID int64
  1002. PosterID int64
  1003. MentionedID int64
  1004. ReviewRequestedID int64
  1005. MilestoneIDs []int64
  1006. ProjectID int64
  1007. ProjectBoardID int64
  1008. IsClosed util.OptionalBool
  1009. IsPull util.OptionalBool
  1010. LabelIDs []int64
  1011. IncludedLabelNames []string
  1012. ExcludedLabelNames []string
  1013. IncludeMilestones []string
  1014. SortType string
  1015. IssueIDs []int64
  1016. UpdatedAfterUnix int64
  1017. UpdatedBeforeUnix int64
  1018. // prioritize issues from this repo
  1019. PriorityRepoID int64
  1020. IsArchived util.OptionalBool
  1021. Org *organization.Organization // issues permission scope
  1022. Team *organization.Team // issues permission scope
  1023. User *user_model.User // issues permission scope
  1024. }
  1025. // sortIssuesSession sort an issues-related session based on the provided
  1026. // sortType string
  1027. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  1028. switch sortType {
  1029. case "oldest":
  1030. sess.Asc("issue.created_unix").Asc("issue.id")
  1031. case "recentupdate":
  1032. sess.Desc("issue.updated_unix").Desc("issue.created_unix").Desc("issue.id")
  1033. case "leastupdate":
  1034. sess.Asc("issue.updated_unix").Asc("issue.created_unix").Asc("issue.id")
  1035. case "mostcomment":
  1036. sess.Desc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id")
  1037. case "leastcomment":
  1038. sess.Asc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id")
  1039. case "priority":
  1040. sess.Desc("issue.priority").Desc("issue.created_unix").Desc("issue.id")
  1041. case "nearduedate":
  1042. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  1043. sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id").
  1044. OrderBy("CASE " +
  1045. "WHEN issue.deadline_unix = 0 AND (milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL) THEN 253370764800 " +
  1046. "WHEN milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL THEN issue.deadline_unix " +
  1047. "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " +
  1048. "ELSE issue.deadline_unix END ASC").
  1049. Desc("issue.created_unix").
  1050. Desc("issue.id")
  1051. case "farduedate":
  1052. sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id").
  1053. OrderBy("CASE " +
  1054. "WHEN milestone.deadline_unix IS NULL THEN issue.deadline_unix " +
  1055. "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " +
  1056. "ELSE issue.deadline_unix END DESC").
  1057. Desc("issue.created_unix").
  1058. Desc("issue.id")
  1059. case "priorityrepo":
  1060. sess.OrderBy("CASE " +
  1061. "WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 " +
  1062. "ELSE 2 END ASC").
  1063. Desc("issue.created_unix").
  1064. Desc("issue.id")
  1065. case "project-column-sorting":
  1066. sess.Asc("project_issue.sorting").Desc("issue.created_unix").Desc("issue.id")
  1067. default:
  1068. sess.Desc("issue.created_unix").Desc("issue.id")
  1069. }
  1070. }
  1071. func (opts *IssuesOptions) setupSessionWithLimit(sess *xorm.Session) {
  1072. if opts.Page >= 0 && opts.PageSize > 0 {
  1073. var start int
  1074. if opts.Page == 0 {
  1075. start = 0
  1076. } else {
  1077. start = (opts.Page - 1) * opts.PageSize
  1078. }
  1079. sess.Limit(opts.PageSize, start)
  1080. }
  1081. opts.setupSessionNoLimit(sess)
  1082. }
  1083. func (opts *IssuesOptions) setupSessionNoLimit(sess *xorm.Session) {
  1084. if len(opts.IssueIDs) > 0 {
  1085. sess.In("issue.id", opts.IssueIDs)
  1086. }
  1087. if opts.RepoID != 0 {
  1088. opts.RepoCond = builder.Eq{"issue.repo_id": opts.RepoID}
  1089. }
  1090. if opts.RepoCond != nil {
  1091. sess.And(opts.RepoCond)
  1092. }
  1093. if !opts.IsClosed.IsNone() {
  1094. sess.And("issue.is_closed=?", opts.IsClosed.IsTrue())
  1095. }
  1096. if opts.AssigneeID > 0 {
  1097. applyAssigneeCondition(sess, opts.AssigneeID)
  1098. }
  1099. if opts.PosterID > 0 {
  1100. applyPosterCondition(sess, opts.PosterID)
  1101. }
  1102. if opts.MentionedID > 0 {
  1103. applyMentionedCondition(sess, opts.MentionedID)
  1104. }
  1105. if opts.ReviewRequestedID > 0 {
  1106. applyReviewRequestedCondition(sess, opts.ReviewRequestedID)
  1107. }
  1108. if len(opts.MilestoneIDs) > 0 {
  1109. sess.In("issue.milestone_id", opts.MilestoneIDs)
  1110. }
  1111. if opts.UpdatedAfterUnix != 0 {
  1112. sess.And(builder.Gte{"issue.updated_unix": opts.UpdatedAfterUnix})
  1113. }
  1114. if opts.UpdatedBeforeUnix != 0 {
  1115. sess.And(builder.Lte{"issue.updated_unix": opts.UpdatedBeforeUnix})
  1116. }
  1117. if opts.ProjectID > 0 {
  1118. sess.Join("INNER", "project_issue", "issue.id = project_issue.issue_id").
  1119. And("project_issue.project_id=?", opts.ProjectID)
  1120. }
  1121. if opts.ProjectBoardID != 0 {
  1122. if opts.ProjectBoardID > 0 {
  1123. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": opts.ProjectBoardID}))
  1124. } else {
  1125. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": 0}))
  1126. }
  1127. }
  1128. switch opts.IsPull {
  1129. case util.OptionalBoolTrue:
  1130. sess.And("issue.is_pull=?", true)
  1131. case util.OptionalBoolFalse:
  1132. sess.And("issue.is_pull=?", false)
  1133. }
  1134. if opts.IsArchived != util.OptionalBoolNone {
  1135. sess.And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()})
  1136. }
  1137. if opts.LabelIDs != nil {
  1138. for i, labelID := range opts.LabelIDs {
  1139. if labelID > 0 {
  1140. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1141. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1142. } else {
  1143. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1144. }
  1145. }
  1146. }
  1147. if len(opts.IncludedLabelNames) > 0 {
  1148. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  1149. }
  1150. if len(opts.ExcludedLabelNames) > 0 {
  1151. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  1152. }
  1153. if len(opts.IncludeMilestones) > 0 {
  1154. sess.In("issue.milestone_id",
  1155. builder.Select("id").
  1156. From("milestone").
  1157. Where(builder.In("name", opts.IncludeMilestones)))
  1158. }
  1159. if opts.User != nil {
  1160. sess.And(issuePullAccessibleRepoCond("issue.repo_id", opts.User.ID, opts.Org, opts.Team, opts.IsPull.IsTrue()))
  1161. }
  1162. }
  1163. // issuePullAccessibleRepoCond userID must not be zero, this condition require join repository table
  1164. func issuePullAccessibleRepoCond(repoIDstr string, userID int64, org *organization.Organization, team *organization.Team, isPull bool) builder.Cond {
  1165. cond := builder.NewCond()
  1166. unitType := unit.TypeIssues
  1167. if isPull {
  1168. unitType = unit.TypePullRequests
  1169. }
  1170. if org != nil {
  1171. if team != nil {
  1172. cond = cond.And(teamUnitsRepoCond(repoIDstr, userID, org.ID, team.ID, unitType)) // special team member repos
  1173. } else {
  1174. cond = cond.And(
  1175. builder.Or(
  1176. userOrgUnitRepoCond(repoIDstr, userID, org.ID, unitType), // team member repos
  1177. userOrgPublicUnitRepoCond(userID, org.ID), // user org public non-member repos, TODO: check repo has issues
  1178. ),
  1179. )
  1180. }
  1181. } else {
  1182. cond = cond.And(
  1183. builder.Or(
  1184. userOwnedRepoCond(userID), // owned repos
  1185. userCollaborationRepoCond(repoIDstr, userID), // collaboration repos
  1186. userAssignedRepoCond(repoIDstr, userID), // user has been assigned accessible public repos
  1187. userMentionedRepoCond(repoIDstr, userID), // user has been mentioned accessible public repos
  1188. userCreateIssueRepoCond(repoIDstr, userID, isPull), // user has created issue/pr accessible public repos
  1189. ),
  1190. )
  1191. }
  1192. return cond
  1193. }
  1194. func applyAssigneeCondition(sess *xorm.Session, assigneeID int64) *xorm.Session {
  1195. return sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1196. And("issue_assignees.assignee_id = ?", assigneeID)
  1197. }
  1198. func applyPosterCondition(sess *xorm.Session, posterID int64) *xorm.Session {
  1199. return sess.And("issue.poster_id=?", posterID)
  1200. }
  1201. func applyMentionedCondition(sess *xorm.Session, mentionedID int64) *xorm.Session {
  1202. return sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1203. And("issue_user.is_mentioned = ?", true).
  1204. And("issue_user.uid = ?", mentionedID)
  1205. }
  1206. func applyReviewRequestedCondition(sess *xorm.Session, reviewRequestedID int64) *xorm.Session {
  1207. return sess.Join("INNER", []string{"review", "r"}, "issue.id = r.issue_id").
  1208. And("issue.poster_id <> ?", reviewRequestedID).
  1209. And("r.type = ?", ReviewTypeRequest).
  1210. And("r.reviewer_id = ? and r.id in (select max(id) from review where issue_id = r.issue_id and reviewer_id = r.reviewer_id and type in (?, ?, ?))"+
  1211. " or r.reviewer_team_id in (select team_id from team_user where uid = ?)",
  1212. reviewRequestedID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest, reviewRequestedID)
  1213. }
  1214. // CountIssuesByRepo map from repoID to number of issues matching the options
  1215. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1216. e := db.GetEngine(db.DefaultContext)
  1217. sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  1218. opts.setupSessionNoLimit(sess)
  1219. countsSlice := make([]*struct {
  1220. RepoID int64
  1221. Count int64
  1222. }, 0, 10)
  1223. if err := sess.GroupBy("issue.repo_id").
  1224. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1225. Table("issue").
  1226. Find(&countsSlice); err != nil {
  1227. return nil, fmt.Errorf("unable to CountIssuesByRepo: %w", err)
  1228. }
  1229. countMap := make(map[int64]int64, len(countsSlice))
  1230. for _, c := range countsSlice {
  1231. countMap[c.RepoID] = c.Count
  1232. }
  1233. return countMap, nil
  1234. }
  1235. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1236. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *user_model.User) ([]int64, error) {
  1237. repoIDs := make([]int64, 0, 5)
  1238. e := db.GetEngine(db.DefaultContext)
  1239. sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  1240. opts.setupSessionNoLimit(sess)
  1241. accessCond := accessibleRepositoryCondition(user)
  1242. if err := sess.Where(accessCond).
  1243. Distinct("issue.repo_id").
  1244. Table("issue").
  1245. Find(&repoIDs); err != nil {
  1246. return nil, fmt.Errorf("unable to GetRepoIDsForIssuesOptions: %w", err)
  1247. }
  1248. return repoIDs, nil
  1249. }
  1250. // Issues returns a list of issues by given conditions.
  1251. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1252. e := db.GetEngine(db.DefaultContext)
  1253. sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  1254. opts.setupSessionWithLimit(sess)
  1255. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1256. issues := make([]*Issue, 0, opts.ListOptions.PageSize)
  1257. if err := sess.Find(&issues); err != nil {
  1258. return nil, fmt.Errorf("unable to query Issues: %w", err)
  1259. }
  1260. if err := IssueList(issues).LoadAttributes(); err != nil {
  1261. return nil, fmt.Errorf("unable to LoadAttributes for Issues: %w", err)
  1262. }
  1263. return issues, nil
  1264. }
  1265. // CountIssues number return of issues by given conditions.
  1266. func CountIssues(opts *IssuesOptions) (int64, error) {
  1267. e := db.GetEngine(db.DefaultContext)
  1268. sess := e.Select("COUNT(issue.id) AS count").Table("issue")
  1269. sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  1270. opts.setupSessionNoLimit(sess)
  1271. return sess.Count()
  1272. }
  1273. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1274. // but skips joining with `user` for performance reasons.
  1275. // User permissions must be verified elsewhere if required.
  1276. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1277. userIDs := make([]int64, 0, 5)
  1278. return userIDs, db.GetEngine(db.DefaultContext).Table("comment").
  1279. Cols("poster_id").
  1280. Where("issue_id = ?", issueID).
  1281. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1282. Distinct("poster_id").
  1283. Find(&userIDs)
  1284. }
  1285. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1286. func IsUserParticipantsOfIssue(user *user_model.User, issue *Issue) bool {
  1287. userIDs, err := issue.getParticipantIDsByIssue(db.DefaultContext)
  1288. if err != nil {
  1289. log.Error(err.Error())
  1290. return false
  1291. }
  1292. return util.IsInt64InSlice(user.ID, userIDs)
  1293. }
  1294. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1295. func UpdateIssueMentions(ctx context.Context, issueID int64, mentions []*user_model.User) error {
  1296. if len(mentions) == 0 {
  1297. return nil
  1298. }
  1299. ids := make([]int64, len(mentions))
  1300. for i, u := range mentions {
  1301. ids[i] = u.ID
  1302. }
  1303. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1304. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1305. }
  1306. return nil
  1307. }
  1308. // IssueStats represents issue statistic information.
  1309. type IssueStats struct {
  1310. OpenCount, ClosedCount int64
  1311. YourRepositoriesCount int64
  1312. AssignCount int64
  1313. CreateCount int64
  1314. MentionCount int64
  1315. ReviewRequestedCount int64
  1316. }
  1317. // Filter modes.
  1318. const (
  1319. FilterModeAll = iota
  1320. FilterModeAssign
  1321. FilterModeCreate
  1322. FilterModeMention
  1323. FilterModeReviewRequested
  1324. FilterModeYourRepositories
  1325. )
  1326. func parseCountResult(results []map[string][]byte) int64 {
  1327. if len(results) == 0 {
  1328. return 0
  1329. }
  1330. for _, result := range results[0] {
  1331. c, _ := strconv.ParseInt(string(result), 10, 64)
  1332. return c
  1333. }
  1334. return 0
  1335. }
  1336. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1337. type IssueStatsOptions struct {
  1338. RepoID int64
  1339. Labels string
  1340. MilestoneID int64
  1341. AssigneeID int64
  1342. MentionedID int64
  1343. PosterID int64
  1344. ReviewRequestedID int64
  1345. IsPull util.OptionalBool
  1346. IssueIDs []int64
  1347. }
  1348. const (
  1349. // When queries are broken down in parts because of the number
  1350. // of parameters, attempt to break by this amount
  1351. maxQueryParameters = 300
  1352. )
  1353. // GetIssueStats returns issue statistic information by given conditions.
  1354. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1355. if len(opts.IssueIDs) <= maxQueryParameters {
  1356. return getIssueStatsChunk(opts, opts.IssueIDs)
  1357. }
  1358. // If too long a list of IDs is provided, we get the statistics in
  1359. // smaller chunks and get accumulates. Note: this could potentially
  1360. // get us invalid results. The alternative is to insert the list of
  1361. // ids in a temporary table and join from them.
  1362. accum := &IssueStats{}
  1363. for i := 0; i < len(opts.IssueIDs); {
  1364. chunk := i + maxQueryParameters
  1365. if chunk > len(opts.IssueIDs) {
  1366. chunk = len(opts.IssueIDs)
  1367. }
  1368. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1369. if err != nil {
  1370. return nil, err
  1371. }
  1372. accum.OpenCount += stats.OpenCount
  1373. accum.ClosedCount += stats.ClosedCount
  1374. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1375. accum.AssignCount += stats.AssignCount
  1376. accum.CreateCount += stats.CreateCount
  1377. accum.OpenCount += stats.MentionCount
  1378. accum.ReviewRequestedCount += stats.ReviewRequestedCount
  1379. i = chunk
  1380. }
  1381. return accum, nil
  1382. }
  1383. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1384. stats := &IssueStats{}
  1385. countSession := func(opts *IssueStatsOptions, issueIDs []int64) *xorm.Session {
  1386. sess := db.GetEngine(db.DefaultContext).
  1387. Where("issue.repo_id = ?", opts.RepoID)
  1388. if len(issueIDs) > 0 {
  1389. sess.In("issue.id", issueIDs)
  1390. }
  1391. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1392. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1393. if err != nil {
  1394. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1395. } else {
  1396. for i, labelID := range labelIDs {
  1397. if labelID > 0 {
  1398. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1399. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1400. } else {
  1401. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1402. }
  1403. }
  1404. }
  1405. }
  1406. if opts.MilestoneID > 0 {
  1407. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1408. }
  1409. if opts.AssigneeID > 0 {
  1410. applyAssigneeCondition(sess, opts.AssigneeID)
  1411. }
  1412. if opts.PosterID > 0 {
  1413. applyPosterCondition(sess, opts.PosterID)
  1414. }
  1415. if opts.MentionedID > 0 {
  1416. applyMentionedCondition(sess, opts.MentionedID)
  1417. }
  1418. if opts.ReviewRequestedID > 0 {
  1419. applyReviewRequestedCondition(sess, opts.ReviewRequestedID)
  1420. }
  1421. switch opts.IsPull {
  1422. case util.OptionalBoolTrue:
  1423. sess.And("issue.is_pull=?", true)
  1424. case util.OptionalBoolFalse:
  1425. sess.And("issue.is_pull=?", false)
  1426. }
  1427. return sess
  1428. }
  1429. var err error
  1430. stats.OpenCount, err = countSession(opts, issueIDs).
  1431. And("issue.is_closed = ?", false).
  1432. Count(new(Issue))
  1433. if err != nil {
  1434. return stats, err
  1435. }
  1436. stats.ClosedCount, err = countSession(opts, issueIDs).
  1437. And("issue.is_closed = ?", true).
  1438. Count(new(Issue))
  1439. return stats, err
  1440. }
  1441. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1442. type UserIssueStatsOptions struct {
  1443. UserID int64
  1444. RepoIDs []int64
  1445. FilterMode int
  1446. IsPull bool
  1447. IsClosed bool
  1448. IssueIDs []int64
  1449. IsArchived util.OptionalBool
  1450. LabelIDs []int64
  1451. RepoCond builder.Cond
  1452. Org *organization.Organization
  1453. Team *organization.Team
  1454. }
  1455. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1456. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1457. var err error
  1458. stats := &IssueStats{}
  1459. cond := builder.NewCond()
  1460. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1461. if len(opts.RepoIDs) > 0 {
  1462. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1463. }
  1464. if len(opts.IssueIDs) > 0 {
  1465. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1466. }
  1467. if opts.RepoCond != nil {
  1468. cond = cond.And(opts.RepoCond)
  1469. }
  1470. if opts.UserID > 0 {
  1471. cond = cond.And(issuePullAccessibleRepoCond("issue.repo_id", opts.UserID, opts.Org, opts.Team, opts.IsPull))
  1472. }
  1473. sess := func(cond builder.Cond) *xorm.Session {
  1474. s := db.GetEngine(db.DefaultContext).Where(cond)
  1475. if len(opts.LabelIDs) > 0 {
  1476. s.Join("INNER", "issue_label", "issue_label.issue_id = issue.id").
  1477. In("issue_label.label_id", opts.LabelIDs)
  1478. }
  1479. if opts.UserID > 0 || opts.IsArchived != util.OptionalBoolNone {
  1480. s.Join("INNER", "repository", "issue.repo_id = repository.id")
  1481. if opts.IsArchived != util.OptionalBoolNone {
  1482. s.And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()})
  1483. }
  1484. }
  1485. return s
  1486. }
  1487. switch opts.FilterMode {
  1488. case FilterModeAll, FilterModeYourRepositories:
  1489. stats.OpenCount, err = sess(cond).
  1490. And("issue.is_closed = ?", false).
  1491. Count(new(Issue))
  1492. if err != nil {
  1493. return nil, err
  1494. }
  1495. stats.ClosedCount, err = sess(cond).
  1496. And("issue.is_closed = ?", true).
  1497. Count(new(Issue))
  1498. if err != nil {
  1499. return nil, err
  1500. }
  1501. case FilterModeAssign:
  1502. stats.OpenCount, err = applyAssigneeCondition(sess(cond), opts.UserID).
  1503. And("issue.is_closed = ?", false).
  1504. Count(new(Issue))
  1505. if err != nil {
  1506. return nil, err
  1507. }
  1508. stats.ClosedCount, err = applyAssigneeCondition(sess(cond), opts.UserID).
  1509. And("issue.is_closed = ?", true).
  1510. Count(new(Issue))
  1511. if err != nil {
  1512. return nil, err
  1513. }
  1514. case FilterModeCreate:
  1515. stats.OpenCount, err = applyPosterCondition(sess(cond), opts.UserID).
  1516. And("issue.is_closed = ?", false).
  1517. Count(new(Issue))
  1518. if err != nil {
  1519. return nil, err
  1520. }
  1521. stats.ClosedCount, err = applyPosterCondition(sess(cond), opts.UserID).
  1522. And("issue.is_closed = ?", true).
  1523. Count(new(Issue))
  1524. if err != nil {
  1525. return nil, err
  1526. }
  1527. case FilterModeMention:
  1528. stats.OpenCount, err = applyMentionedCondition(sess(cond), opts.UserID).
  1529. And("issue.is_closed = ?", false).
  1530. Count(new(Issue))
  1531. if err != nil {
  1532. return nil, err
  1533. }
  1534. stats.ClosedCount, err = applyMentionedCondition(sess(cond), opts.UserID).
  1535. And("issue.is_closed = ?", true).
  1536. Count(new(Issue))
  1537. if err != nil {
  1538. return nil, err
  1539. }
  1540. case FilterModeReviewRequested:
  1541. stats.OpenCount, err = applyReviewRequestedCondition(sess(cond), opts.UserID).
  1542. And("issue.is_closed = ?", false).
  1543. Count(new(Issue))
  1544. if err != nil {
  1545. return nil, err
  1546. }
  1547. stats.ClosedCount, err = applyReviewRequestedCondition(sess(cond), opts.UserID).
  1548. And("issue.is_closed = ?", true).
  1549. Count(new(Issue))
  1550. if err != nil {
  1551. return nil, err
  1552. }
  1553. }
  1554. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1555. stats.AssignCount, err = applyAssigneeCondition(sess(cond), opts.UserID).Count(new(Issue))
  1556. if err != nil {
  1557. return nil, err
  1558. }
  1559. stats.CreateCount, err = applyPosterCondition(sess(cond), opts.UserID).Count(new(Issue))
  1560. if err != nil {
  1561. return nil, err
  1562. }
  1563. stats.MentionCount, err = applyMentionedCondition(sess(cond), opts.UserID).Count(new(Issue))
  1564. if err != nil {
  1565. return nil, err
  1566. }
  1567. stats.YourRepositoriesCount, err = sess(cond).Count(new(Issue))
  1568. if err != nil {
  1569. return nil, err
  1570. }
  1571. stats.ReviewRequestedCount, err = applyReviewRequestedCondition(sess(cond), opts.UserID).Count(new(Issue))
  1572. if err != nil {
  1573. return nil, err
  1574. }
  1575. return stats, nil
  1576. }
  1577. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1578. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen, numClosed int64) {
  1579. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1580. sess := db.GetEngine(db.DefaultContext).
  1581. Where("is_closed = ?", isClosed).
  1582. And("is_pull = ?", isPull).
  1583. And("repo_id = ?", repoID)
  1584. return sess
  1585. }
  1586. openCountSession := countSession(false, isPull, repoID)
  1587. closedCountSession := countSession(true, isPull, repoID)
  1588. switch filterMode {
  1589. case FilterModeAssign:
  1590. applyAssigneeCondition(openCountSession, uid)
  1591. applyAssigneeCondition(closedCountSession, uid)
  1592. case FilterModeCreate:
  1593. applyPosterCondition(openCountSession, uid)
  1594. applyPosterCondition(closedCountSession, uid)
  1595. }
  1596. openResult, _ := openCountSession.Count(new(Issue))
  1597. closedResult, _ := closedCountSession.Count(new(Issue))
  1598. return openResult, closedResult
  1599. }
  1600. // SearchIssueIDsByKeyword search issues on database
  1601. func SearchIssueIDsByKeyword(ctx context.Context, kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1602. repoCond := builder.In("repo_id", repoIDs)
  1603. subQuery := builder.Select("id").From("issue").Where(repoCond)
  1604. // SQLite's UPPER function only transforms ASCII letters.
  1605. if setting.Database.UseSQLite3 {
  1606. kw = util.ToUpperASCII(kw)
  1607. } else {
  1608. kw = strings.ToUpper(kw)
  1609. }
  1610. cond := builder.And(
  1611. repoCond,
  1612. builder.Or(
  1613. builder.Like{"UPPER(name)", kw},
  1614. builder.Like{"UPPER(content)", kw},
  1615. builder.In("id", builder.Select("issue_id").
  1616. From("comment").
  1617. Where(builder.And(
  1618. builder.Eq{"type": CommentTypeComment},
  1619. builder.In("issue_id", subQuery),
  1620. builder.Like{"UPPER(content)", kw},
  1621. )),
  1622. ),
  1623. ),
  1624. )
  1625. ids := make([]int64, 0, limit)
  1626. res := make([]struct {
  1627. ID int64
  1628. UpdatedUnix int64
  1629. }, 0, limit)
  1630. err := db.GetEngine(ctx).Distinct("id", "updated_unix").Table("issue").Where(cond).
  1631. OrderBy("`updated_unix` DESC").Limit(limit, start).
  1632. Find(&res)
  1633. if err != nil {
  1634. return 0, nil, err
  1635. }
  1636. for _, r := range res {
  1637. ids = append(ids, r.ID)
  1638. }
  1639. total, err := db.GetEngine(ctx).Distinct("id").Table("issue").Where(cond).Count()
  1640. if err != nil {
  1641. return 0, nil, err
  1642. }
  1643. return total, ids, nil
  1644. }
  1645. // UpdateIssueByAPI updates all allowed fields of given issue.
  1646. // If the issue status is changed a statusChangeComment is returned
  1647. // similarly if the title is changed the titleChanged bool is set to true
  1648. func UpdateIssueByAPI(issue *Issue, doer *user_model.User) (statusChangeComment *Comment, titleChanged bool, err error) {
  1649. ctx, committer, err := db.TxContext()
  1650. if err != nil {
  1651. return nil, false, err
  1652. }
  1653. defer committer.Close()
  1654. if err := issue.LoadRepo(ctx); err != nil {
  1655. return nil, false, fmt.Errorf("loadRepo: %v", err)
  1656. }
  1657. // Reload the issue
  1658. currentIssue, err := getIssueByID(ctx, issue.ID)
  1659. if err != nil {
  1660. return nil, false, err
  1661. }
  1662. if _, err := db.GetEngine(ctx).ID(issue.ID).Cols(
  1663. "name", "content", "milestone_id", "priority",
  1664. "deadline_unix", "updated_unix", "is_locked").
  1665. Update(issue); err != nil {
  1666. return nil, false, err
  1667. }
  1668. titleChanged = currentIssue.Title != issue.Title
  1669. if titleChanged {
  1670. opts := &CreateCommentOptions{
  1671. Type: CommentTypeChangeTitle,
  1672. Doer: doer,
  1673. Repo: issue.Repo,
  1674. Issue: issue,
  1675. OldTitle: currentIssue.Title,
  1676. NewTitle: issue.Title,
  1677. }
  1678. _, err := CreateCommentCtx(ctx, opts)
  1679. if err != nil {
  1680. return nil, false, fmt.Errorf("createComment: %v", err)
  1681. }
  1682. }
  1683. if currentIssue.IsClosed != issue.IsClosed {
  1684. statusChangeComment, err = doChangeIssueStatus(ctx, issue, doer, false)
  1685. if err != nil {
  1686. return nil, false, err
  1687. }
  1688. }
  1689. if err := issue.addCrossReferences(ctx, doer, true); err != nil {
  1690. return nil, false, err
  1691. }
  1692. return statusChangeComment, titleChanged, committer.Commit()
  1693. }
  1694. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1695. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *user_model.User) (err error) {
  1696. // if the deadline hasn't changed do nothing
  1697. if issue.DeadlineUnix == deadlineUnix {
  1698. return nil
  1699. }
  1700. ctx, committer, err := db.TxContext()
  1701. if err != nil {
  1702. return err
  1703. }
  1704. defer committer.Close()
  1705. // Update the deadline
  1706. if err = UpdateIssueCols(ctx, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1707. return err
  1708. }
  1709. // Make the comment
  1710. if _, err = createDeadlineComment(ctx, doer, issue, deadlineUnix); err != nil {
  1711. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1712. }
  1713. return committer.Commit()
  1714. }
  1715. // DeleteIssue deletes the issue
  1716. func DeleteIssue(issue *Issue) error {
  1717. ctx, committer, err := db.TxContext()
  1718. if err != nil {
  1719. return err
  1720. }
  1721. defer committer.Close()
  1722. if err := deleteIssue(ctx, issue); err != nil {
  1723. return err
  1724. }
  1725. return committer.Commit()
  1726. }
  1727. func deleteInIssue(ctx context.Context, issueID int64, beans ...interface{}) error {
  1728. e := db.GetEngine(ctx)
  1729. for _, bean := range beans {
  1730. if _, err := e.In("issue_id", issueID).Delete(bean); err != nil {
  1731. return err
  1732. }
  1733. }
  1734. return nil
  1735. }
  1736. func deleteIssue(ctx context.Context, issue *Issue) error {
  1737. e := db.GetEngine(ctx)
  1738. if _, err := e.ID(issue.ID).NoAutoCondition().Delete(issue); err != nil {
  1739. return err
  1740. }
  1741. if issue.IsPull {
  1742. if _, err := e.ID(issue.RepoID).Decr("num_pulls").Update(new(repo_model.Repository)); err != nil {
  1743. return err
  1744. }
  1745. if issue.IsClosed {
  1746. if _, err := e.ID(issue.RepoID).Decr("num_closed_pulls").Update(new(repo_model.Repository)); err != nil {
  1747. return err
  1748. }
  1749. }
  1750. } else {
  1751. if _, err := e.ID(issue.RepoID).Decr("num_issues").Update(new(repo_model.Repository)); err != nil {
  1752. return err
  1753. }
  1754. if issue.IsClosed {
  1755. if _, err := e.ID(issue.RepoID).Decr("num_closed_issues").Update(new(repo_model.Repository)); err != nil {
  1756. return err
  1757. }
  1758. }
  1759. }
  1760. // delete actions assigned to this issue
  1761. subQuery := builder.Select("`id`").
  1762. From("`comment`").
  1763. Where(builder.Eq{"`issue_id`": issue.ID})
  1764. if _, err := e.In("comment_id", subQuery).Delete(&Action{}); err != nil {
  1765. return err
  1766. }
  1767. if _, err := e.Table("action").Where("repo_id = ?", issue.RepoID).
  1768. In("op_type", ActionCreateIssue, ActionCreatePullRequest).
  1769. Where("content LIKE ?", strconv.FormatInt(issue.ID, 10)+"|%").
  1770. Delete(&Action{}); err != nil {
  1771. return err
  1772. }
  1773. // find attachments related to this issue and remove them
  1774. var attachments []*repo_model.Attachment
  1775. if err := e.In("issue_id", issue.ID).Find(&attachments); err != nil {
  1776. return err
  1777. }
  1778. for i := range attachments {
  1779. admin_model.RemoveStorageWithNotice(ctx, storage.Attachments, "Delete issue attachment", attachments[i].RelativePath())
  1780. }
  1781. // delete all database data still assigned to this issue
  1782. if err := deleteInIssue(ctx, issue.ID,
  1783. &issues_model.ContentHistory{},
  1784. &Comment{},
  1785. &IssueLabel{},
  1786. &IssueDependency{},
  1787. &IssueAssignees{},
  1788. &IssueUser{},
  1789. &Notification{},
  1790. &issues_model.Reaction{},
  1791. &IssueWatch{},
  1792. &Stopwatch{},
  1793. &TrackedTime{},
  1794. &project_model.ProjectIssue{},
  1795. &repo_model.Attachment{},
  1796. &PullRequest{},
  1797. ); err != nil {
  1798. return err
  1799. }
  1800. // References to this issue in other issues
  1801. if _, err := e.In("ref_issue_id", issue.ID).Delete(&Comment{}); err != nil {
  1802. return err
  1803. }
  1804. // Delete dependencies for issues in other repositories
  1805. if _, err := e.In("dependency_id", issue.ID).Delete(&IssueDependency{}); err != nil {
  1806. return err
  1807. }
  1808. // delete from dependent issues
  1809. if _, err := e.In("dependent_issue_id", issue.ID).Delete(&Comment{}); err != nil {
  1810. return err
  1811. }
  1812. return nil
  1813. }
  1814. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1815. type DependencyInfo struct {
  1816. Issue `xorm:"extends"`
  1817. repo_model.Repository `xorm:"extends"`
  1818. }
  1819. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1820. func (issue *Issue) getParticipantIDsByIssue(ctx context.Context) ([]int64, error) {
  1821. if issue == nil {
  1822. return nil, nil
  1823. }
  1824. userIDs := make([]int64, 0, 5)
  1825. if err := db.GetEngine(ctx).Table("comment").Cols("poster_id").
  1826. Where("`comment`.issue_id = ?", issue.ID).
  1827. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1828. And("`user`.is_active = ?", true).
  1829. And("`user`.prohibit_login = ?", false).
  1830. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1831. Distinct("poster_id").
  1832. Find(&userIDs); err != nil {
  1833. return nil, fmt.Errorf("get poster IDs: %v", err)
  1834. }
  1835. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1836. return append(userIDs, issue.PosterID), nil
  1837. }
  1838. return userIDs, nil
  1839. }
  1840. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1841. func (issue *Issue) BlockedByDependencies(ctx context.Context) (issueDeps []*DependencyInfo, err error) {
  1842. err = db.GetEngine(ctx).
  1843. Table("issue").
  1844. Join("INNER", "repository", "repository.id = issue.repo_id").
  1845. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1846. Where("issue_id = ?", issue.ID).
  1847. // sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1848. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1849. Find(&issueDeps)
  1850. for _, depInfo := range issueDeps {
  1851. depInfo.Issue.Repo = &depInfo.Repository
  1852. }
  1853. return issueDeps, err
  1854. }
  1855. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1856. func (issue *Issue) BlockingDependencies(ctx context.Context) (issueDeps []*DependencyInfo, err error) {
  1857. err = db.GetEngine(ctx).
  1858. Table("issue").
  1859. Join("INNER", "repository", "repository.id = issue.repo_id").
  1860. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1861. Where("dependency_id = ?", issue.ID).
  1862. // sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1863. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1864. Find(&issueDeps)
  1865. for _, depInfo := range issueDeps {
  1866. depInfo.Issue.Repo = &depInfo.Repository
  1867. }
  1868. return issueDeps, err
  1869. }
  1870. func updateIssueClosedNum(ctx context.Context, issue *Issue) (err error) {
  1871. if issue.IsPull {
  1872. err = repoStatsCorrectNumClosed(ctx, issue.RepoID, true, "num_closed_pulls")
  1873. } else {
  1874. err = repoStatsCorrectNumClosed(ctx, issue.RepoID, false, "num_closed_issues")
  1875. }
  1876. return
  1877. }
  1878. // FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database.
  1879. func FindAndUpdateIssueMentions(ctx context.Context, issue *Issue, doer *user_model.User, content string) (mentions []*user_model.User, err error) {
  1880. rawMentions := references.FindAllMentionsMarkdown(content)
  1881. mentions, err = ResolveIssueMentionsByVisibility(ctx, issue, doer, rawMentions)
  1882. if err != nil {
  1883. return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
  1884. }
  1885. if err = UpdateIssueMentions(ctx, issue.ID, mentions); err != nil {
  1886. return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
  1887. }
  1888. return
  1889. }
  1890. // ResolveIssueMentionsByVisibility returns the users mentioned in an issue, removing those that
  1891. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1892. func ResolveIssueMentionsByVisibility(ctx context.Context, issue *Issue, doer *user_model.User, mentions []string) (users []*user_model.User, err error) {
  1893. if len(mentions) == 0 {
  1894. return
  1895. }
  1896. if err = issue.LoadRepo(ctx); err != nil {
  1897. return
  1898. }
  1899. resolved := make(map[string]bool, 10)
  1900. var mentionTeams []string
  1901. if err := issue.Repo.GetOwner(ctx); err != nil {
  1902. return nil, err
  1903. }
  1904. repoOwnerIsOrg := issue.Repo.Owner.IsOrganization()
  1905. if repoOwnerIsOrg {
  1906. mentionTeams = make([]string, 0, 5)
  1907. }
  1908. resolved[doer.LowerName] = true
  1909. for _, name := range mentions {
  1910. name := strings.ToLower(name)
  1911. if _, ok := resolved[name]; ok {
  1912. continue
  1913. }
  1914. if repoOwnerIsOrg && strings.Contains(name, "/") {
  1915. names := strings.Split(name, "/")
  1916. if len(names) < 2 || names[0] != issue.Repo.Owner.LowerName {
  1917. continue
  1918. }
  1919. mentionTeams = append(mentionTeams, names[1])
  1920. resolved[name] = true
  1921. } else {
  1922. resolved[name] = false
  1923. }
  1924. }
  1925. if issue.Repo.Owner.IsOrganization() && len(mentionTeams) > 0 {
  1926. teams := make([]*organization.Team, 0, len(mentionTeams))
  1927. if err := db.GetEngine(ctx).
  1928. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1929. Where("team_repo.repo_id=?", issue.Repo.ID).
  1930. In("team.lower_name", mentionTeams).
  1931. Find(&teams); err != nil {
  1932. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1933. }
  1934. if len(teams) != 0 {
  1935. checked := make([]int64, 0, len(teams))
  1936. unittype := unit.TypeIssues
  1937. if issue.IsPull {
  1938. unittype = unit.TypePullRequests
  1939. }
  1940. for _, team := range teams {
  1941. if team.AccessMode >= perm.AccessModeAdmin {
  1942. checked = append(checked, team.ID)
  1943. resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true
  1944. continue
  1945. }
  1946. has, err := db.GetEngine(ctx).Get(&organization.TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1947. if err != nil {
  1948. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1949. }
  1950. if has {
  1951. checked = append(checked, team.ID)
  1952. resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true
  1953. }
  1954. }
  1955. if len(checked) != 0 {
  1956. teamusers := make([]*user_model.User, 0, 20)
  1957. if err := db.GetEngine(ctx).
  1958. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1959. In("`team_user`.team_id", checked).
  1960. And("`user`.is_active = ?", true).
  1961. And("`user`.prohibit_login = ?", false).
  1962. Find(&teamusers); err != nil {
  1963. return nil, fmt.Errorf("get teams users: %v", err)
  1964. }
  1965. if len(teamusers) > 0 {
  1966. users = make([]*user_model.User, 0, len(teamusers))
  1967. for _, user := range teamusers {
  1968. if already, ok := resolved[user.LowerName]; !ok || !already {
  1969. users = append(users, user)
  1970. resolved[user.LowerName] = true
  1971. }
  1972. }
  1973. }
  1974. }
  1975. }
  1976. }
  1977. // Remove names already in the list to avoid querying the database if pending names remain
  1978. mentionUsers := make([]string, 0, len(resolved))
  1979. for name, already := range resolved {
  1980. if !already {
  1981. mentionUsers = append(mentionUsers, name)
  1982. }
  1983. }
  1984. if len(mentionUsers) == 0 {
  1985. return
  1986. }
  1987. if users == nil {
  1988. users = make([]*user_model.User, 0, len(mentionUsers))
  1989. }
  1990. unchecked := make([]*user_model.User, 0, len(mentionUsers))
  1991. if err := db.GetEngine(ctx).
  1992. Where("`user`.is_active = ?", true).
  1993. And("`user`.prohibit_login = ?", false).
  1994. In("`user`.lower_name", mentionUsers).
  1995. Find(&unchecked); err != nil {
  1996. return nil, fmt.Errorf("find mentioned users: %v", err)
  1997. }
  1998. for _, user := range unchecked {
  1999. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  2000. continue
  2001. }
  2002. // Normal users must have read access to the referencing issue
  2003. perm, err := access_model.GetUserRepoPermission(ctx, issue.Repo, user)
  2004. if err != nil {
  2005. return nil, fmt.Errorf("GetUserRepoPermission [%d]: %v", user.ID, err)
  2006. }
  2007. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  2008. continue
  2009. }
  2010. users = append(users, user)
  2011. }
  2012. return
  2013. }
  2014. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  2015. func UpdateIssuesMigrationsByType(gitServiceType api.GitServiceType, originalAuthorID string, posterID int64) error {
  2016. _, err := db.GetEngine(db.DefaultContext).Table("issue").
  2017. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  2018. And("original_author_id = ?", originalAuthorID).
  2019. Update(map[string]interface{}{
  2020. "poster_id": posterID,
  2021. "original_author": "",
  2022. "original_author_id": 0,
  2023. })
  2024. return err
  2025. }
  2026. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  2027. func UpdateReactionsMigrationsByType(gitServiceType api.GitServiceType, originalAuthorID string, userID int64) error {
  2028. _, err := db.GetEngine(db.DefaultContext).Table("reaction").
  2029. Where("original_author_id = ?", originalAuthorID).
  2030. And(migratedIssueCond(gitServiceType)).
  2031. Update(map[string]interface{}{
  2032. "user_id": userID,
  2033. "original_author": "",
  2034. "original_author_id": 0,
  2035. })
  2036. return err
  2037. }
  2038. func deleteIssuesByRepoID(ctx context.Context, repoID int64) (attachmentPaths []string, err error) {
  2039. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"issue.repo_id": repoID})
  2040. sess := db.GetEngine(ctx)
  2041. // Delete content histories
  2042. if _, err = sess.In("issue_id", deleteCond).
  2043. Delete(&issues_model.ContentHistory{}); err != nil {
  2044. return
  2045. }
  2046. // Delete comments and attachments
  2047. if _, err = sess.In("issue_id", deleteCond).
  2048. Delete(&Comment{}); err != nil {
  2049. return
  2050. }
  2051. // Dependencies for issues in this repository
  2052. if _, err = sess.In("issue_id", deleteCond).
  2053. Delete(&IssueDependency{}); err != nil {
  2054. return
  2055. }
  2056. // Delete dependencies for issues in other repositories
  2057. if _, err = sess.In("dependency_id", deleteCond).
  2058. Delete(&IssueDependency{}); err != nil {
  2059. return
  2060. }
  2061. if _, err = sess.In("issue_id", deleteCond).
  2062. Delete(&IssueUser{}); err != nil {
  2063. return
  2064. }
  2065. if _, err = sess.In("issue_id", deleteCond).
  2066. Delete(&issues_model.Reaction{}); err != nil {
  2067. return
  2068. }
  2069. if _, err = sess.In("issue_id", deleteCond).
  2070. Delete(&IssueWatch{}); err != nil {
  2071. return
  2072. }
  2073. if _, err = sess.In("issue_id", deleteCond).
  2074. Delete(&Stopwatch{}); err != nil {
  2075. return
  2076. }
  2077. if _, err = sess.In("issue_id", deleteCond).
  2078. Delete(&TrackedTime{}); err != nil {
  2079. return
  2080. }
  2081. if _, err = sess.In("issue_id", deleteCond).
  2082. Delete(&project_model.ProjectIssue{}); err != nil {
  2083. return
  2084. }
  2085. if _, err = sess.In("dependent_issue_id", deleteCond).
  2086. Delete(&Comment{}); err != nil {
  2087. return
  2088. }
  2089. var attachments []*repo_model.Attachment
  2090. if err = sess.In("issue_id", deleteCond).
  2091. Find(&attachments); err != nil {
  2092. return
  2093. }
  2094. for j := range attachments {
  2095. attachmentPaths = append(attachmentPaths, attachments[j].RelativePath())
  2096. }
  2097. if _, err = sess.In("issue_id", deleteCond).
  2098. Delete(&repo_model.Attachment{}); err != nil {
  2099. return
  2100. }
  2101. if _, err = db.DeleteByBean(ctx, &Issue{RepoID: repoID}); err != nil {
  2102. return
  2103. }
  2104. return
  2105. }
  2106. // RemapExternalUser ExternalUserRemappable interface
  2107. func (issue *Issue) RemapExternalUser(externalName string, externalID, userID int64) error {
  2108. issue.OriginalAuthor = externalName
  2109. issue.OriginalAuthorID = externalID
  2110. issue.PosterID = userID
  2111. return nil
  2112. }
  2113. // GetUserID ExternalUserRemappable interface
  2114. func (issue *Issue) GetUserID() int64 { return issue.PosterID }
  2115. // GetExternalName ExternalUserRemappable interface
  2116. func (issue *Issue) GetExternalName() string { return issue.OriginalAuthor }
  2117. // GetExternalID ExternalUserRemappable interface
  2118. func (issue *Issue) GetExternalID() int64 { return issue.OriginalAuthorID }