Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 | 16x 16x 16x 16x 16x 16x 16x 16x 16x 3x 3x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x | import { Types } from 'mongoose' import Crowi from 'server/crowi' import Debug from 'debug' import ApiResponse from '../util/apiResponse' import { decodeSpace } from '../util/path' import { BookmarkDocument } from 'server/models/bookmark' import { PageDocument } from 'server/models/page' import { RevisionDocument } from 'server/models/revision' import { UserDocument } from 'server/models/user' interface PagerOptions { offset: number | string limit: number | string length?: number } export default (crowi: Crowi) => { const debug = Debug('crowi:routes:page') const Page = crowi.model('Page') const User = crowi.model('User') const Bookmark = crowi.model('Bookmark') const Watcher = crowi.model('Watcher') const actions = {} as any const api = (actions.api = {} as any) // register page events const pageEvent = crowi.event('Page') pageEvent.on('update', function(page, user) { const io = crowi.getIo() Iif (io) { io.sockets.emit('page edited', { page, user }) } }) function getPathFromRequest(req) { let path path = '/' + (req.params[0] || '') path = decodeSpace(path) path = path.replace(/\.md$/, '') return path } // TODO: total とかでちゃんと計算する function generatePager(options: PagerOptions) { let next: number | null = null let prev: number | null = null const offset = parseInt(String(options.offset), 10) const limit = parseInt(String(options.limit), 10) const length = options.length || 0 if (offset > 0) { prev = offset - limit if (prev < 0) { prev = 0 } } if (length < limit) { next = null } else { next = offset + limit } return { prev: prev, next: next, offset: offset, } } // routing actions.pageListShow = async function(req, res) { const limit = 50 const offset = parseInt(req.query.offset) || 0 const SEENER_THRESHOLD = 10 let path = getPathFromRequest(req) path = path + (path == '/' ? '' : '/') debug('Page list show', path) const pagerOptions: PagerOptions = { offset, limit } const queryOptions = { offset, limit: limit + 1 } try { const [portalPage, pageList] = await Promise.all([ Page.findPortalPage(path, req.user, req.query.revision), Page.findListByStartWith(path, req.user, queryOptions), ]) if (pageList.length > limit) { pageList.pop() } if (portalPage) { crowi.lru.add(req.user._id.toString(), portalPage._id.toString()) } pagerOptions.length = pageList.length res.render('page_list', { path, page: portalPage || null, pages: pageList, pager: generatePager(pagerOptions), viewConfig: { seener_threshold: SEENER_THRESHOLD, }, }) } catch (err) { debug('Error on rendering pageListShow', err) } } actions.deletedPageListShow = function(req, res) { var path = '/trash' + getPathFromRequest(req) var limit = 50 var offset = parseInt(req.query.offset) || 0 // index page const pagerOptions: PagerOptions = { offset, limit } const queryOptions = { offset, limit: limit + 1, includeDeletedPage: true, } const renderVars: any = { page: null, path, pages: [], } Page.findListByStartWith(path, req.user, queryOptions) .then(function(pageList) { if (pageList.length > limit) { pageList.pop() } pagerOptions.length = pageList.length renderVars.pager = generatePager(pagerOptions) renderVars.pages = pageList res.render('page_list', renderVars) }) .catch(function(err) { debug('Error on rendering deletedPageListShow', err) }) } async function renderPage(pageData, req, res) { // create page if (!pageData) { return res.render('page', { author: {}, page: false, }) } crowi.lru.add(req.user._id.toString(), pageData._id.toString()) if (pageData.redirectTo) { return res.redirect(encodeURI(pageData.redirectTo + '?redirectFrom=' + pageData.path)) } const renderVars = { path: pageData.path, page: pageData, revision: pageData.revision || {}, author: pageData.revision.author || false, } const defaultPageTeamplate = 'page' res.render(req.query.presentation ? 'page_presentation' : defaultPageTeamplate, renderVars) } actions.userPageShow = async function(req, res) { const username = req.params.username const path = `/user/${username}` res.locals.path = path debug('path', path) // check page existance let pageData try { pageData = await Page.findPage(path, req.user, req.query.revision) crowi.lru.add(req.user._id.toString(), pageData._id.toString()) if (pageData.redirectTo) { return res.redirect(encodeURI(pageData.redirectTo + '?redirectFrom=' + pageData.path)) } } catch (e) { // for B.C.: Old Crowi has no user page return renderPage(null, req, res) // show create } let pageUser: UserDocument | {} | null = {} let bookmarkList: BookmarkDocument[] = [] let createdList = [] try { // user いない場合 pageUser = await User.findUserByUsername(username) ;[bookmarkList, createdList] = await Promise.all([ Bookmark.findByUser(pageUser, { limit: 10, populatePage: true, requestUser: req.user }), Page.findListByCreator(pageUser, { limit: 10 }, req.user), ]) } catch (e) { debug('Error while loading user page.', username) } return res.render('user_page', { username, bookmarkList, createdList, pageUser, path: pageData.path, page: pageData, revision: pageData.revision || {}, author: pageData.revision.author || false, }) } actions.pageShow = async function(req, res) { const path = getPathFromRequest(req) // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ var isMarkdown = req.params[0].match(/.+\.md$/) || false res.locals.path = path try { const page = (await Page.findPage(path, req.user, req.query.revision)) as PageDocument debug('Page found', page._id, page.path) if (isMarkdown) { res.set('Content-Type', 'text/plain') return res.send(((page.revision as any) as RevisionDocument).body) } return renderPage(page, req, res) } catch (err) { const normalizedPath = Page.normalizePath(path) if (normalizedPath !== path) { return res.redirect(normalizedPath) } // pageShow は /* にマッチしてる最後の砦なので、creatableName でない routing は // これ以前に定義されているはずなので、こうしてしまって問題ない。 if (!Page.isCreatableName(path)) { // 削除済みページの場合 /trash 以下に移動しているので creatableName になっていないので、表示を許可 debug('Page is not creatable name.', path) res.redirect('/') return } if (req.query.revision) { return res.redirect(encodeURI(path)) } if (isMarkdown) { return res.redirect('/') } try { const portalPage = await Page.hasPortalPage(path + '/', req.user) if (portalPage) { return res.redirect(encodeURI(path) + '/') } else { const fixed = Page.fixToCreatableName(path) if (fixed !== path) { debug('fixed page name', fixed) res.redirect(encodeURI(fixed)) return } debug('There no page for', `${path}`) return renderPage(null, req, res) } } catch (err) { debug('Error on rendering pageShow (redirect to portal)', err) } } } actions.pageEdit = function(req, res) { var pageForm = req.body.pageForm var body = pageForm.body var currentRevision = pageForm.currentRevision var grant = pageForm.grant var path = pageForm.path // TODO: make it pluggable var notify = pageForm.notify || {} debug('notify: ', notify) var redirectPath = encodeURI(path) var pageData: PageDocument | null | {} = {} var updateOrCreate var previousRevision: Types.ObjectId | null | false = false // set to render res.locals.pageForm = pageForm // 削除済みページはここで編集不可判定される if (!Page.isCreatableName(path)) { res.redirect(redirectPath) return } var ignoreNotFound = true Page.findPage(path, req.user, null, ignoreNotFound) .then(function(data) { pageData = data if (!req.form.isValid) { debug('Form data not valid') throw new Error('Form data not valid.') } if (data && !data.isUpdatable(currentRevision)) { debug('Conflict occured') req.form.errors.push('page_edit.notice.conflict') throw new Error('Conflict.') } if (data) { previousRevision = data.revision return Page.updatePage(data, body, req.user, { grant: grant }) } else { // new page updateOrCreate = 'create' return Page.createPage(path, body, req.user, { grant: grant }) } }) .then(function(data) { // data is a saved page data. pageData = data if (!data) { throw new Error('Data not found') } // TODO: move to events if (notify.slack) { if (notify.slack.on && notify.slack.channel) { data .updateSlackChannel(notify.slack.channel) .then(function() {}) .catch(function() {}) if (crowi.slack) { notify.slack.channel.split(',').map(function(chan) { var message = crowi.slack.prepareSlackMessage(pageData, req.user, chan, updateOrCreate, previousRevision) crowi.slack .post(message.channel, message.text, message) .then(function() {}) .catch(function() {}) }) } } } return res.redirect(redirectPath) }) .catch(function(err) { debug('Page create or edit error.', err) if (pageData && !req.form.isValid) { return renderPage(pageData, req, res) } return res.redirect(redirectPath) }) } // app.get( '/users/:username([^/]+)/bookmarks' , loginRequired(crowi, app) , page.userBookmarkList); actions.userBookmarkList = function(req, res) { var username = req.params.username var limit = 50 var offset = parseInt(req.query.offset) || 0 var renderVars: any = {} var pagerOptions: PagerOptions = { offset, limit } var queryOptions = { offset, limit: limit + 1, populatePage: true, requestUser: req.user } User.findUserByUsername(username) .then(function(user) { if (user === null) { throw new Error('The user not found.') } renderVars.pageUser = user return Bookmark.findByUser(user, queryOptions) }) .then(function(bookmarks) { if (bookmarks.length > limit) { bookmarks.pop() } pagerOptions.length = bookmarks.length renderVars.pager = generatePager(pagerOptions) renderVars.bookmarks = bookmarks return res.render('user/bookmarks', renderVars) }) .catch(function(err) { debug('Error on rendereing bookmark', err) res.redirect('/') }) } // app.get( '/users/:username([^/]+)/recent-create' , loginRequired(crowi, app) , page.userRecentCreatedList); actions.userRecentCreatedList = function(req, res) { var username = req.params.username var limit = 50 var offset = parseInt(req.query.offset) || 0 var renderVars: any = {} var pagerOptions: PagerOptions = { offset, limit } var queryOptions = { offset, limit: limit + 1 } User.findUserByUsername(username) .then(function(user) { if (user === null) { throw new Error('The user not found.') } renderVars.pageUser = user return Page.findListByCreator(user, queryOptions, req.user) }) .then(function(pages) { if (pages.length > limit) { pages.pop() } pagerOptions.length = pages.length renderVars.pager = generatePager(pagerOptions) renderVars.pages = pages return res.render('user/recent-create', renderVars) }) .catch(function(err) { debug('Error on rendereing recent-created', err) res.redirect('/') }) } /** * redirector */ api.redirector = function(req, res) { var id = req.params.id Page.findPageById(id) .then(function(pageData) { const isGranted = pageData.isGrantedFor(req.user) if (pageData.grant == Page.GRANT_RESTRICTED && !isGranted) { return Page.pushToGrantedUsers(pageData, req.user) } if (!isGranted) { throw new Error('Page is not granted for the user.') } return Promise.resolve(pageData) }) .then(function(page) { return res.redirect(encodeURI(page.path)) }) .catch(function(err) { return res.redirect('/') }) } /** * @api {get} /pages.list List pages by user * @apiName ListPage * @apiGroup Page * * @apiParam {String} path * @apiParam {String} user */ api.list = function(req, res) { var username = req.query.user || null var path = req.query.path || null var limit = 50 var offset = parseInt(req.query.offset) || 0 var pagerOptions: PagerOptions = { offset, limit } var queryOptions = { offset, limit: limit + 1 } // Accepts only one of these if (username === null && path === null) { return res.json(ApiResponse.error('Parameter user or path is required.')) } if (username !== null && path !== null) { return res.json(ApiResponse.error('Parameter user or path is required.')) } var pageFetcher if (path === null) { pageFetcher = User.findUserByUsername(username).then(function(user) { if (user === null) { throw new Error('The user not found.') } return Page.findListByCreator(user, queryOptions, req.user) }) } else { pageFetcher = Page.findListByStartWith(path, req.user, queryOptions) } pageFetcher .then(function(pages) { if (pages.length > limit) { pages.pop() } pagerOptions.length = pages.length const result = { pages } return res.json(ApiResponse.success(result)) }) .catch(function(err) { return res.json(ApiResponse.error(err)) }) } /** * @api {post} /pages.create Create new page * @apiName CreatePage * @apiGroup Page * * @apiParam {String} body * @apiParam {String} path * @apiParam {String} grant */ api.create = function(req, res) { var body = req.body.body || null var pagePath = req.body.path || null var grant = req.body.grant || null if (body === null || pagePath === null) { return res.json(ApiResponse.error('Parameters body and path are required.')) } var ignoreNotFound = true Page.findPage(pagePath, req.user, null, ignoreNotFound) .then(function(data) { if (data !== null) { throw new Error('Page exists') } return Page.createPage(pagePath, body, req.user, { grant: grant }) }) .then(function(data) { if (!data) { throw new Error('Failed to create page.') } var result = { page: data.toObject() } return res.json(ApiResponse.success(result)) }) .catch(function(err) { return res.json(ApiResponse.error(err)) }) } /** * @api {post} /pages.update Update page * @apiName UpdatePage * @apiGroup Page * * @apiParam {String} body * @apiParam {String} page_id * @apiParam {String} revision_id * @apiParam {String} grant * * In the case of the page exists: * - If revision_id is specified => update the page, * - If revision_id is not specified => force update by the new contents. */ api.update = function(req, res) { var pageBody = req.body.body || null var pageId = req.body.page_id || null var revisionId = req.body.revision_id || null var grant = req.body.grant || null if (pageId === null || pageBody === null) { return res.json(ApiResponse.error('page_id and body are required.')) } Page.findPageByIdAndGrantedUser(pageId, req.user) .then(function(pageData) { if (pageData && revisionId !== null && !pageData.isUpdatable(revisionId)) { throw new Error('Revision error.') } var grantOption = { grant: pageData.grant } if (grant !== null) { grantOption.grant = grant } return Page.updatePage(pageData, pageBody, req.user, grantOption) }) .then(function(pageData) { var result = { page: pageData.toObject(), } return res.json(ApiResponse.success(result)) }) .catch(function(err) { debug('error on _api/pages.update', err) return res.json(ApiResponse.error(err)) }) } /** * @api {get} /pages.get Get page data * @apiName GetPage * @apiGroup Page * * @apiParam {String} page_id * @apiParam {String} path * @apiParam {String} revision_id */ api.get = function(req, res) { const pagePath = req.query.path || null const pageId = req.query.page_id || null // TODO: handling const revisionId = req.query.revision_id || null if (!pageId && !pagePath) { return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.'))) } let pageFinder if (pageId) { // prioritized pageFinder = Page.findPageByIdAndGrantedUser(pageId, req.user) } else if (pagePath) { pageFinder = Page.findPage(pagePath, req.user, revisionId) } pageFinder .then(function(page) { const result = { page } return res.json(ApiResponse.success(result)) }) .catch(function(err) { return res.json(ApiResponse.error(err)) }) } /** * @api {post} /pages.seen Mark as seen user * @apiName SeenPage * @apiGroup Page * * @apiParam {String} page_id Page Id. */ api.seen = function(req, res) { var pageId = req.body.page_id if (!pageId) { return res.json(ApiResponse.error('page_id required')) } Page.findPageByIdAndGrantedUser(pageId, req.user) .then(function(page) { return page.seen(req.user) }) .then(function(seenUser) { const result = { seenUser } return res.json(ApiResponse.success(result)) }) .catch(function(err) { debug('Seen user update error', err) return res.json(ApiResponse.error(err)) }) } /** * @api {post} /likes.add Like page * @apiName LikePage * @apiGroup Page * * @apiParam {String} page_id Page Id. */ api.like = function(req, res) { var id = req.body.page_id Page.findPageByIdAndGrantedUser(id, req.user) .then(function(pageData) { return pageData.like(req.user) }) .then(function(data) { var result = { page: data } return res.json(ApiResponse.success(result)) }) .catch(function(err) { debug('Like failed', err) return res.json(ApiResponse.error({})) }) } /** * @api {post} /likes.remove Unlike page * @apiName UnlikePage * @apiGroup Page * * @apiParam {String} page_id Page Id. */ api.unlike = function(req, res) { var id = req.body.page_id Page.findPageByIdAndGrantedUser(id, req.user) .then(function(pageData) { return pageData.unlike(req.user) }) .then(function(data) { var result = { page: data } return res.json(ApiResponse.success(result)) }) .catch(function(err) { debug('Unlike failed', err) return res.json(ApiResponse.error({})) }) } /** * @api {get} /pages.updatePost * @apiName Get UpdatePost setting list * @apiGroup Page * * @apiParam {String} path */ api.getUpdatePost = function(req, res) { var path = req.query.path var UpdatePost = crowi.model('UpdatePost') if (!path) { return res.json(ApiResponse.error({})) } UpdatePost.findSettingsByPath(path) .then(function(data) { data = data.map(function(e) { return e.channel }) debug('Found updatePost data', data) var result = { updatePost: data } return res.json(ApiResponse.success(result)) }) .catch(function(err) { debug('Error occured while get setting', err) return res.json(ApiResponse.error({})) }) } /** * @api {post} /pages.remove Remove page * @apiName RemovePage * @apiGroup Page * * @apiParam {String} page_id Page Id. * @apiParam {String} revision_id */ api.remove = function(req, res) { var pageId = req.body.page_id var previousRevision = req.body.revision_id || null // get completely flag const isCompletely = req.body.completely !== undefined Page.findPageByIdAndGrantedUser(pageId, req.user) .then(function(pageData) { debug('Delete page', pageData._id, pageData.path) if (isCompletely) { return Page.completelyDeletePage(pageData, req.user) } // else if (!pageData.isUpdatable(previousRevision)) { throw new Error("Someone could update this page, so couldn't delete.") } return Page.deletePage(pageData, req.user) }) .then(function(page) { debug('Page deleted', page.path) const result = { page } return res.json(ApiResponse.success(result)) }) .catch(function(err) { debug('Error occured while get setting', err, err.stack) return res.json(ApiResponse.error('Failed to delete page.')) }) } /** * @api {post} /pages.revertRemove Revert removed page * @apiName RevertRemovePage * @apiGroup Page * * @apiParam {String} page_id Page Id. */ api.revertRemove = function(req, res) { var pageId = req.body.page_id Page.findPageByIdAndGrantedUser(pageId, req.user) .then(function(pageData) { // TODO: これでいいんだっけ return Page.revertDeletedPage(pageData, req.user) }) .then(function(page) { debug('Complete to revert deleted page', page.path) const result = { page } return res.json(ApiResponse.success(result)) }) .catch(function(err) { debug('Error occured while get setting', err, err.stack) return res.json(ApiResponse.error('Failed to revert deleted page.')) }) } /** * @api {post} /pages.rename Rename page * @apiName RenamePage * @apiGroup Page * * @apiParam {String} page_id Page Id. * @apiParam {String} path * @apiParam {String} revision_id * @apiParam {String} new_path * @apiParam {Bool} create_redirect */ api.rename = async function(req, res) { const { page_id: pageId, revision_id: previousRevision = null, new_path: newPath, create_redirect: createRedirect, move_trees: moveTrees } = req.body const newPagePath = Page.normalizePath(newPath) const newPageIsPortal = newPagePath.endsWith('/') const options = { createRedirectPage: (!newPageIsPortal && createRedirect) || 0, moveUnderTrees: moveTrees || 0, } if (!Page.isCreatableName(newPagePath)) { return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})`)) } const rename = async function() { try { const page = await Page.findPageById(pageId) if (!page.isUpdatable(previousRevision)) { return res.json(ApiResponse.error(new Error("Someone could update this page, so couldn't delete."))) } await Page.rename(page, newPagePath, req.user, options) const result = { page } return res.json(ApiResponse.success(result)) } catch (err) { return res.json(ApiResponse.error('Failed to update page.')) } } try { const page = await Page.findPageByPath(newPagePath) if (page.isUnlinkable(req.user)) { try { await page.unlink(req.user) rename() } catch (err) { res.json(ApiResponse.error(err)) } } else { // can't rename to that path when page found and can't remove it return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`)) } } catch (err) { rename() } } api.renameTree = async function(req, res) { const { path, new_path: newPath, create_redirect: createRedirect = 0 } = req.body const options = { createRedirectPage: createRedirect } const paths = await Page.findChildrenByPath(path, req.user, {}) const pathMap = Page.getPathMap(paths, path, newPath) const [error, errors] = await Page.checkPagesRenamable(Object.values(pathMap), req.user) if (error) { const info = { errors, path_map: pathMap } return res.json(ApiResponse.error('rename_tree.error.can_not_move', info)) } try { const result = await Page.renameTree(pathMap, req.user, options) return res.json(ApiResponse.success({ pages: result })) } catch (err) { return res.json(ApiResponse.error(err)) } } api.checkTreeRenamable = async function(req, res) { const { path, new_path: newPath } = req.body const paths = await Page.findChildrenByPath(path, req.user, {}) const pathMap = Page.getPathMap(paths, path, newPath) const [error, errors] = await Page.checkPagesRenamable(Object.values(pathMap), req.user) if (error) { const info = { errors, path_map: pathMap } return res.json(ApiResponse.error('rename_tree.error.can_not_move', info)) } return res.json(ApiResponse.success({ path_map: pathMap })) } /** * @api {post} /pages.unlink Remove the redirecting page * @apiName UnlinkPage * @apiGroup Page * * @apiParam {String} page_id Page Id. * @apiParam {String} revision_id */ api.unlink = async function(req, res) { const { page_id: pageId } = req.body try { const page = await Page.findPageByIdAndGrantedUser(pageId, req.user) debug('Unlink page', page._id, page.path) await Page.removeRedirectOriginPageByPath(page.path) debug('Redirect Page deleted', page.path) const result = { page } return res.json(ApiResponse.success(result)) } catch (err) { debug('Error occured while get setting', err, err.stack) return res.json(ApiResponse.error('Failed to delete redirect page.')) } } api.watchStatus = async function(req, res) { const { page_id: pageId } = req.query const { _id: userId } = req.user try { const watcher = await Watcher.findByUserIdAndTargetId(userId, pageId) const getDefaultStatus = async () => { const page = await Page.findById(pageId) if (!page) throw new Error('Page not found') const targetUsers = await page.getNotificationTargetUsers() return targetUsers.some(user => user.toString() === userId.toString()) } const watching = watcher ? watcher.isWatching() : await getDefaultStatus() const result = { watching } return res.json(ApiResponse.success(result)) } catch (err) { debug('Error occured while get setting', err, err.stack) return res.json(ApiResponse.error('Failed to fetch watch status.')) } } api.watch = async function(req, res) { const { page_id: pageId } = req.body const { _id: userId } = req.user const status = req.body.status ? Watcher.STATUS_WATCH : Watcher.STATUS_IGNORE try { const watcher = await Watcher.watchByPageId(userId, pageId, status) const result = { watcher } return res.json(ApiResponse.success(result)) } catch (err) { debug('Error occured while update watch status', err, err.stack) return res.json(ApiResponse.error('Failed to watch this page.')) } } return actions } |