page.js 35 KB

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