this repo has no description
1package issues 2 3import ( 4 "context" 5 "database/sql" 6 "errors" 7 "fmt" 8 "log/slog" 9 "net/http" 10 "time" 11 12 comatproto "github.com/bluesky-social/indigo/api/atproto" 13 atpclient "github.com/bluesky-social/indigo/atproto/client" 14 "github.com/bluesky-social/indigo/atproto/syntax" 15 lexutil "github.com/bluesky-social/indigo/lex/util" 16 "github.com/go-chi/chi/v5" 17 18 "tangled.org/core/api/tangled" 19 "tangled.org/core/appview/config" 20 "tangled.org/core/appview/db" 21 issues_indexer "tangled.org/core/appview/indexer/issues" 22 "tangled.org/core/appview/mentions" 23 "tangled.org/core/appview/models" 24 "tangled.org/core/appview/notify" 25 "tangled.org/core/appview/oauth" 26 "tangled.org/core/appview/pages" 27 "tangled.org/core/appview/pages/repoinfo" 28 "tangled.org/core/appview/pagination" 29 "tangled.org/core/appview/reporesolver" 30 "tangled.org/core/appview/validator" 31 "tangled.org/core/idresolver" 32 "tangled.org/core/orm" 33 "tangled.org/core/rbac" 34 "tangled.org/core/tid" 35) 36 37type Issues struct { 38 oauth *oauth.OAuth 39 repoResolver *reporesolver.RepoResolver 40 enforcer *rbac.Enforcer 41 pages *pages.Pages 42 idResolver *idresolver.Resolver 43 mentionsResolver *mentions.Resolver 44 db *db.DB 45 config *config.Config 46 notifier notify.Notifier 47 logger *slog.Logger 48 validator *validator.Validator 49 indexer *issues_indexer.Indexer 50} 51 52func New( 53 oauth *oauth.OAuth, 54 repoResolver *reporesolver.RepoResolver, 55 enforcer *rbac.Enforcer, 56 pages *pages.Pages, 57 idResolver *idresolver.Resolver, 58 mentionsResolver *mentions.Resolver, 59 db *db.DB, 60 config *config.Config, 61 notifier notify.Notifier, 62 validator *validator.Validator, 63 indexer *issues_indexer.Indexer, 64 logger *slog.Logger, 65) *Issues { 66 return &Issues{ 67 oauth: oauth, 68 repoResolver: repoResolver, 69 enforcer: enforcer, 70 pages: pages, 71 idResolver: idResolver, 72 mentionsResolver: mentionsResolver, 73 db: db, 74 config: config, 75 notifier: notifier, 76 logger: logger, 77 validator: validator, 78 indexer: indexer, 79 } 80} 81 82func (rp *Issues) RepoSingleIssue(w http.ResponseWriter, r *http.Request) { 83 l := rp.logger.With("handler", "RepoSingleIssue") 84 user := rp.oauth.GetUser(r) 85 f, err := rp.repoResolver.Resolve(r) 86 if err != nil { 87 l.Error("failed to get repo and knot", "err", err) 88 return 89 } 90 91 issue, ok := r.Context().Value("issue").(*models.Issue) 92 if !ok { 93 l.Error("failed to get issue") 94 rp.pages.Error404(w) 95 return 96 } 97 98 reactionMap, err := db.GetReactionMap(rp.db, 20, issue.AtUri()) 99 if err != nil { 100 l.Error("failed to get issue reactions", "err", err) 101 } 102 103 userReactions := map[models.ReactionKind]bool{} 104 if user != nil { 105 userReactions = db.GetReactionStatusMap(rp.db, user.Did, issue.AtUri()) 106 } 107 108 backlinks, err := db.GetBacklinks(rp.db, issue.AtUri()) 109 if err != nil { 110 l.Error("failed to fetch backlinks", "err", err) 111 rp.pages.Error503(w) 112 return 113 } 114 115 labelDefs, err := db.GetLabelDefinitions( 116 rp.db, 117 orm.FilterIn("at_uri", f.Labels), 118 orm.FilterContains("scope", tangled.RepoIssueNSID), 119 ) 120 if err != nil { 121 l.Error("failed to fetch labels", "err", err) 122 rp.pages.Error503(w) 123 return 124 } 125 126 defs := make(map[string]*models.LabelDefinition) 127 for _, l := range labelDefs { 128 defs[l.AtUri().String()] = &l 129 } 130 131 rp.pages.RepoSingleIssue(w, pages.RepoSingleIssueParams{ 132 LoggedInUser: user, 133 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 134 Issue: issue, 135 CommentList: issue.CommentList(), 136 Backlinks: backlinks, 137 OrderedReactionKinds: models.OrderedReactionKinds, 138 Reactions: reactionMap, 139 UserReacted: userReactions, 140 LabelDefs: defs, 141 }) 142} 143 144func (rp *Issues) EditIssue(w http.ResponseWriter, r *http.Request) { 145 l := rp.logger.With("handler", "EditIssue") 146 user := rp.oauth.GetUser(r) 147 148 issue, ok := r.Context().Value("issue").(*models.Issue) 149 if !ok { 150 l.Error("failed to get issue") 151 rp.pages.Error404(w) 152 return 153 } 154 155 switch r.Method { 156 case http.MethodGet: 157 rp.pages.EditIssueFragment(w, pages.EditIssueParams{ 158 LoggedInUser: user, 159 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 160 Issue: issue, 161 }) 162 case http.MethodPost: 163 noticeId := "issues" 164 newIssue := issue 165 newIssue.Title = r.FormValue("title") 166 newIssue.Body = r.FormValue("body") 167 newIssue.Mentions, newIssue.References = rp.mentionsResolver.Resolve(r.Context(), newIssue.Body) 168 169 if err := rp.validator.ValidateIssue(newIssue); err != nil { 170 l.Error("validation error", "err", err) 171 rp.pages.Notice(w, noticeId, fmt.Sprintf("Failed to edit issue: %s", err)) 172 return 173 } 174 175 newRecord := newIssue.AsRecord() 176 177 // edit an atproto record 178 client, err := rp.oauth.AuthorizedClient(r) 179 if err != nil { 180 l.Error("failed to get authorized client", "err", err) 181 rp.pages.Notice(w, noticeId, "Failed to edit issue.") 182 return 183 } 184 185 ex, err := comatproto.RepoGetRecord(r.Context(), client, "", tangled.RepoIssueNSID, user.Did, newIssue.Rkey) 186 if err != nil { 187 l.Error("failed to get record", "err", err) 188 rp.pages.Notice(w, noticeId, "Failed to edit issue, no record found on PDS.") 189 return 190 } 191 192 _, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{ 193 Collection: tangled.RepoIssueNSID, 194 Repo: user.Did, 195 Rkey: newIssue.Rkey, 196 SwapRecord: ex.Cid, 197 Record: &lexutil.LexiconTypeDecoder{ 198 Val: &newRecord, 199 }, 200 }) 201 if err != nil { 202 l.Error("failed to edit record on PDS", "err", err) 203 rp.pages.Notice(w, noticeId, "Failed to edit issue on PDS.") 204 return 205 } 206 207 // modify on DB -- TODO: transact this cleverly 208 tx, err := rp.db.Begin() 209 if err != nil { 210 l.Error("failed to edit issue on DB", "err", err) 211 rp.pages.Notice(w, noticeId, "Failed to edit issue.") 212 return 213 } 214 defer tx.Rollback() 215 216 err = db.PutIssue(tx, newIssue) 217 if err != nil { 218 l.Error("failed to edit issue", "err", err) 219 rp.pages.Notice(w, "issues", "Failed to edit issue.") 220 return 221 } 222 223 if err = tx.Commit(); err != nil { 224 l.Error("failed to edit issue", "err", err) 225 rp.pages.Notice(w, "issues", "Failed to cedit issue.") 226 return 227 } 228 229 rp.pages.HxRefresh(w) 230 } 231} 232 233func (rp *Issues) DeleteIssue(w http.ResponseWriter, r *http.Request) { 234 l := rp.logger.With("handler", "DeleteIssue") 235 noticeId := "issue-actions-error" 236 237 f, err := rp.repoResolver.Resolve(r) 238 if err != nil { 239 l.Error("failed to get repo and knot", "err", err) 240 return 241 } 242 243 issue, ok := r.Context().Value("issue").(*models.Issue) 244 if !ok { 245 l.Error("failed to get issue") 246 rp.pages.Notice(w, noticeId, "Failed to delete issue.") 247 return 248 } 249 l = l.With("did", issue.Did, "rkey", issue.Rkey) 250 251 tx, err := rp.db.Begin() 252 if err != nil { 253 l.Error("failed to start transaction", "err", err) 254 rp.pages.Notice(w, "issue-comment", "Failed to create comment, try again later.") 255 return 256 } 257 defer tx.Rollback() 258 259 // delete from PDS 260 client, err := rp.oauth.AuthorizedClient(r) 261 if err != nil { 262 l.Error("failed to get authorized client", "err", err) 263 rp.pages.Notice(w, "issue-comment", "Failed to delete comment.") 264 return 265 } 266 _, err = comatproto.RepoDeleteRecord(r.Context(), client, &comatproto.RepoDeleteRecord_Input{ 267 Collection: tangled.RepoIssueNSID, 268 Repo: issue.Did, 269 Rkey: issue.Rkey, 270 }) 271 if err != nil { 272 // TODO: transact this better 273 l.Error("failed to delete issue from PDS", "err", err) 274 rp.pages.Notice(w, noticeId, "Failed to delete issue.") 275 return 276 } 277 278 // delete from db 279 if err := db.DeleteIssues(tx, issue.Did, issue.Rkey); err != nil { 280 l.Error("failed to delete issue", "err", err) 281 rp.pages.Notice(w, noticeId, "Failed to delete issue.") 282 return 283 } 284 tx.Commit() 285 286 rp.notifier.DeleteIssue(r.Context(), issue) 287 288 // return to all issues page 289 ownerSlashRepo := reporesolver.GetBaseRepoPath(r, f) 290 rp.pages.HxRedirect(w, "/"+ownerSlashRepo+"/issues") 291} 292 293func (rp *Issues) CloseIssue(w http.ResponseWriter, r *http.Request) { 294 l := rp.logger.With("handler", "CloseIssue") 295 user := rp.oauth.GetUser(r) 296 f, err := rp.repoResolver.Resolve(r) 297 if err != nil { 298 l.Error("failed to get repo and knot", "err", err) 299 return 300 } 301 302 issue, ok := r.Context().Value("issue").(*models.Issue) 303 if !ok { 304 l.Error("failed to get issue") 305 rp.pages.Error404(w) 306 return 307 } 308 309 roles := repoinfo.RolesInRepo{Roles: rp.enforcer.GetPermissionsInRepo(user.Did, f.Knot, f.DidSlashRepo())} 310 isRepoOwner := roles.IsOwner() 311 isCollaborator := roles.IsCollaborator() 312 isIssueOwner := user.Did == issue.Did 313 314 // TODO: make this more granular 315 if isIssueOwner || isRepoOwner || isCollaborator { 316 err = db.CloseIssues( 317 rp.db, 318 orm.FilterEq("id", issue.Id), 319 ) 320 if err != nil { 321 l.Error("failed to close issue", "err", err) 322 rp.pages.Notice(w, "issue-action", "Failed to close issue. Try again later.") 323 return 324 } 325 // change the issue state (this will pass down to the notifiers) 326 issue.Open = false 327 328 // notify about the issue closure 329 rp.notifier.NewIssueState(r.Context(), syntax.DID(user.Did), issue) 330 331 ownerSlashRepo := reporesolver.GetBaseRepoPath(r, f) 332 rp.pages.HxLocation(w, fmt.Sprintf("/%s/issues/%d", ownerSlashRepo, issue.IssueId)) 333 return 334 } else { 335 l.Error("user is not permitted to close issue") 336 http.Error(w, "for biden", http.StatusUnauthorized) 337 return 338 } 339} 340 341func (rp *Issues) ReopenIssue(w http.ResponseWriter, r *http.Request) { 342 l := rp.logger.With("handler", "ReopenIssue") 343 user := rp.oauth.GetUser(r) 344 f, err := rp.repoResolver.Resolve(r) 345 if err != nil { 346 l.Error("failed to get repo and knot", "err", err) 347 return 348 } 349 350 issue, ok := r.Context().Value("issue").(*models.Issue) 351 if !ok { 352 l.Error("failed to get issue") 353 rp.pages.Error404(w) 354 return 355 } 356 357 roles := repoinfo.RolesInRepo{Roles: rp.enforcer.GetPermissionsInRepo(user.Did, f.Knot, f.DidSlashRepo())} 358 isRepoOwner := roles.IsOwner() 359 isCollaborator := roles.IsCollaborator() 360 isIssueOwner := user.Did == issue.Did 361 362 if isCollaborator || isRepoOwner || isIssueOwner { 363 err := db.ReopenIssues( 364 rp.db, 365 orm.FilterEq("id", issue.Id), 366 ) 367 if err != nil { 368 l.Error("failed to reopen issue", "err", err) 369 rp.pages.Notice(w, "issue-action", "Failed to reopen issue. Try again later.") 370 return 371 } 372 // change the issue state (this will pass down to the notifiers) 373 issue.Open = true 374 375 // notify about the issue reopen 376 rp.notifier.NewIssueState(r.Context(), syntax.DID(user.Did), issue) 377 378 ownerSlashRepo := reporesolver.GetBaseRepoPath(r, f) 379 rp.pages.HxLocation(w, fmt.Sprintf("/%s/issues/%d", ownerSlashRepo, issue.IssueId)) 380 return 381 } else { 382 l.Error("user is not the owner of the repo") 383 http.Error(w, "forbidden", http.StatusUnauthorized) 384 return 385 } 386} 387 388func (rp *Issues) NewIssueComment(w http.ResponseWriter, r *http.Request) { 389 l := rp.logger.With("handler", "NewIssueComment") 390 user := rp.oauth.GetUser(r) 391 f, err := rp.repoResolver.Resolve(r) 392 if err != nil { 393 l.Error("failed to get repo and knot", "err", err) 394 return 395 } 396 397 issue, ok := r.Context().Value("issue").(*models.Issue) 398 if !ok { 399 l.Error("failed to get issue") 400 rp.pages.Error404(w) 401 return 402 } 403 404 body := r.FormValue("body") 405 if body == "" { 406 rp.pages.Notice(w, "issue-comment", "Body is required") 407 return 408 } 409 410 var replyTo *syntax.ATURI 411 replyToRaw := r.FormValue("reply-to") 412 if replyToRaw != "" { 413 aturi, err := syntax.ParseATURI(r.FormValue("reply-to")) 414 if err != nil { 415 rp.pages.Notice(w, "issue-comment", "reply-to should be valid AT-URI") 416 return 417 } 418 replyTo = &aturi 419 } 420 421 mentions, references := rp.mentionsResolver.Resolve(r.Context(), body) 422 423 comment := models.Comment{ 424 Did: syntax.DID(user.Did), 425 Rkey: tid.TID(), 426 Subject: issue.AtUri(), 427 ReplyTo: replyTo, 428 Body: body, 429 Created: time.Now(), 430 Mentions: mentions, 431 References: references, 432 } 433 if err = comment.Validate(); err != nil { 434 l.Error("failed to validate comment", "err", err) 435 rp.pages.Notice(w, "issue-comment", "Failed to create comment.") 436 return 437 } 438 record := comment.AsRecord() 439 440 client, err := rp.oauth.AuthorizedClient(r) 441 if err != nil { 442 l.Error("failed to get authorized client", "err", err) 443 rp.pages.Notice(w, "issue-comment", "Failed to create comment.") 444 return 445 } 446 447 // create a record first 448 resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{ 449 Collection: tangled.CommentNSID, 450 Repo: user.Did, 451 Rkey: comment.Rkey, 452 Record: &lexutil.LexiconTypeDecoder{ 453 Val: &record, 454 }, 455 }) 456 if err != nil { 457 l.Error("failed to create comment", "err", err) 458 rp.pages.Notice(w, "issue-comment", "Failed to create comment.") 459 return 460 } 461 atUri := resp.Uri 462 defer func() { 463 if err := rollbackRecord(context.Background(), atUri, client); err != nil { 464 l.Error("rollback failed", "err", err) 465 } 466 }() 467 468 tx, err := rp.db.Begin() 469 if err != nil { 470 l.Error("failed to start transaction", "err", err) 471 rp.pages.Notice(w, "issue-comment", "Failed to create comment, try again later.") 472 return 473 } 474 defer tx.Rollback() 475 476 err = db.PutComment(tx, &comment) 477 if err != nil { 478 l.Error("failed to create comment", "err", err) 479 rp.pages.Notice(w, "issue-comment", "Failed to create comment.") 480 return 481 } 482 err = tx.Commit() 483 if err != nil { 484 l.Error("failed to commit transaction", "err", err) 485 rp.pages.Notice(w, "issue-comment", "Failed to create comment, try again later.") 486 return 487 } 488 489 // reset atUri to make rollback a no-op 490 atUri = "" 491 492 rp.notifier.NewIssueComment(r.Context(), &comment, mentions) 493 494 ownerSlashRepo := reporesolver.GetBaseRepoPath(r, f) 495 rp.pages.HxLocation(w, fmt.Sprintf("/%s/issues/%d#comment-%d", ownerSlashRepo, issue.IssueId, comment.Id)) 496} 497 498func (rp *Issues) IssueComment(w http.ResponseWriter, r *http.Request) { 499 l := rp.logger.With("handler", "IssueComment") 500 user := rp.oauth.GetUser(r) 501 502 issue, ok := r.Context().Value("issue").(*models.Issue) 503 if !ok { 504 l.Error("failed to get issue") 505 rp.pages.Error404(w) 506 return 507 } 508 509 commentId := chi.URLParam(r, "commentId") 510 comments, err := db.GetComments( 511 rp.db, 512 orm.FilterEq("id", commentId), 513 ) 514 if err != nil { 515 l.Error("failed to fetch comment", "id", commentId) 516 http.Error(w, "failed to fetch comment id", http.StatusBadRequest) 517 return 518 } 519 if len(comments) != 1 { 520 l.Error("incorrect number of comments returned", "id", commentId, "len(comments)", len(comments)) 521 http.Error(w, "invalid comment id", http.StatusBadRequest) 522 return 523 } 524 comment := comments[0] 525 526 rp.pages.IssueCommentBodyFragment(w, pages.IssueCommentBodyParams{ 527 LoggedInUser: user, 528 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 529 Issue: issue, 530 Comment: &comment, 531 }) 532} 533 534func (rp *Issues) EditIssueComment(w http.ResponseWriter, r *http.Request) { 535 l := rp.logger.With("handler", "EditIssueComment") 536 user := rp.oauth.GetUser(r) 537 538 issue, ok := r.Context().Value("issue").(*models.Issue) 539 if !ok { 540 l.Error("failed to get issue") 541 rp.pages.Error404(w) 542 return 543 } 544 545 commentId := chi.URLParam(r, "commentId") 546 comments, err := db.GetComments( 547 rp.db, 548 orm.FilterEq("id", commentId), 549 ) 550 if err != nil { 551 l.Error("failed to fetch comment", "id", commentId) 552 http.Error(w, "failed to fetch comment id", http.StatusBadRequest) 553 return 554 } 555 if len(comments) != 1 { 556 l.Error("incorrect number of comments returned", "id", commentId, "len(comments)", len(comments)) 557 http.Error(w, "invalid comment id", http.StatusBadRequest) 558 return 559 } 560 comment := comments[0] 561 562 if comment.Did.String() != user.Did { 563 l.Error("unauthorized comment edit", "expectedDid", comment.Did, "gotDid", user.Did) 564 http.Error(w, "you are not the author of this comment", http.StatusUnauthorized) 565 return 566 } 567 568 switch r.Method { 569 case http.MethodGet: 570 rp.pages.EditIssueCommentFragment(w, pages.EditIssueCommentParams{ 571 LoggedInUser: user, 572 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 573 Issue: issue, 574 Comment: &comment, 575 }) 576 case http.MethodPost: 577 // extract form value 578 newBody := r.FormValue("body") 579 client, err := rp.oauth.AuthorizedClient(r) 580 if err != nil { 581 l.Error("failed to get authorized client", "err", err) 582 rp.pages.Notice(w, "issue-comment", "Failed to create comment.") 583 return 584 } 585 586 now := time.Now() 587 newComment := comment 588 newComment.Body = newBody 589 newComment.Edited = &now 590 newComment.Mentions, newComment.References = rp.mentionsResolver.Resolve(r.Context(), newBody) 591 592 record := newComment.AsRecord() 593 594 tx, err := rp.db.Begin() 595 if err != nil { 596 l.Error("failed to start transaction", "err", err) 597 rp.pages.Notice(w, "repo-notice", "Failed to update description, try again later.") 598 return 599 } 600 defer tx.Rollback() 601 602 err = db.PutComment(tx, &newComment) 603 if err != nil { 604 l.Error("failed to perferom update-description query", "err", err) 605 rp.pages.Notice(w, "repo-notice", "Failed to update description, try again later.") 606 return 607 } 608 tx.Commit() 609 610 // rkey is optional, it was introduced later 611 if newComment.Rkey != "" { 612 // update the record on pds 613 ex, err := comatproto.RepoGetRecord(r.Context(), client, "", tangled.CommentNSID, user.Did, comment.Rkey) 614 if err != nil { 615 l.Error("failed to get record", "err", err, "did", newComment.Did, "rkey", newComment.Rkey) 616 rp.pages.Notice(w, fmt.Sprintf("comment-%s-status", commentId), "Failed to update description, no record found on PDS.") 617 return 618 } 619 620 _, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{ 621 Collection: tangled.CommentNSID, 622 Repo: user.Did, 623 Rkey: newComment.Rkey, 624 SwapRecord: ex.Cid, 625 Record: &lexutil.LexiconTypeDecoder{ 626 Val: &record, 627 }, 628 }) 629 if err != nil { 630 l.Error("failed to update record on PDS", "err", err) 631 } 632 } 633 634 // return new comment body with htmx 635 rp.pages.IssueCommentBodyFragment(w, pages.IssueCommentBodyParams{ 636 LoggedInUser: user, 637 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 638 Issue: issue, 639 Comment: &newComment, 640 }) 641 } 642} 643 644func (rp *Issues) ReplyIssueCommentPlaceholder(w http.ResponseWriter, r *http.Request) { 645 l := rp.logger.With("handler", "ReplyIssueCommentPlaceholder") 646 user := rp.oauth.GetUser(r) 647 648 issue, ok := r.Context().Value("issue").(*models.Issue) 649 if !ok { 650 l.Error("failed to get issue") 651 rp.pages.Error404(w) 652 return 653 } 654 655 commentId := chi.URLParam(r, "commentId") 656 comments, err := db.GetComments( 657 rp.db, 658 orm.FilterEq("id", commentId), 659 ) 660 if err != nil { 661 l.Error("failed to fetch comment", "id", commentId) 662 http.Error(w, "failed to fetch comment id", http.StatusBadRequest) 663 return 664 } 665 if len(comments) != 1 { 666 l.Error("incorrect number of comments returned", "id", commentId, "len(comments)", len(comments)) 667 http.Error(w, "invalid comment id", http.StatusBadRequest) 668 return 669 } 670 comment := comments[0] 671 672 rp.pages.ReplyIssueCommentPlaceholderFragment(w, pages.ReplyIssueCommentPlaceholderParams{ 673 LoggedInUser: user, 674 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 675 Issue: issue, 676 Comment: &comment, 677 }) 678} 679 680func (rp *Issues) ReplyIssueComment(w http.ResponseWriter, r *http.Request) { 681 l := rp.logger.With("handler", "ReplyIssueComment") 682 user := rp.oauth.GetUser(r) 683 684 issue, ok := r.Context().Value("issue").(*models.Issue) 685 if !ok { 686 l.Error("failed to get issue") 687 rp.pages.Error404(w) 688 return 689 } 690 691 commentId := chi.URLParam(r, "commentId") 692 comments, err := db.GetComments( 693 rp.db, 694 orm.FilterEq("id", commentId), 695 ) 696 if err != nil { 697 l.Error("failed to fetch comment", "id", commentId) 698 http.Error(w, "failed to fetch comment id", http.StatusBadRequest) 699 return 700 } 701 if len(comments) != 1 { 702 l.Error("incorrect number of comments returned", "id", commentId, "len(comments)", len(comments)) 703 http.Error(w, "invalid comment id", http.StatusBadRequest) 704 return 705 } 706 comment := comments[0] 707 708 rp.pages.ReplyIssueCommentFragment(w, pages.ReplyIssueCommentParams{ 709 LoggedInUser: user, 710 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 711 Issue: issue, 712 Comment: &comment, 713 }) 714} 715 716func (rp *Issues) DeleteIssueComment(w http.ResponseWriter, r *http.Request) { 717 l := rp.logger.With("handler", "DeleteIssueComment") 718 user := rp.oauth.GetUser(r) 719 720 issue, ok := r.Context().Value("issue").(*models.Issue) 721 if !ok { 722 l.Error("failed to get issue") 723 rp.pages.Error404(w) 724 return 725 } 726 727 commentId := chi.URLParam(r, "commentId") 728 comments, err := db.GetComments( 729 rp.db, 730 orm.FilterEq("id", commentId), 731 ) 732 if err != nil { 733 l.Error("failed to fetch comment", "id", commentId) 734 http.Error(w, "failed to fetch comment id", http.StatusBadRequest) 735 return 736 } 737 if len(comments) != 1 { 738 l.Error("incorrect number of comments returned", "id", commentId, "len(comments)", len(comments)) 739 http.Error(w, "invalid comment id", http.StatusBadRequest) 740 return 741 } 742 comment := comments[0] 743 744 if comment.Did.String() != user.Did { 745 l.Error("unauthorized action", "expectedDid", comment.Did, "gotDid", user.Did) 746 http.Error(w, "you are not the author of this comment", http.StatusUnauthorized) 747 return 748 } 749 750 if comment.Deleted != nil { 751 http.Error(w, "comment already deleted", http.StatusBadRequest) 752 return 753 } 754 755 // optimistic deletion 756 deleted := time.Now() 757 err = db.DeleteComments(rp.db, orm.FilterEq("id", comment.Id)) 758 if err != nil { 759 l.Error("failed to delete comment", "err", err) 760 rp.pages.Notice(w, fmt.Sprintf("comment-%s-status", commentId), "failed to delete comment") 761 return 762 } 763 764 // delete from pds 765 if comment.Rkey != "" { 766 client, err := rp.oauth.AuthorizedClient(r) 767 if err != nil { 768 l.Error("failed to get authorized client", "err", err) 769 rp.pages.Notice(w, "issue-comment", "Failed to delete comment.") 770 return 771 } 772 _, err = comatproto.RepoDeleteRecord(r.Context(), client, &comatproto.RepoDeleteRecord_Input{ 773 Collection: tangled.CommentNSID, 774 Repo: user.Did, 775 Rkey: comment.Rkey, 776 }) 777 if err != nil { 778 l.Error("failed to delete from PDS", "err", err) 779 } 780 } 781 782 // optimistic update for htmx 783 comment.Body = "" 784 comment.Deleted = &deleted 785 786 // htmx fragment of comment after deletion 787 rp.pages.IssueCommentBodyFragment(w, pages.IssueCommentBodyParams{ 788 LoggedInUser: user, 789 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 790 Issue: issue, 791 Comment: &comment, 792 }) 793} 794 795func (rp *Issues) RepoIssues(w http.ResponseWriter, r *http.Request) { 796 l := rp.logger.With("handler", "RepoIssues") 797 798 params := r.URL.Query() 799 state := params.Get("state") 800 isOpen := true 801 switch state { 802 case "open": 803 isOpen = true 804 case "closed": 805 isOpen = false 806 default: 807 isOpen = true 808 } 809 810 page := pagination.FromContext(r.Context()) 811 812 user := rp.oauth.GetUser(r) 813 f, err := rp.repoResolver.Resolve(r) 814 if err != nil { 815 l.Error("failed to get repo and knot", "err", err) 816 return 817 } 818 819 totalIssues := 0 820 if isOpen { 821 totalIssues = f.RepoStats.IssueCount.Open 822 } else { 823 totalIssues = f.RepoStats.IssueCount.Closed 824 } 825 826 keyword := params.Get("q") 827 828 var issues []models.Issue 829 searchOpts := models.IssueSearchOptions{ 830 Keyword: keyword, 831 RepoAt: f.RepoAt().String(), 832 IsOpen: isOpen, 833 Page: page, 834 } 835 if keyword != "" { 836 res, err := rp.indexer.Search(r.Context(), searchOpts) 837 if err != nil { 838 l.Error("failed to search for issues", "err", err) 839 return 840 } 841 l.Debug("searched issues with indexer", "count", len(res.Hits)) 842 totalIssues = int(res.Total) 843 844 issues, err = db.GetIssues( 845 rp.db, 846 orm.FilterIn("id", res.Hits), 847 ) 848 if err != nil { 849 l.Error("failed to get issues", "err", err) 850 rp.pages.Notice(w, "issues", "Failed to load issues. Try again later.") 851 return 852 } 853 854 } else { 855 openInt := 0 856 if isOpen { 857 openInt = 1 858 } 859 issues, err = db.GetIssuesPaginated( 860 rp.db, 861 page, 862 orm.FilterEq("repo_at", f.RepoAt()), 863 orm.FilterEq("open", openInt), 864 ) 865 if err != nil { 866 l.Error("failed to get issues", "err", err) 867 rp.pages.Notice(w, "issues", "Failed to load issues. Try again later.") 868 return 869 } 870 } 871 872 labelDefs, err := db.GetLabelDefinitions( 873 rp.db, 874 orm.FilterIn("at_uri", f.Labels), 875 orm.FilterContains("scope", tangled.RepoIssueNSID), 876 ) 877 if err != nil { 878 l.Error("failed to fetch labels", "err", err) 879 rp.pages.Error503(w) 880 return 881 } 882 883 defs := make(map[string]*models.LabelDefinition) 884 for _, l := range labelDefs { 885 defs[l.AtUri().String()] = &l 886 } 887 888 rp.pages.RepoIssues(w, pages.RepoIssuesParams{ 889 LoggedInUser: rp.oauth.GetUser(r), 890 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 891 Issues: issues, 892 IssueCount: totalIssues, 893 LabelDefs: defs, 894 FilteringByOpen: isOpen, 895 FilterQuery: keyword, 896 Page: page, 897 }) 898} 899 900func (rp *Issues) NewIssue(w http.ResponseWriter, r *http.Request) { 901 l := rp.logger.With("handler", "NewIssue") 902 user := rp.oauth.GetUser(r) 903 904 f, err := rp.repoResolver.Resolve(r) 905 if err != nil { 906 l.Error("failed to get repo and knot", "err", err) 907 return 908 } 909 910 switch r.Method { 911 case http.MethodGet: 912 rp.pages.RepoNewIssue(w, pages.RepoNewIssueParams{ 913 LoggedInUser: user, 914 RepoInfo: rp.repoResolver.GetRepoInfo(r, user), 915 }) 916 case http.MethodPost: 917 body := r.FormValue("body") 918 mentions, references := rp.mentionsResolver.Resolve(r.Context(), body) 919 920 issue := &models.Issue{ 921 RepoAt: f.RepoAt(), 922 Rkey: tid.TID(), 923 Title: r.FormValue("title"), 924 Body: body, 925 Open: true, 926 Did: user.Did, 927 Created: time.Now(), 928 Mentions: mentions, 929 References: references, 930 Repo: f, 931 } 932 933 if err := rp.validator.ValidateIssue(issue); err != nil { 934 l.Error("validation error", "err", err) 935 rp.pages.Notice(w, "issues", fmt.Sprintf("Failed to create issue: %s", err)) 936 return 937 } 938 939 record := issue.AsRecord() 940 941 // create an atproto record 942 client, err := rp.oauth.AuthorizedClient(r) 943 if err != nil { 944 l.Error("failed to get authorized client", "err", err) 945 rp.pages.Notice(w, "issues", "Failed to create issue.") 946 return 947 } 948 resp, err := comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{ 949 Collection: tangled.RepoIssueNSID, 950 Repo: user.Did, 951 Rkey: issue.Rkey, 952 Record: &lexutil.LexiconTypeDecoder{ 953 Val: &record, 954 }, 955 }) 956 if err != nil { 957 l.Error("failed to create issue", "err", err) 958 rp.pages.Notice(w, "issues", "Failed to create issue.") 959 return 960 } 961 atUri := resp.Uri 962 963 tx, err := rp.db.BeginTx(r.Context(), nil) 964 if err != nil { 965 rp.pages.Notice(w, "issues", "Failed to create issue, try again later") 966 return 967 } 968 rollback := func() { 969 err1 := tx.Rollback() 970 err2 := rollbackRecord(context.Background(), atUri, client) 971 972 if errors.Is(err1, sql.ErrTxDone) { 973 err1 = nil 974 } 975 976 if err := errors.Join(err1, err2); err != nil { 977 l.Error("failed to rollback txn", "err", err) 978 } 979 } 980 defer rollback() 981 982 err = db.PutIssue(tx, issue) 983 if err != nil { 984 l.Error("failed to create issue", "err", err) 985 rp.pages.Notice(w, "issues", "Failed to create issue.") 986 return 987 } 988 989 if err = tx.Commit(); err != nil { 990 l.Error("failed to create issue", "err", err) 991 rp.pages.Notice(w, "issues", "Failed to create issue.") 992 return 993 } 994 995 // everything is successful, do not rollback the atproto record 996 atUri = "" 997 998 rp.notifier.NewIssue(r.Context(), issue, mentions) 999 1000 ownerSlashRepo := reporesolver.GetBaseRepoPath(r, f) 1001 rp.pages.HxLocation(w, fmt.Sprintf("/%s/issues/%d", ownerSlashRepo, issue.IssueId)) 1002 return 1003 } 1004} 1005 1006// this is used to rollback changes made to the PDS 1007// 1008// it is a no-op if the provided ATURI is empty 1009func rollbackRecord(ctx context.Context, aturi string, client *atpclient.APIClient) error { 1010 if aturi == "" { 1011 return nil 1012 } 1013 1014 parsed := syntax.ATURI(aturi) 1015 1016 collection := parsed.Collection().String() 1017 repo := parsed.Authority().String() 1018 rkey := parsed.RecordKey().String() 1019 1020 _, err := comatproto.RepoDeleteRecord(ctx, client, &comatproto.RepoDeleteRecord_Input{ 1021 Collection: collection, 1022 Repo: repo, 1023 Rkey: rkey, 1024 }) 1025 return err 1026}