page.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. /* eslint-disable no-use-before-define */
  2. module.exports = function(crowi, app) {
  3. const debug = require('debug')('growi:routes:page');
  4. const logger = require('@alias/logger')('growi:routes:page');
  5. const swig = require('swig-templates');
  6. const pathUtils = require('growi-commons').pathUtils;
  7. const Page = crowi.model('Page');
  8. const User = crowi.model('User');
  9. const Bookmark = crowi.model('Bookmark');
  10. const PageTagRelation = crowi.model('PageTagRelation');
  11. const UpdatePost = crowi.model('UpdatePost');
  12. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  13. const ApiResponse = require('../util/apiResponse');
  14. const getToday = require('../util/getToday');
  15. const { configManager, slackNotificationService } = crowi;
  16. const interceptorManager = crowi.getInterceptorManager();
  17. const globalNotificationService = crowi.getGlobalNotificationService();
  18. const actions = {};
  19. const PORTAL_STATUS_NOT_EXISTS = 0;
  20. const PORTAL_STATUS_EXISTS = 1;
  21. const PORTAL_STATUS_FORBIDDEN = 2;
  22. // register page events
  23. const pageEvent = crowi.event('page');
  24. pageEvent.on('create', (page, user, socketClientId) => {
  25. page = serializeToObj(page); // eslint-disable-line no-param-reassign
  26. crowi.getIo().sockets.emit('page:create', { page, user, socketClientId });
  27. });
  28. pageEvent.on('update', (page, user, socketClientId) => {
  29. page = serializeToObj(page); // eslint-disable-line no-param-reassign
  30. crowi.getIo().sockets.emit('page:update', { page, user, socketClientId });
  31. });
  32. pageEvent.on('delete', (page, user, socketClientId) => {
  33. page = serializeToObj(page); // eslint-disable-line no-param-reassign
  34. crowi.getIo().sockets.emit('page:delete', { page, user, socketClientId });
  35. });
  36. function serializeToObj(page) {
  37. const returnObj = page.toObject();
  38. if (page.revisionHackmdSynced != null && page.revisionHackmdSynced._id != null) {
  39. returnObj.revisionHackmdSynced = page.revisionHackmdSynced._id;
  40. }
  41. if (page.lastUpdateUser != null && page.lastUpdateUser instanceof User) {
  42. returnObj.lastUpdateUser = page.lastUpdateUser.toObject();
  43. }
  44. if (page.creator != null && page.creator instanceof User) {
  45. returnObj.creator = page.creator.toObject();
  46. }
  47. return returnObj;
  48. }
  49. function getPathFromRequest(req) {
  50. return pathUtils.normalizePath(req.params[0] || '');
  51. }
  52. function isUserPage(path) {
  53. if (path.match(/^\/user\/[^/]+\/?$/)) {
  54. return true;
  55. }
  56. return false;
  57. }
  58. function generatePager(offset, limit, totalCount) {
  59. let prev = null;
  60. if (offset > 0) {
  61. prev = offset - limit;
  62. if (prev < 0) {
  63. prev = 0;
  64. }
  65. }
  66. let next = offset + limit;
  67. if (totalCount < next) {
  68. next = null;
  69. }
  70. return {
  71. prev,
  72. next,
  73. offset,
  74. };
  75. }
  76. // user notification
  77. // TODO create '/service/user-notification' module
  78. /**
  79. *
  80. * @param {Page} page
  81. * @param {User} user
  82. * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
  83. * @param {boolean} updateOrCreate
  84. * @param {string} previousRevision
  85. */
  86. async function notifyToSlackByUser(page, user, slackChannelsStr, updateOrCreate, previousRevision) {
  87. await page.updateSlackChannel(slackChannelsStr)
  88. .catch((err) => {
  89. logger.error('Error occured in updating slack channels: ', err);
  90. });
  91. if (slackNotificationService.hasSlackConfig()) {
  92. const slackChannels = slackChannelsStr != null ? slackChannelsStr.split(',') : [null];
  93. const promises = slackChannels.map((chan) => {
  94. return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
  95. });
  96. Promise.all(promises)
  97. .catch((err) => {
  98. logger.error('Error occured in sending slack notification: ', err);
  99. });
  100. }
  101. }
  102. function addRendarVarsForPage(renderVars, page) {
  103. renderVars.page = page;
  104. renderVars.path = page.path;
  105. renderVars.revision = page.revision;
  106. renderVars.author = page.revision.author;
  107. renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
  108. renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
  109. renderVars.hasDraftOnHackmd = page.hasDraftOnHackmd;
  110. }
  111. async function addRenderVarsForUserPage(renderVars, page, requestUser) {
  112. const userData = await User.findUserByUsername(User.getUsernameByPath(page.path))
  113. .populate(User.IMAGE_POPULATION);
  114. if (userData != null) {
  115. renderVars.pageUser = userData;
  116. renderVars.bookmarkList = await Bookmark.findByUser(userData, { limit: 10, populatePage: true, requestUser });
  117. }
  118. }
  119. function addRendarVarsForScope(renderVars, page) {
  120. renderVars.grant = page.grant;
  121. renderVars.grantedGroupId = page.grantedGroup ? page.grantedGroup.id : null;
  122. renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
  123. }
  124. async function addRenderVarsForSlack(renderVars, page) {
  125. renderVars.slack = await getSlackChannels(page);
  126. }
  127. async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
  128. const SEENER_THRESHOLD = 10;
  129. const queryOptions = {
  130. offset,
  131. limit,
  132. includeTrashed: path.startsWith('/trash/'),
  133. isRegExpEscapedFromPath,
  134. };
  135. const result = await Page.findListWithDescendants(path, requestUser, queryOptions);
  136. if (result.pages.length > limit) {
  137. result.pages.pop();
  138. }
  139. renderVars.viewConfig = {
  140. seener_threshold: SEENER_THRESHOLD,
  141. };
  142. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  143. renderVars.pages = pathUtils.encodePagesPath(result.pages);
  144. }
  145. function replacePlaceholdersOfTemplate(template, req) {
  146. if (req.user == null) {
  147. return '';
  148. }
  149. const definitions = {
  150. pagepath: getPathFromRequest(req),
  151. username: req.user.name,
  152. today: getToday(),
  153. };
  154. const compiledTemplate = swig.compile(template);
  155. return compiledTemplate(definitions);
  156. }
  157. async function showPageForPresentation(req, res, next) {
  158. const path = getPathFromRequest(req);
  159. const revisionId = req.query.revision;
  160. let page = await Page.findByPathAndViewer(path, req.user);
  161. if (page == null) {
  162. next();
  163. }
  164. const renderVars = {};
  165. // populate
  166. page = await page.populateDataToMakePresentation(revisionId);
  167. addRendarVarsForPage(renderVars, page);
  168. return res.render('page_presentation', renderVars);
  169. }
  170. async function showPageListForCrowiBehavior(req, res, next) {
  171. const portalPath = pathUtils.addTrailingSlash(getPathFromRequest(req));
  172. const revisionId = req.query.revision;
  173. // check whether this page has portal page
  174. const portalPageStatus = await getPortalPageState(portalPath, req.user);
  175. let view = 'customlayout-selector/page_list';
  176. const renderVars = { path: portalPath };
  177. if (portalPageStatus === PORTAL_STATUS_FORBIDDEN) {
  178. // inject to req
  179. req.isForbidden = true;
  180. view = 'customlayout-selector/forbidden';
  181. }
  182. else if (portalPageStatus === PORTAL_STATUS_EXISTS) {
  183. let portalPage = await Page.findByPathAndViewer(portalPath, req.user);
  184. portalPage.initLatestRevisionField(revisionId);
  185. // populate
  186. portalPage = await portalPage.populateDataToShowRevision();
  187. addRendarVarsForPage(renderVars, portalPage);
  188. await addRenderVarsForSlack(renderVars, portalPage);
  189. }
  190. const limit = 50;
  191. const offset = parseInt(req.query.offset) || 0;
  192. await addRenderVarsForDescendants(renderVars, portalPath, req.user, offset, limit);
  193. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  194. return res.render(view, renderVars);
  195. }
  196. async function showPageForGrowiBehavior(req, res, next) {
  197. const path = getPathFromRequest(req);
  198. const revisionId = req.query.revision;
  199. let page = await Page.findByPathAndViewer(path, req.user);
  200. if (page == null) {
  201. // check the page is forbidden or just does not exist.
  202. req.isForbidden = await Page.count({ path }) > 0;
  203. return next();
  204. }
  205. if (page.redirectTo) {
  206. debug(`Redirect to '${page.redirectTo}'`);
  207. return res.redirect(encodeURI(`${page.redirectTo}?redirectFrom=${pathUtils.encodePagePath(path)}`));
  208. }
  209. logger.debug('Page is found when processing pageShowForGrowiBehavior', page._id, page.path);
  210. const limit = 50;
  211. const offset = parseInt(req.query.offset) || 0;
  212. const renderVars = {};
  213. let view = 'customlayout-selector/page';
  214. page.initLatestRevisionField(revisionId);
  215. // populate
  216. page = await page.populateDataToShowRevision();
  217. addRendarVarsForPage(renderVars, page);
  218. addRendarVarsForScope(renderVars, page);
  219. await addRenderVarsForSlack(renderVars, page);
  220. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  221. if (isUserPage(page.path)) {
  222. // change template
  223. view = 'customlayout-selector/user_page';
  224. await addRenderVarsForUserPage(renderVars, page, req.user);
  225. }
  226. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  227. return res.render(view, renderVars);
  228. }
  229. const getSlackChannels = async(page) => {
  230. if (page.extended.slack) {
  231. return page.extended.slack;
  232. }
  233. const data = await UpdatePost.findSettingsByPath(page.path);
  234. const channels = data.map((e) => { return e.channel }).join(', ');
  235. return channels;
  236. };
  237. /**
  238. *
  239. * @param {string} path
  240. * @param {User} user
  241. * @returns {number} PORTAL_STATUS_NOT_EXISTS(0) or PORTAL_STATUS_EXISTS(1) or PORTAL_STATUS_FORBIDDEN(2)
  242. */
  243. async function getPortalPageState(path, user) {
  244. const portalPath = Page.addSlashOfEnd(path);
  245. const page = await Page.findByPathAndViewer(portalPath, user);
  246. if (page == null) {
  247. // check the page is forbidden or just does not exist.
  248. const isForbidden = await Page.count({ path: portalPath }) > 0;
  249. return isForbidden ? PORTAL_STATUS_FORBIDDEN : PORTAL_STATUS_NOT_EXISTS;
  250. }
  251. return PORTAL_STATUS_EXISTS;
  252. }
  253. actions.showTopPage = function(req, res) {
  254. return showPageListForCrowiBehavior(req, res);
  255. };
  256. /**
  257. * switch action by behaviorType
  258. */
  259. /* eslint-disable no-else-return */
  260. actions.showPageWithEndOfSlash = function(req, res, next) {
  261. const behaviorType = configManager.getConfig('crowi', 'customize:behavior');
  262. if (behaviorType === 'crowi') {
  263. return showPageListForCrowiBehavior(req, res, next);
  264. }
  265. else {
  266. const path = getPathFromRequest(req); // end of slash should be omitted
  267. // redirect and showPage action will be triggered
  268. return res.redirect(path);
  269. }
  270. };
  271. /* eslint-enable no-else-return */
  272. /**
  273. * switch action
  274. * - presentation mode
  275. * - by behaviorType
  276. */
  277. actions.showPage = async function(req, res, next) {
  278. // presentation mode
  279. if (req.query.presentation) {
  280. return showPageForPresentation(req, res, next);
  281. }
  282. const behaviorType = configManager.getConfig('crowi', 'customize:behavior');
  283. // check whether this page has portal page
  284. if (behaviorType === 'crowi') {
  285. const portalPagePath = pathUtils.addTrailingSlash(getPathFromRequest(req));
  286. const hasPortalPage = await Page.count({ path: portalPagePath }) > 0;
  287. if (hasPortalPage) {
  288. logger.debug('The portal page is found', portalPagePath);
  289. return res.redirect(encodeURI(`${portalPagePath}?redirectFrom=${pathUtils.encodePagePath(req.path)}`));
  290. }
  291. }
  292. // delegate to showPageForGrowiBehavior
  293. return showPageForGrowiBehavior(req, res, next);
  294. };
  295. /**
  296. * switch action by behaviorType
  297. */
  298. /* eslint-disable no-else-return */
  299. actions.trashPageListShowWrapper = function(req, res) {
  300. const behaviorType = configManager.getConfig('crowi', 'customize:behavior');
  301. if (behaviorType === 'crowi') {
  302. // Crowi behavior for '/trash/*'
  303. return actions.deletedPageListShow(req, res);
  304. }
  305. else {
  306. // redirect to '/trash'
  307. return res.redirect('/trash');
  308. }
  309. };
  310. /* eslint-enable no-else-return */
  311. /**
  312. * switch action by behaviorType
  313. */
  314. /* eslint-disable no-else-return */
  315. actions.trashPageShowWrapper = function(req, res) {
  316. const behaviorType = configManager.getConfig('crowi', 'customize:behavior');
  317. if (behaviorType === 'crowi') {
  318. // redirect to '/trash/'
  319. return res.redirect('/trash/');
  320. }
  321. else {
  322. // Crowi behavior for '/trash/*'
  323. return actions.deletedPageListShow(req, res);
  324. }
  325. };
  326. /* eslint-enable no-else-return */
  327. /**
  328. * switch action by behaviorType
  329. */
  330. /* eslint-disable no-else-return */
  331. actions.deletedPageListShowWrapper = function(req, res) {
  332. const behaviorType = configManager.getConfig('crowi', 'customize:behavior');
  333. if (behaviorType === 'crowi') {
  334. // Crowi behavior for '/trash/*'
  335. return actions.deletedPageListShow(req, res);
  336. }
  337. else {
  338. const path = `/trash${getPathFromRequest(req)}`;
  339. return res.redirect(path);
  340. }
  341. };
  342. /* eslint-enable no-else-return */
  343. actions.notFound = async function(req, res) {
  344. const path = getPathFromRequest(req);
  345. const isCreatable = Page.isCreatableName(path);
  346. let view;
  347. const renderVars = { path };
  348. if (!isCreatable) {
  349. view = 'customlayout-selector/not_creatable';
  350. }
  351. else if (req.isForbidden) {
  352. view = 'customlayout-selector/forbidden';
  353. }
  354. else {
  355. view = 'customlayout-selector/not_found';
  356. // retrieve templates
  357. if (req.user != null) {
  358. const template = await Page.findTemplate(path);
  359. if (template.templateBody) {
  360. const body = replacePlaceholdersOfTemplate(template.templateBody, req);
  361. const tags = template.templateTags;
  362. renderVars.template = body;
  363. renderVars.templateTags = tags;
  364. }
  365. }
  366. // add scope variables by ancestor page
  367. const ancestor = await Page.findAncestorByPathAndViewer(path, req.user);
  368. if (ancestor != null) {
  369. await ancestor.populate('grantedGroup').execPopulate();
  370. addRendarVarsForScope(renderVars, ancestor);
  371. }
  372. }
  373. const limit = 50;
  374. const offset = parseInt(req.query.offset) || 0;
  375. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  376. return res.render(view, renderVars);
  377. };
  378. actions.deletedPageListShow = async function(req, res) {
  379. // normalizePath makes '/trash/' -> '/trash'
  380. const path = pathUtils.normalizePath(`/trash${getPathFromRequest(req)}`);
  381. const limit = 50;
  382. const offset = parseInt(req.query.offset) || 0;
  383. const queryOptions = {
  384. offset,
  385. limit,
  386. includeTrashed: true,
  387. };
  388. const renderVars = {
  389. page: null,
  390. path,
  391. pages: [],
  392. };
  393. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  394. if (result.pages.length > limit) {
  395. result.pages.pop();
  396. }
  397. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  398. renderVars.pages = pathUtils.encodePagesPath(result.pages);
  399. res.render('customlayout-selector/page_list', renderVars);
  400. };
  401. /**
  402. * redirector
  403. */
  404. actions.redirector = async function(req, res) {
  405. const id = req.params.id;
  406. const page = await Page.findByIdAndViewer(id, req.user);
  407. if (page != null) {
  408. return res.redirect(pathUtils.encodePagePath(page.path));
  409. }
  410. return res.redirect('/');
  411. };
  412. const api = {};
  413. actions.api = api;
  414. /**
  415. * @api {get} /pages.list List pages by user
  416. * @apiName ListPage
  417. * @apiGroup Page
  418. *
  419. * @apiParam {String} path
  420. * @apiParam {String} user
  421. */
  422. api.list = async function(req, res) {
  423. const username = req.query.user || null;
  424. const path = req.query.path || null;
  425. const limit = +req.query.limit || 50;
  426. const offset = parseInt(req.query.offset) || 0;
  427. const queryOptions = { offset, limit: limit + 1 };
  428. // Accepts only one of these
  429. if (username === null && path === null) {
  430. return res.json(ApiResponse.error('Parameter user or path is required.'));
  431. }
  432. if (username !== null && path !== null) {
  433. return res.json(ApiResponse.error('Parameter user or path is required.'));
  434. }
  435. try {
  436. let result = null;
  437. if (path == null) {
  438. const user = await User.findUserByUsername(username);
  439. if (user === null) {
  440. throw new Error('The user not found.');
  441. }
  442. result = await Page.findListByCreator(user, req.user, queryOptions);
  443. }
  444. else {
  445. result = await Page.findListByStartWith(path, req.user, queryOptions);
  446. }
  447. if (result.pages.length > limit) {
  448. result.pages.pop();
  449. }
  450. result.pages = pathUtils.encodePagesPath(result.pages);
  451. return res.json(ApiResponse.success(result));
  452. }
  453. catch (err) {
  454. return res.json(ApiResponse.error(err));
  455. }
  456. };
  457. /**
  458. * @api {post} /pages.create Create new page
  459. * @apiName CreatePage
  460. * @apiGroup Page
  461. *
  462. * @apiParam {String} body
  463. * @apiParam {String} path
  464. * @apiParam {String} grant
  465. * @apiParam {Array} pageTags
  466. */
  467. api.create = async function(req, res) {
  468. const body = req.body.body || null;
  469. const pagePath = req.body.path || null;
  470. const grant = req.body.grant || null;
  471. const grantUserGroupId = req.body.grantUserGroupId || null;
  472. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  473. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  474. const slackChannels = req.body.slackChannels || null;
  475. const socketClientId = req.body.socketClientId || undefined;
  476. const pageTags = req.body.pageTags || undefined;
  477. if (body === null || pagePath === null) {
  478. return res.json(ApiResponse.error('Parameters body and path are required.'));
  479. }
  480. // check page existence
  481. const isExist = await Page.count({ path: pagePath }) > 0;
  482. if (isExist) {
  483. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  484. }
  485. const options = { socketClientId };
  486. if (grant != null) {
  487. options.grant = grant;
  488. options.grantUserGroupId = grantUserGroupId;
  489. }
  490. const createdPage = await Page.create(pagePath, body, req.user, options);
  491. let savedTags;
  492. if (pageTags != null) {
  493. await PageTagRelation.updatePageTags(createdPage.id, pageTags);
  494. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  495. }
  496. const result = { page: serializeToObj(createdPage), tags: savedTags };
  497. res.json(ApiResponse.success(result));
  498. // update scopes for descendants
  499. if (overwriteScopesOfDescendants) {
  500. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  501. }
  502. // global notification
  503. try {
  504. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage.path, req.user);
  505. }
  506. catch (err) {
  507. logger.error(err);
  508. }
  509. // user notification
  510. if (isSlackEnabled) {
  511. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  512. }
  513. };
  514. /**
  515. * @api {post} /pages.update Update page
  516. * @apiName UpdatePage
  517. * @apiGroup Page
  518. *
  519. * @apiParam {String} body
  520. * @apiParam {String} page_id
  521. * @apiParam {String} revision_id
  522. * @apiParam {String} grant
  523. *
  524. * In the case of the page exists:
  525. * - If revision_id is specified => update the page,
  526. * - If revision_id is not specified => force update by the new contents.
  527. */
  528. api.update = async function(req, res) {
  529. const pageBody = req.body.body || null;
  530. const pageId = req.body.page_id || null;
  531. const revisionId = req.body.revision_id || null;
  532. const grant = req.body.grant || null;
  533. const grantUserGroupId = req.body.grantUserGroupId || null;
  534. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  535. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  536. const slackChannels = req.body.slackChannels || null;
  537. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  538. const socketClientId = req.body.socketClientId || undefined;
  539. const pageTags = req.body.pageTags || undefined;
  540. if (pageId === null || pageBody === null) {
  541. return res.json(ApiResponse.error('page_id and body are required.'));
  542. }
  543. // check page existence
  544. const isExist = await Page.count({ _id: pageId }) > 0;
  545. if (!isExist) {
  546. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  547. }
  548. // check revision
  549. let page = await Page.findByIdAndViewer(pageId, req.user);
  550. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  551. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  552. }
  553. const options = { isSyncRevisionToHackmd, socketClientId };
  554. if (grant != null) {
  555. options.grant = grant;
  556. options.grantUserGroupId = grantUserGroupId;
  557. }
  558. const Revision = crowi.model('Revision');
  559. const previousRevision = await Revision.findById(revisionId);
  560. try {
  561. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  562. }
  563. catch (err) {
  564. logger.error('error on _api/pages.update', err);
  565. return res.json(ApiResponse.error(err));
  566. }
  567. let savedTags;
  568. if (pageTags != null) {
  569. await PageTagRelation.updatePageTags(pageId, pageTags);
  570. savedTags = await PageTagRelation.listTagNamesByPage(pageId);
  571. }
  572. const result = { page: serializeToObj(page), tags: savedTags };
  573. res.json(ApiResponse.success(result));
  574. // update scopes for descendants
  575. if (overwriteScopesOfDescendants) {
  576. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  577. }
  578. // global notification
  579. try {
  580. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_EDIT, page.path, req.user);
  581. }
  582. catch (err) {
  583. logger.error(err);
  584. }
  585. // user notification
  586. if (isSlackEnabled) {
  587. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  588. }
  589. };
  590. /**
  591. * @api {get} /pages.get Get page data
  592. * @apiName GetPage
  593. * @apiGroup Page
  594. *
  595. * @apiParam {String} page_id
  596. * @apiParam {String} path
  597. * @apiParam {String} revision_id
  598. */
  599. api.get = async function(req, res) {
  600. const pagePath = req.query.path || null;
  601. const pageId = req.query.page_id || null; // TODO: handling
  602. if (!pageId && !pagePath) {
  603. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  604. }
  605. let page;
  606. try {
  607. if (pageId) { // prioritized
  608. page = await Page.findByIdAndViewer(pageId, req.user);
  609. }
  610. else if (pagePath) {
  611. page = await Page.findByPathAndViewer(pagePath, req.user);
  612. }
  613. if (page == null) {
  614. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  615. }
  616. page.initLatestRevisionField();
  617. // populate
  618. page = await page.populateDataToShowRevision();
  619. }
  620. catch (err) {
  621. return res.json(ApiResponse.error(err));
  622. }
  623. const result = {};
  624. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  625. return res.json(ApiResponse.success(result));
  626. };
  627. /**
  628. * @api {get} /pages.exist Get if page exists
  629. * @apiName GetPage
  630. * @apiGroup Page
  631. *
  632. * @apiParam {String} pages (stringified JSON)
  633. */
  634. api.exist = async function(req, res) {
  635. const pagesAsObj = JSON.parse(req.query.pages || '{}');
  636. const pagePaths = Object.keys(pagesAsObj);
  637. await Promise.all(pagePaths.map(async(path) => {
  638. // check page existence
  639. const isExist = await Page.count({ path }) > 0;
  640. pagesAsObj[path] = isExist;
  641. return;
  642. }));
  643. const result = { pages: pagesAsObj };
  644. return res.json(ApiResponse.success(result));
  645. };
  646. /**
  647. * @api {get} /pages.getPageTag get page tags
  648. * @apiName GetPageTag
  649. * @apiGroup Page
  650. *
  651. * @apiParam {String} pageId
  652. */
  653. api.getPageTag = async function(req, res) {
  654. const result = {};
  655. try {
  656. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  657. }
  658. catch (err) {
  659. return res.json(ApiResponse.error(err));
  660. }
  661. return res.json(ApiResponse.success(result));
  662. };
  663. /**
  664. * @api {post} /pages.seen Mark as seen user
  665. * @apiName SeenPage
  666. * @apiGroup Page
  667. *
  668. * @apiParam {String} page_id Page Id.
  669. */
  670. api.seen = async function(req, res) {
  671. const user = req.user;
  672. const pageId = req.body.page_id;
  673. if (!pageId) {
  674. return res.json(ApiResponse.error('page_id required'));
  675. }
  676. if (!req.user) {
  677. return res.json(ApiResponse.error('user required'));
  678. }
  679. let page;
  680. try {
  681. page = await Page.findByIdAndViewer(pageId, user);
  682. if (user != null) {
  683. page = await page.seen(user);
  684. }
  685. }
  686. catch (err) {
  687. debug('Seen user update error', err);
  688. return res.json(ApiResponse.error(err));
  689. }
  690. const result = {};
  691. result.seenUser = page.seenUsers;
  692. return res.json(ApiResponse.success(result));
  693. };
  694. /**
  695. * @api {post} /likes.add Like page
  696. * @apiName LikePage
  697. * @apiGroup Page
  698. *
  699. * @apiParam {String} page_id Page Id.
  700. */
  701. api.like = async function(req, res) {
  702. const pageId = req.body.page_id;
  703. if (!pageId) {
  704. return res.json(ApiResponse.error('page_id required'));
  705. }
  706. if (!req.user) {
  707. return res.json(ApiResponse.error('user required'));
  708. }
  709. let page;
  710. try {
  711. page = await Page.findByIdAndViewer(pageId, req.user);
  712. if (page == null) {
  713. throw new Error(`Page '${pageId}' is not found or forbidden`);
  714. }
  715. page = await page.like(req.user);
  716. }
  717. catch (err) {
  718. debug('Seen user update error', err);
  719. return res.json(ApiResponse.error(err));
  720. }
  721. const result = { page };
  722. result.seenUser = page.seenUsers;
  723. res.json(ApiResponse.success(result));
  724. try {
  725. // global notification
  726. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_LIKE, page.path, req.user);
  727. }
  728. catch (err) {
  729. logger.error('Like failed', err);
  730. }
  731. };
  732. /**
  733. * @api {post} /likes.remove Unlike page
  734. * @apiName UnlikePage
  735. * @apiGroup Page
  736. *
  737. * @apiParam {String} page_id Page Id.
  738. */
  739. api.unlike = async function(req, res) {
  740. const pageId = req.body.page_id;
  741. if (!pageId) {
  742. return res.json(ApiResponse.error('page_id required'));
  743. }
  744. if (req.user == null) {
  745. return res.json(ApiResponse.error('user required'));
  746. }
  747. let page;
  748. try {
  749. page = await Page.findByIdAndViewer(pageId, req.user);
  750. if (page == null) {
  751. throw new Error(`Page '${pageId}' is not found or forbidden`);
  752. }
  753. page = await page.unlike(req.user);
  754. }
  755. catch (err) {
  756. debug('Seen user update error', err);
  757. return res.json(ApiResponse.error(err));
  758. }
  759. const result = { page };
  760. result.seenUser = page.seenUsers;
  761. return res.json(ApiResponse.success(result));
  762. };
  763. /**
  764. * @api {get} /pages.updatePost
  765. * @apiName Get UpdatePost setting list
  766. * @apiGroup Page
  767. *
  768. * @apiParam {String} path
  769. */
  770. api.getUpdatePost = function(req, res) {
  771. const path = req.query.path;
  772. const UpdatePost = crowi.model('UpdatePost');
  773. if (!path) {
  774. return res.json(ApiResponse.error({}));
  775. }
  776. UpdatePost.findSettingsByPath(path)
  777. .then((data) => {
  778. // eslint-disable-next-line no-param-reassign
  779. data = data.map((e) => {
  780. return e.channel;
  781. });
  782. debug('Found updatePost data', data);
  783. const result = { updatePost: data };
  784. return res.json(ApiResponse.success(result));
  785. })
  786. .catch((err) => {
  787. debug('Error occured while get setting', err);
  788. return res.json(ApiResponse.error({}));
  789. });
  790. };
  791. /**
  792. * @api {post} /pages.remove Remove page
  793. * @apiName RemovePage
  794. * @apiGroup Page
  795. *
  796. * @apiParam {String} page_id Page Id.
  797. * @apiParam {String} revision_id
  798. */
  799. api.remove = async function(req, res) {
  800. const pageId = req.body.page_id;
  801. const previousRevision = req.body.revision_id || null;
  802. const socketClientId = req.body.socketClientId || undefined;
  803. // get completely flag
  804. const isCompletely = (req.body.completely != null);
  805. // get recursively flag
  806. const isRecursively = (req.body.recursively != null);
  807. const options = { socketClientId };
  808. let page = await Page.findByIdAndViewer(pageId, req.user);
  809. if (page == null) {
  810. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  811. }
  812. debug('Delete page', page._id, page.path);
  813. try {
  814. if (isCompletely) {
  815. if (!req.user.canDeleteCompletely(page.creator)) {
  816. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  817. }
  818. if (isRecursively) {
  819. page = await Page.completelyDeletePageRecursively(page, req.user, options);
  820. }
  821. else {
  822. page = await Page.completelyDeletePage(page, req.user, options);
  823. }
  824. }
  825. else {
  826. if (!page.isUpdatable(previousRevision)) {
  827. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  828. }
  829. if (isRecursively) {
  830. page = await Page.deletePageRecursively(page, req.user, options);
  831. }
  832. else {
  833. page = await Page.deletePage(page, req.user, options);
  834. }
  835. }
  836. }
  837. catch (err) {
  838. logger.error('Error occured while get setting', err);
  839. return res.json(ApiResponse.error('Failed to delete page.', 'unknown'));
  840. }
  841. debug('Page deleted', page.path);
  842. const result = {};
  843. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  844. res.json(ApiResponse.success(result));
  845. // global notification
  846. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page.path, req.user);
  847. };
  848. /**
  849. * @api {post} /pages.revertRemove Revert removed page
  850. * @apiName RevertRemovePage
  851. * @apiGroup Page
  852. *
  853. * @apiParam {String} page_id Page Id.
  854. */
  855. api.revertRemove = async function(req, res, options) {
  856. const pageId = req.body.page_id;
  857. const socketClientId = req.body.socketClientId || undefined;
  858. // get recursively flag
  859. const isRecursively = (req.body.recursively !== undefined);
  860. let page;
  861. try {
  862. page = await Page.findByIdAndViewer(pageId, req.user);
  863. if (page == null) {
  864. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  865. }
  866. if (isRecursively) {
  867. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  868. }
  869. else {
  870. page = await Page.revertDeletedPage(page, req.user, { socketClientId });
  871. }
  872. }
  873. catch (err) {
  874. logger.error('Error occured while get setting', err);
  875. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  876. }
  877. const result = {};
  878. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  879. return res.json(ApiResponse.success(result));
  880. };
  881. /**
  882. * @api {post} /pages.rename Rename page
  883. * @apiName RenamePage
  884. * @apiGroup Page
  885. *
  886. * @apiParam {String} page_id Page Id.
  887. * @apiParam {String} path
  888. * @apiParam {String} revision_id
  889. * @apiParam {String} new_path New path name.
  890. * @apiParam {Bool} create_redirect
  891. */
  892. api.rename = async function(req, res) {
  893. const pageId = req.body.page_id;
  894. const previousRevision = req.body.revision_id || null;
  895. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  896. const options = {
  897. createRedirectPage: (req.body.create_redirect != null),
  898. updateMetadata: (req.body.remain_metadata == null),
  899. socketClientId: +req.body.socketClientId || undefined,
  900. };
  901. const isRecursively = (req.body.recursively != null);
  902. if (!Page.isCreatableName(newPagePath)) {
  903. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  904. }
  905. const isExist = await Page.count({ path: newPagePath }) > 0;
  906. if (isExist) {
  907. // if page found, cannot cannot rename to that path
  908. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  909. }
  910. let page;
  911. try {
  912. page = await Page.findByIdAndViewer(pageId, req.user);
  913. if (page == null) {
  914. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  915. }
  916. if (!page.isUpdatable(previousRevision)) {
  917. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  918. }
  919. if (isRecursively) {
  920. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  921. }
  922. else {
  923. page = await Page.rename(page, newPagePath, req.user, options);
  924. }
  925. }
  926. catch (err) {
  927. logger.error(err);
  928. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  929. }
  930. const result = {};
  931. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  932. res.json(ApiResponse.success(result));
  933. // global notification
  934. globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_MOVE, page.path, req.user, {
  935. oldPath: req.body.path,
  936. });
  937. return page;
  938. };
  939. /**
  940. * @api {post} /pages.duplicate Duplicate page
  941. * @apiName DuplicatePage
  942. * @apiGroup Page
  943. *
  944. * @apiParam {String} page_id Page Id.
  945. * @apiParam {String} new_path New path name.
  946. */
  947. api.duplicate = async function(req, res) {
  948. const pageId = req.body.page_id;
  949. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  950. const page = await Page.findByIdAndViewer(pageId, req.user);
  951. if (page == null) {
  952. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  953. }
  954. await page.populateDataToShowRevision();
  955. const originTags = await page.findRelatedTagsById();
  956. req.body.path = newPagePath;
  957. req.body.body = page.revision.body;
  958. req.body.grant = page.grant;
  959. req.body.grantedUsers = page.grantedUsers;
  960. req.body.grantUserGroupId = page.grantedGroup;
  961. req.body.pageTags = originTags;
  962. return api.create(req, res);
  963. };
  964. /**
  965. * @api {post} /pages.unlink Remove the redirecting page
  966. * @apiName UnlinkPage
  967. * @apiGroup Page
  968. *
  969. * @apiParam {String} page_id Page Id.
  970. * @apiParam {String} revision_id
  971. */
  972. api.unlink = async function(req, res) {
  973. const path = req.body.path;
  974. try {
  975. await Page.removeRedirectOriginPageByPath(path);
  976. logger.debug('Redirect Page deleted', path);
  977. }
  978. catch (err) {
  979. logger.error('Error occured while get setting', err);
  980. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  981. }
  982. const result = { path };
  983. return res.json(ApiResponse.success(result));
  984. };
  985. api.recentCreated = async function(req, res) {
  986. const pageId = req.query.page_id;
  987. if (pageId == null) {
  988. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  989. }
  990. const page = await Page.findById(pageId);
  991. if (page == null) {
  992. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  993. }
  994. if (!isUserPage(page.path)) {
  995. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  996. }
  997. const limit = +req.query.limit || 50;
  998. const offset = +req.query.offset || 0;
  999. const queryOptions = { offset, limit };
  1000. try {
  1001. const result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  1002. result.pages = pathUtils.encodePagesPath(result.pages);
  1003. return res.json(ApiResponse.success(result));
  1004. }
  1005. catch (err) {
  1006. return res.json(ApiResponse.error(err));
  1007. }
  1008. };
  1009. return actions;
  1010. };