| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283 |
- module.exports = function(crowi, app) {
- 'use strict';
- const debug = require('debug')('growi:routes:page')
- , logger = require('@alias/logger')('growi:routes:page')
- , Page = crowi.model('Page')
- , User = crowi.model('User')
- , Config = crowi.model('Config')
- , config = crowi.getConfig()
- , Revision = crowi.model('Revision')
- , Bookmark = crowi.model('Bookmark')
- , PageGroupRelation = crowi.model('PageGroupRelation')
- , UpdatePost = crowi.model('UpdatePost')
- , ApiResponse = require('../util/apiResponse')
- , interceptorManager = crowi.getInterceptorManager()
- , pagePathUtil = require('../util/pagePathUtil')
- , swig = require('swig-templates')
- , getToday = require('../util/getToday')
- , globalNotificationService = crowi.getGlobalNotificationService()
- , actions = {};
- // register page events
- var pageEvent = crowi.event('page');
- pageEvent.on('update', function(page, user) {
- crowi.getIo().sockets.emit('page edited', {page, user});
- });
- function getPathFromRequest(req) {
- var path = '/' + (req.params[0] || '');
- return path.replace(/\.md$/, '');
- }
- function isUserPage(path) {
- if (path.match(/^\/user\/[^\/]+\/?$/)) {
- return true;
- }
- return false;
- }
- // TODO: total とかでちゃんと計算する
- function generatePager(options) {
- var next = null,
- prev = null,
- offset = parseInt(options.offset, 10),
- limit = parseInt(options.limit, 10),
- 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,
- };
- }
- /**
- * switch action by behaviorType
- */
- actions.pageListShowWrapper = function(req, res) {
- const behaviorType = Config.behaviorType(config);
- if (!behaviorType || 'crowi' === behaviorType) {
- return actions.pageListShow(req, res);
- }
- else {
- return actions.pageListShowForCrowiPlus(req, res);
- }
- };
- /**
- * switch action by behaviorType
- */
- actions.pageShowWrapper = function(req, res) {
- const behaviorType = Config.behaviorType(config);
- if (!behaviorType || 'crowi' === behaviorType) {
- return actions.pageShow(req, res);
- }
- else {
- return actions.pageShowForCrowiPlus(req, res);
- }
- };
- /**
- * switch action by behaviorType
- */
- actions.trashPageListShowWrapper = function(req, res) {
- const behaviorType = Config.behaviorType(config);
- if (!behaviorType || 'crowi' === behaviorType) {
- // Crowi behavior for '/trash/*'
- return actions.deletedPageListShow(req, res);
- }
- else {
- // redirect to '/trash'
- return res.redirect('/trash');
- }
- };
- /**
- * switch action by behaviorType
- */
- actions.trashPageShowWrapper = function(req, res) {
- const behaviorType = Config.behaviorType(config);
- if (!behaviorType || 'crowi' === behaviorType) {
- // redirect to '/trash/'
- return res.redirect('/trash/');
- }
- else {
- // Crowi behavior for '/trash/*'
- return actions.deletedPageListShow(req, res);
- }
- };
- /**
- * switch action by behaviorType
- */
- actions.deletedPageListShowWrapper = function(req, res) {
- const behaviorType = Config.behaviorType(config);
- if (!behaviorType || 'crowi' === behaviorType) {
- // Crowi behavior for '/trash/*'
- return actions.deletedPageListShow(req, res);
- }
- else {
- const path = '/trash' + getPathFromRequest(req);
- return res.redirect(path);
- }
- };
- actions.pageListShow = function(req, res) {
- var path = getPathFromRequest(req);
- var limit = 50;
- var offset = parseInt(req.query.offset) || 0;
- var SEENER_THRESHOLD = 10;
- // add slash if root
- path = path + (path == '/' ? '' : '/');
- debug('Page list show', path);
- // index page
- var pagerOptions = {
- offset: offset,
- limit: limit
- };
- var queryOptions = {
- offset: offset,
- limit: limit + 1,
- isPopulateRevisionBody: Config.isEnabledTimeline(config),
- };
- var renderVars = {
- page: null,
- path: path,
- isPortal: false,
- pages: [],
- tree: [],
- };
- Page.hasPortalPage(path, req.user, req.query.revision)
- .then(function(portalPage) {
- renderVars.page = portalPage;
- renderVars.isPortal = (portalPage != null);
- if (portalPage) {
- renderVars.revision = portalPage.revision;
- renderVars.revisionHackmdSynced = portalPage.revisionHackmdSynced;
- renderVars.pageIdOnHackmd = portalPage.pageIdOnHackmd;
- return Revision.findRevisionList(portalPage.path, {});
- }
- else {
- return Promise.resolve([]);
- }
- })
- .then(function(tree) {
- renderVars.tree = tree;
- return Page.findListByStartWith(path, req.user, queryOptions);
- })
- .then(function(pageList) {
- if (pageList.length > limit) {
- pageList.pop();
- }
- pagerOptions.length = pageList.length;
- renderVars.viewConfig = {
- seener_threshold: SEENER_THRESHOLD,
- };
- renderVars.pager = generatePager(pagerOptions);
- renderVars.pages = pagePathUtil.encodePagesPath(pageList);
- })
- .then(() => {
- return PageGroupRelation.findByPage(renderVars.page);
- })
- .then((pageGroupRelation) => {
- if (pageGroupRelation != null) {
- renderVars.pageRelatedGroup = pageGroupRelation.relatedGroup;
- }
- })
- .then(() => {
- res.render('customlayout-selector/page_list', renderVars);
- }).catch(function(err) {
- debug('Error on rendering pageListShow', err);
- });
- };
- actions.pageListShowForCrowiPlus = function(req, res) {
- let path = getPathFromRequest(req);
- // omit the slash of the last
- path = path.replace((/\/$/), '');
- // redirect
- return res.redirect(path);
- };
- actions.pageShowForCrowiPlus = function(req, res) {
- const path = getPathFromRequest(req);
- const limit = 50;
- const offset = parseInt(req.query.offset) || 0;
- const SEENER_THRESHOLD = 10;
- // index page
- const pagerOptions = {
- offset: offset,
- limit: limit
- };
- const queryOptions = {
- offset: offset,
- limit: limit + 1,
- isPopulateRevisionBody: Config.isEnabledTimeline(config),
- includeDeletedPage: path.startsWith('/trash/'),
- };
- const renderVars = {
- path: path,
- page: null,
- revision: {},
- author: false,
- pages: [],
- tree: [],
- pageRelatedGroup: null,
- template: null,
- revisionHackmdSynced: null,
- slack: '',
- };
- let view = 'customlayout-selector/page';
- let isRedirect = false;
- Page.findPage(path, req.user, req.query.revision)
- .then(function(page) {
- debug('Page found', page._id, page.path);
- // redirect
- if (page.redirectTo) {
- debug(`Redirect to '${page.redirectTo}'`);
- isRedirect = true;
- return res.redirect(encodeURI(page.redirectTo + '?redirectFrom=' + pagePathUtil.encodePagePath(page.path)));
- }
- renderVars.page = page;
- if (page) {
- renderVars.path = page.path;
- renderVars.revision = page.revision;
- renderVars.author = page.revision.author;
- renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
- renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
- return Revision.findRevisionList(page.path, {})
- .then(function(tree) {
- renderVars.tree = tree;
- })
- .then(() => {
- return PageGroupRelation.findByPage(renderVars.page);
- })
- .then((pageGroupRelation) => {
- if (pageGroupRelation != null) {
- renderVars.pageRelatedGroup = pageGroupRelation.relatedGroup;
- }
- })
- .then(() => {
- return getSlackChannels(page);
- })
- .then((channels) => {
- renderVars.slack = channels;
- })
- .then(function() {
- const userPage = isUserPage(page.path);
- let userData = null;
- if (userPage) {
- // change template
- view = 'customlayout-selector/user_page';
- return User.findUserByUsername(User.getUsernameByPath(page.path))
- .then(function(data) {
- if (data === null) {
- throw new Error('The user not found.');
- }
- userData = data;
- renderVars.pageUser = userData;
- return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
- }).then(function(bookmarkList) {
- renderVars.bookmarkList = bookmarkList;
- return Page.findListByCreator(userData, {limit: 10}, req.user);
- }).then(function(createdList) {
- renderVars.createdList = createdList;
- return Promise.resolve();
- }).catch(function(err) {
- debug('Error on finding user related entities', err);
- // pass
- });
- }
- });
- }
- })
- // page is not found or user is forbidden
- .catch(function(err) {
- let isForbidden = false;
- if (err.name === 'UserHasNoGrantException') {
- isForbidden = true;
- }
- if (isForbidden) {
- view = 'customlayout-selector/forbidden';
- return;
- }
- else {
- view = 'customlayout-selector/not_found';
- // look for templates
- return Page.findTemplate(path)
- .then(template => {
- if (template) {
- template = replacePlaceholders(template, req);
- }
- renderVars.template = template;
- });
- }
- })
- // get list pages
- .then(function() {
- if (!isRedirect) {
- Page.findListWithDescendants(path, req.user, queryOptions)
- .then(function(pageList) {
- if (pageList.length > limit) {
- pageList.pop();
- }
- pagerOptions.length = pageList.length;
- renderVars.viewConfig = {
- seener_threshold: SEENER_THRESHOLD,
- };
- renderVars.pager = generatePager(pagerOptions);
- renderVars.pages = pagePathUtil.encodePagesPath(pageList);
- return;
- })
- .then(function() {
- return interceptorManager.process('beforeRenderPage', req, res, renderVars);
- })
- .then(function() {
- res.render(req.query.presentation ? 'page_presentation' : view, renderVars);
- })
- .catch(function(err) {
- logger.error('Error on rendering pageListShowForCrowiPlus', err);
- });
- }
- });
- };
- const getSlackChannels = async page => {
- if (page.extended.slack) {
- return page.extended.slack;
- }
- else {
- const data = await UpdatePost.findSettingsByPath(page.path);
- const channels = data.map(e => e.channel).join(', ');
- return channels;
- }
- };
- const replacePlaceholders = (template, req) => {
- const definitions = {
- pagepath: getPathFromRequest(req),
- username: req.user.name,
- today: getToday(),
- };
- const compiledTemplate = swig.compile(template);
- return compiledTemplate(definitions);
- };
- actions.deletedPageListShow = function(req, res) {
- var path = '/trash' + getPathFromRequest(req);
- var limit = 50;
- var offset = parseInt(req.query.offset) || 0;
- // index page
- var pagerOptions = {
- offset: offset,
- limit: limit
- };
- var queryOptions = {
- offset: offset,
- limit: limit + 1,
- includeDeletedPage: true,
- };
- var renderVars = {
- page: null,
- path: path,
- pages: [],
- };
- Page.findListWithDescendants(path, req.user, queryOptions)
- .then(function(pageList) {
- if (pageList.length > limit) {
- pageList.pop();
- }
- pagerOptions.length = pageList.length;
- renderVars.pager = generatePager(pagerOptions);
- renderVars.pages = pagePathUtil.encodePagesPath(pageList);
- res.render('customlayout-selector/page_list', renderVars);
- }).catch(function(err) {
- debug('Error on rendering deletedPageListShow', err);
- });
- };
- actions.search = function(req, res) {
- // spec: ?q=query&sort=sort_order&author=author_filter
- var query = req.query.q;
- var search = require('../util/search')(crowi);
- search.searchPageByKeyword(query)
- .then(function(pages) {
- debug('pages', pages);
- if (pages.hits.total <= 0) {
- return Promise.resolve([]);
- }
- var ids = pages.hits.hits.map(function(page) {
- return page._id;
- });
- return Page.findListByPageIds(ids);
- }).then(function(pages) {
- res.render('customlayout-selector/page_list', {
- path: '/',
- pages: pagePathUtil.encodePagesPath(pages),
- pager: generatePager({offset: 0, limit: 50})
- });
- }).catch(function(err) {
- debug('search error', err);
- });
- };
- async function renderPage(pageData, req, res, isForbidden) {
- if (!pageData) {
- let view = 'customlayout-selector/not_found';
- let template = undefined;
- // forbidden
- if (isForbidden) {
- view = 'customlayout-selector/forbidden';
- }
- else {
- const path = getPathFromRequest(req);
- template = await Page.findTemplate(path);
- if (template != null) {
- template = replacePlaceholders(template, req);
- }
- }
- return res.render(view, {
- author: {},
- page: false,
- template,
- });
- }
- if (pageData.redirectTo) {
- return res.redirect(encodeURI(pageData.redirectTo + '?redirectFrom=' + pagePathUtil.encodePagePath(pageData.path)));
- }
- const renderVars = {
- path: pageData.path,
- page: pageData,
- revision: pageData.revision || {},
- author: pageData.revision.author || false,
- slack: '',
- };
- const userPage = isUserPage(pageData.path);
- let userData = null;
- Revision.findRevisionList(pageData.path, {})
- .then(function(tree) {
- renderVars.tree = tree;
- })
- .then(() => {
- return PageGroupRelation.findByPage(renderVars.page);
- })
- .then((pageGroupRelation) => {
- if (pageGroupRelation != null) {
- renderVars.pageRelatedGroup = pageGroupRelation.relatedGroup;
- }
- })
- .then(() => {
- return getSlackChannels(pageData);
- })
- .then(channels => {
- renderVars.slack = channels;
- })
- .then(function() {
- if (userPage) {
- return User.findUserByUsername(User.getUsernameByPath(pageData.path))
- .then(function(data) {
- if (data === null) {
- throw new Error('The user not found.');
- }
- userData = data;
- renderVars.pageUser = userData;
- return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
- }).then(function(bookmarkList) {
- renderVars.bookmarkList = bookmarkList;
- return Page.findListByCreator(userData, {limit: 10}, req.user);
- }).then(function(createdList) {
- renderVars.createdList = createdList;
- return Promise.resolve();
- }).catch(function(err) {
- debug('Error on finding user related entities', err);
- // pass
- });
- }
- else {
- return Promise.resolve();
- }
- }).then(function() {
- return interceptorManager.process('beforeRenderPage', req, res, renderVars);
- }).then(function() {
- let view = 'customlayout-selector/page';
- if (userData) {
- view = 'customlayout-selector/user_page';
- }
- res.render(req.query.presentation ? 'page_presentation' : view, renderVars);
- }).catch(function(err) {
- debug('Error: renderPage()', err);
- if (err) {
- res.redirect('/');
- }
- });
- }
- actions.pageShow = function(req, res) {
- var path = path || getPathFromRequest(req);
- // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ
- var isMarkdown = req.params[0].match(/.+\.md$/) || false;
- res.locals.path = path;
- Page.findPage(path, req.user, req.query.revision)
- .then(function(page) {
- debug('Page found', page._id, page.path);
- if (isMarkdown) {
- res.set('Content-Type', 'text/plain');
- return res.send(page.revision.body);
- }
- return renderPage(page, req, res);
- })
- // page is not found or the user is forbidden
- .catch(function(err) {
- let isForbidden = false;
- if (err.name === 'UserHasNoGrantException') {
- isForbidden = true;
- }
- const normalizedPath = Page.normalizePath(path);
- if (normalizedPath !== path) {
- return res.redirect(normalizedPath);
- }
- // pageShow は /* にマッチしてる最後の砦なので、creatableName でない routing は
- // これ以前に定義されているはずなので、こうしてしまって問題ない。
- if (!Page.isCreatableName(path)) {
- // 削除済みページの場合 /trash 以下に移動しているので creatableName になっていないので、表示を許可
- logger.warn('Page is not creatable name.', path);
- res.redirect('/');
- return ;
- }
- if (req.query.revision) {
- return res.redirect(pagePathUtil.encodePagePath(path));
- }
- if (isMarkdown) {
- return res.redirect('/');
- }
- Page.hasPortalPage(path + '/', req.user)
- .then(function(page) {
- if (page) {
- return res.redirect(pagePathUtil.encodePagePath(path) + '/');
- }
- else {
- const fixed = Page.fixToCreatableName(path);
- if (fixed !== path) {
- logger.warn('fixed page name', fixed);
- res.redirect(pagePathUtil.encodePagePath(fixed));
- return ;
- }
- // if guest user
- if (!req.user) {
- res.redirect('/');
- }
- // render editor
- debug('Catch pageShow', err);
- return renderPage(null, req, res, isForbidden);
- }
- }).catch(function(err) {
- debug('Error on rendering pageShow (redirect to portal)', err);
- });
- });
- };
- actions.pageEdit = function(req, res) {
- if (!req.form.isValid) {
- req.flash('dangerMessage', 'Request is invalid.');
- return res.redirect(req.headers.referer);
- }
- var pageForm = req.form.pageForm;
- var path = pageForm.path;
- var body = pageForm.body;
- var currentRevision = pageForm.currentRevision;
- var grant = pageForm.grant;
- var grantUserGroupId = pageForm.grantUserGroupId;
- // TODO: make it pluggable
- var notify = pageForm.notify || {};
- debug('notify: ', notify);
- var redirectPath = pagePathUtil.encodePagePath(path);
- var pageData = {};
- var updateOrCreate;
- var previousRevision = 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 (data && !data.isUpdatable(currentRevision)) {
- debug('Conflict occured');
- req.flash('dangerMessage', 'Conflict occured');
- return res.redirect(req.headers.referer);
- }
- if (data) {
- previousRevision = data.revision;
- return Page.updatePage(data, body, req.user, { grant, grantUserGroupId })
- .then((page) => {
- // global notification
- globalNotificationService.notifyPageEdit(page);
- return page;
- });
- }
- else {
- // new page
- updateOrCreate = 'create';
- return Page.create(path, body, req.user, { grant, grantUserGroupId })
- .then((page) => {
- // global notification
- globalNotificationService.notifyPageCreate(page);
- return page;
- });
- }
- }).then(function(data) {
- // data is a saved page data with revision.
- 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)
- .catch(err => {
- logger.error('Error occured in updating slack channels: ', err);
- });
- if (crowi.slack) {
- const promises = notify.slack.channel.split(',').map(function(chan) {
- return crowi.slack.postPage(pageData, req.user, chan, updateOrCreate, previousRevision);
- });
- Promise.all(promises)
- .catch(err => {
- logger.error('Error occured in sending slack notification: ', err);
- });
- }
- }
- }
- return res.redirect(redirectPath);
- });
- };
- var api = actions.api = {};
- /**
- * redirector
- */
- api.redirector = function(req, res) {
- var id = req.params.id;
- Page.findPageById(id)
- .then(function(pageData) {
- if (pageData.grant == Page.GRANT_RESTRICTED && !pageData.isGrantedFor(req.user)) {
- return Page.pushToGrantedUsers(pageData, req.user);
- }
- return Promise.resolve(pageData);
- }).then(function(page) {
- return res.redirect(pagePathUtil.encodePagePath(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 = { offset: offset, limit: limit };
- var queryOptions = { offset: 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;
- var result = {};
- result.pages = pagePathUtil.encodePagesPath(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;
- var grantUserGroupId = req.body.grantUserGroupId || 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.create(pagePath, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
- }).then(function(data) {
- if (!data) {
- throw new Error('Failed to create page.');
- }
- var result = { page: data.toObject() };
- result.page.lastUpdateUser = User.filterToPublicFields(data.lastUpdateUser);
- result.page.creator = User.filterToPublicFields(data.creator);
- 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;
- var grantUserGroupId = req.body.grantUserGroupId || 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 = {};
- if (grant != null) {
- grantOption.grant = grant;
- }
- if (grantUserGroupId != null) {
- grantOption.grantUserGroupId = grantUserGroupId;
- }
- return Page.updatePage(pageData, pageBody, req.user, grantOption);
- }).then(function(pageData) {
- var result = {
- page: pageData.toObject(),
- };
- result.page.lastUpdateUser = User.filterToPublicFields(result.page.lastUpdateUser);
- 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(pageData) {
- var result = {};
- result.page = pageData;
- 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(user) {
- var result = {};
- result.seenUser = user;
- 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(page) {
- var result = {page: page};
- res.json(ApiResponse.success(result));
- return page;
- })
- .then((page) => {
- // global notification
- return globalNotificationService.notifyPageLike(page, req.user);
- })
- .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);
- // get recursively flag
- const isRecursively = (req.body.recursively !== undefined);
- Page.findPageByIdAndGrantedUser(pageId, req.user)
- .then(function(pageData) {
- debug('Delete page', pageData._id, pageData.path);
- if (isCompletely) {
- if (isRecursively) {
- return Page.completelyDeletePageRecursively(pageData, req.user);
- }
- else {
- return Page.completelyDeletePage(pageData, req.user);
- }
- }
- // else
- if (!pageData.isUpdatable(previousRevision)) {
- throw new Error('Someone could update this page, so couldn\'t delete.');
- }
- if (isRecursively) {
- return Page.deletePageRecursively(pageData, req.user);
- }
- else {
- return Page.deletePage(pageData, req.user);
- }
- })
- .then(function(data) {
- debug('Page deleted', data.path);
- var result = {};
- result.page = data;
- res.json(ApiResponse.success(result));
- return data;
- })
- .then((page) => {
- // global notification
- return globalNotificationService.notifyPageDelete(page);
- })
- .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;
- // get recursively flag
- const isRecursively = (req.body.recursively !== undefined);
- Page.findPageByIdAndGrantedUser(pageId, req.user)
- .then(function(pageData) {
- if (isRecursively) {
- return Page.revertDeletedPageRecursively(pageData, req.user);
- }
- else {
- return Page.revertDeletedPage(pageData, req.user);
- }
- }).then(function(data) {
- debug('Complete to revert deleted page', data.path);
- var result = {};
- result.page = data;
- 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 = function(req, res) {
- var pageId = req.body.page_id;
- var previousRevision = req.body.revision_id || null;
- var newPagePath = Page.normalizePath(req.body.new_path);
- var options = {
- createRedirectPage: req.body.create_redirect || 0,
- moveUnderTrees: req.body.move_trees || 0,
- };
- var isRecursiveMove = req.body.move_recursively || 0;
- var page = {};
- if (!Page.isCreatableName(newPagePath)) {
- return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})`));
- }
- Page.findPageByPath(newPagePath)
- .then(function(page) {
- if (page != null) {
- // if page found, cannot cannot rename to that path
- return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`));
- }
- Page.findPageById(pageId)
- .then(function(pageData) {
- page = pageData;
- if (!pageData.isUpdatable(previousRevision)) {
- throw new Error('Someone could update this page, so couldn\'t delete.');
- }
- if (isRecursiveMove) {
- return Page.renameRecursively(pageData, newPagePath, req.user, options);
- }
- else {
- return Page.rename(pageData, newPagePath, req.user, options);
- }
- })
- .then(function() {
- var result = {};
- result.page = page;
- return res.json(ApiResponse.success(result));
- })
- .then(() => {
- // global notification
- globalNotificationService.notifyPageMove(page, req.body.path, req.user);
- })
- .catch(function(err) {
- return res.json(ApiResponse.error('Failed to update page.'));
- });
- });
- };
- /**
- * @api {post} /pages.duplicate Duplicate page
- * @apiName DuplicatePage
- * @apiGroup Page
- *
- * @apiParam {String} page_id Page Id.
- * @apiParam {String} new_path
- */
- api.duplicate = function(req, res) {
- var pageId = req.body.page_id;
- var newPagePath = Page.normalizePath(req.body.new_path);
- Page.findPageById(pageId)
- .then(function(pageData) {
- req.body.path = newPagePath;
- req.body.body = pageData.revision.body;
- req.body.grant = pageData.grant;
- return api.create(req, res);
- });
- };
- /**
- * @api {post} /pages.unlink Remove the redirecting page
- * @apiName UnlinkPage
- * @apiGroup Page
- *
- * @apiParam {String} page_id Page Id.
- * @apiParam {String} revision_id
- */
- api.unlink = function(req, res) {
- var pageId = req.body.page_id;
- Page.findPageByIdAndGrantedUser(pageId, req.user)
- .then(function(pageData) {
- debug('Unlink page', pageData._id, pageData.path);
- return Page.removeRedirectOriginPageByPath(pageData.path)
- .then(() => pageData);
- }).then(function(data) {
- debug('Redirect Page deleted', data.path);
- var result = {};
- result.page = data;
- 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 redirect page.'));
- });
- };
- return actions;
- };
|