page.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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 = {
  468. grant, grantUserGroupId, overwriteScopesOfDescendants, socketClientId, pageTags,
  469. };
  470. const createdPage = await Page.create(pagePath, body, req.user, options);
  471. const result = { page: serializeToObj(createdPage) };
  472. result.page.lastUpdateUser = User.filterToPublicFields(createdPage.lastUpdateUser);
  473. result.page.creator = User.filterToPublicFields(createdPage.creator);
  474. res.json(ApiResponse.success(result));
  475. // update scopes for descendants
  476. if (overwriteScopesOfDescendants) {
  477. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  478. }
  479. // global notification
  480. try {
  481. await globalNotificationService.notifyPageCreate(createdPage);
  482. }
  483. catch (err) {
  484. logger.error(err);
  485. }
  486. // user notification
  487. if (isSlackEnabled && slackChannels != null) {
  488. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  489. }
  490. };
  491. /**
  492. * @api {post} /pages.update Update page
  493. * @apiName UpdatePage
  494. * @apiGroup Page
  495. *
  496. * @apiParam {String} body
  497. * @apiParam {String} page_id
  498. * @apiParam {String} revision_id
  499. * @apiParam {String} grant
  500. *
  501. * In the case of the page exists:
  502. * - If revision_id is specified => update the page,
  503. * - If revision_id is not specified => force update by the new contents.
  504. */
  505. api.update = async function(req, res) {
  506. const pageBody = req.body.body || null;
  507. const pageId = req.body.page_id || null;
  508. const revisionId = req.body.revision_id || null;
  509. const grant = req.body.grant || null;
  510. const grantUserGroupId = req.body.grantUserGroupId || null;
  511. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  512. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  513. const slackChannels = req.body.slackChannels || null;
  514. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  515. const socketClientId = req.body.socketClientId || undefined;
  516. const pageTags = req.body.pageTags || undefined;
  517. if (pageId === null || pageBody === null) {
  518. return res.json(ApiResponse.error('page_id and body are required.'));
  519. }
  520. // check page existence
  521. const isExist = await Page.count({ _id: pageId }) > 0;
  522. if (!isExist) {
  523. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  524. }
  525. // check revision
  526. let page = await Page.findByIdAndViewer(pageId, req.user);
  527. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  528. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  529. }
  530. const options = { isSyncRevisionToHackmd, socketClientId, pageTags };
  531. if (grant != null) {
  532. options.grant = grant;
  533. }
  534. if (grantUserGroupId != null) {
  535. options.grantUserGroupId = grantUserGroupId;
  536. }
  537. const Revision = crowi.model('Revision');
  538. const previousRevision = await Revision.findById(revisionId);
  539. try {
  540. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  541. }
  542. catch (err) {
  543. logger.error('error on _api/pages.update', err);
  544. return res.json(ApiResponse.error(err));
  545. }
  546. const result = { page: serializeToObj(page) };
  547. result.page.lastUpdateUser = User.filterToPublicFields(page.lastUpdateUser);
  548. res.json(ApiResponse.success(result));
  549. // update scopes for descendants
  550. if (overwriteScopesOfDescendants) {
  551. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  552. }
  553. // global notification
  554. try {
  555. await globalNotificationService.notifyPageEdit(page);
  556. }
  557. catch (err) {
  558. logger.error(err);
  559. }
  560. // user notification
  561. if (isSlackEnabled && slackChannels != null) {
  562. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  563. }
  564. };
  565. /**
  566. * @api {get} /pages.get Get page data
  567. * @apiName GetPage
  568. * @apiGroup Page
  569. *
  570. * @apiParam {String} page_id
  571. * @apiParam {String} path
  572. * @apiParam {String} revision_id
  573. */
  574. api.get = async function(req, res) {
  575. const pagePath = req.query.path || null;
  576. const pageId = req.query.page_id || null; // TODO: handling
  577. if (!pageId && !pagePath) {
  578. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  579. }
  580. let page;
  581. try {
  582. if (pageId) { // prioritized
  583. page = await Page.findByIdAndViewer(pageId, req.user);
  584. }
  585. else if (pagePath) {
  586. page = await Page.findByPathAndViewer(pagePath, req.user);
  587. }
  588. if (page == null) {
  589. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  590. }
  591. page.initLatestRevisionField();
  592. // populate
  593. page = await page.populateDataToShowRevision();
  594. }
  595. catch (err) {
  596. return res.json(ApiResponse.error(err));
  597. }
  598. const result = {};
  599. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  600. return res.json(ApiResponse.success(result));
  601. };
  602. /**
  603. * @api {get} /pages.exist Get if page exists
  604. * @apiName GetPage
  605. * @apiGroup Page
  606. *
  607. * @apiParam {String} pages (stringified JSON)
  608. */
  609. api.exist = async function(req, res) {
  610. const pagesAsObj = JSON.parse(req.query.pages || '{}');
  611. const pagePaths = Object.keys(pagesAsObj);
  612. await Promise.all(pagePaths.map(async(path) => {
  613. // check page existence
  614. const isExist = await Page.count({ path }) > 0;
  615. pagesAsObj[path] = isExist;
  616. return;
  617. }));
  618. const result = { pages: pagesAsObj };
  619. return res.json(ApiResponse.success(result));
  620. };
  621. /**
  622. * @api {get} /pages.getPageTag get page tags
  623. * @apiName GetPageTag
  624. * @apiGroup Page
  625. *
  626. * @apiParam {String} pageId
  627. */
  628. api.getPageTag = async function(req, res) {
  629. const result = {};
  630. try {
  631. const tags = await PageTagRelation.find({ relatedPage: req.query.pageId }).populate('relatedTag').select('-_id relatedTag');
  632. result.tags = tags.map((tag) => { return tag.relatedTag.name });
  633. }
  634. catch (err) {
  635. return res.json(ApiResponse.error(err));
  636. }
  637. return res.json(ApiResponse.success(result));
  638. };
  639. /**
  640. * @api {post} /pages.seen Mark as seen user
  641. * @apiName SeenPage
  642. * @apiGroup Page
  643. *
  644. * @apiParam {String} page_id Page Id.
  645. */
  646. api.seen = async function(req, res) {
  647. const user = req.user;
  648. const pageId = req.body.page_id;
  649. if (!pageId) {
  650. return res.json(ApiResponse.error('page_id required'));
  651. }
  652. if (!req.user) {
  653. return res.json(ApiResponse.error('user required'));
  654. }
  655. let page;
  656. try {
  657. page = await Page.findByIdAndViewer(pageId, user);
  658. if (user != null) {
  659. page = await page.seen(user);
  660. }
  661. }
  662. catch (err) {
  663. debug('Seen user update error', err);
  664. return res.json(ApiResponse.error(err));
  665. }
  666. const result = {};
  667. result.seenUser = page.seenUsers;
  668. return res.json(ApiResponse.success(result));
  669. };
  670. /**
  671. * @api {post} /likes.add Like page
  672. * @apiName LikePage
  673. * @apiGroup Page
  674. *
  675. * @apiParam {String} page_id Page Id.
  676. */
  677. api.like = async function(req, res) {
  678. const pageId = req.body.page_id;
  679. if (!pageId) {
  680. return res.json(ApiResponse.error('page_id required'));
  681. }
  682. if (!req.user) {
  683. return res.json(ApiResponse.error('user required'));
  684. }
  685. let page;
  686. try {
  687. page = await Page.findByIdAndViewer(pageId, req.user);
  688. if (page == null) {
  689. throw new Error(`Page '${pageId}' is not found or forbidden`);
  690. }
  691. page = await page.like(req.user);
  692. }
  693. catch (err) {
  694. debug('Seen user update error', err);
  695. return res.json(ApiResponse.error(err));
  696. }
  697. const result = { page };
  698. result.seenUser = page.seenUsers;
  699. res.json(ApiResponse.success(result));
  700. try {
  701. // global notification
  702. globalNotificationService.notifyPageLike(page, req.user);
  703. }
  704. catch (err) {
  705. logger.error('Like failed', err);
  706. }
  707. };
  708. /**
  709. * @api {post} /likes.remove Unlike page
  710. * @apiName UnlikePage
  711. * @apiGroup Page
  712. *
  713. * @apiParam {String} page_id Page Id.
  714. */
  715. api.unlike = async function(req, res) {
  716. const pageId = req.body.page_id;
  717. if (!pageId) {
  718. return res.json(ApiResponse.error('page_id required'));
  719. }
  720. if (req.user == null) {
  721. return res.json(ApiResponse.error('user required'));
  722. }
  723. let page;
  724. try {
  725. page = await Page.findByIdAndViewer(pageId, req.user);
  726. if (page == null) {
  727. throw new Error(`Page '${pageId}' is not found or forbidden`);
  728. }
  729. page = await page.unlike(req.user);
  730. }
  731. catch (err) {
  732. debug('Seen user update error', err);
  733. return res.json(ApiResponse.error(err));
  734. }
  735. const result = { page };
  736. result.seenUser = page.seenUsers;
  737. return res.json(ApiResponse.success(result));
  738. };
  739. /**
  740. * @api {get} /pages.updatePost
  741. * @apiName Get UpdatePost setting list
  742. * @apiGroup Page
  743. *
  744. * @apiParam {String} path
  745. */
  746. api.getUpdatePost = function(req, res) {
  747. const path = req.query.path;
  748. const UpdatePost = crowi.model('UpdatePost');
  749. if (!path) {
  750. return res.json(ApiResponse.error({}));
  751. }
  752. UpdatePost.findSettingsByPath(path)
  753. .then((data) => {
  754. // eslint-disable-next-line no-param-reassign
  755. data = data.map((e) => {
  756. return e.channel;
  757. });
  758. debug('Found updatePost data', data);
  759. const result = { updatePost: data };
  760. return res.json(ApiResponse.success(result));
  761. })
  762. .catch((err) => {
  763. debug('Error occured while get setting', err);
  764. return res.json(ApiResponse.error({}));
  765. });
  766. };
  767. /**
  768. * @api {post} /pages.remove Remove page
  769. * @apiName RemovePage
  770. * @apiGroup Page
  771. *
  772. * @apiParam {String} page_id Page Id.
  773. * @apiParam {String} revision_id
  774. */
  775. api.remove = async function(req, res) {
  776. const pageId = req.body.page_id;
  777. const previousRevision = req.body.revision_id || null;
  778. const socketClientId = req.body.socketClientId || undefined;
  779. // get completely flag
  780. const isCompletely = (req.body.completely != null);
  781. // get recursively flag
  782. const isRecursively = (req.body.recursively != null);
  783. const options = { socketClientId };
  784. let page = await Page.findByIdAndViewer(pageId, req.user);
  785. if (page == null) {
  786. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  787. }
  788. debug('Delete page', page._id, page.path);
  789. try {
  790. if (isCompletely) {
  791. // get useradmin flag
  792. const isDeniedCompletelyDelete = !req.user.admin;
  793. if (isDeniedCompletelyDelete) {
  794. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  795. }
  796. if (isRecursively) {
  797. page = await Page.completelyDeletePageRecursively(page, req.user, options);
  798. }
  799. else {
  800. page = await Page.completelyDeletePage(page, req.user, options);
  801. }
  802. }
  803. else {
  804. if (!page.isUpdatable(previousRevision)) {
  805. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  806. }
  807. if (isRecursively) {
  808. page = await Page.deletePageRecursively(page, req.user, options);
  809. }
  810. else {
  811. page = await Page.deletePage(page, req.user, options);
  812. }
  813. }
  814. }
  815. catch (err) {
  816. logger.error('Error occured while get setting', err);
  817. return res.json(ApiResponse.error('Failed to delete page.', 'unknown'));
  818. }
  819. debug('Page deleted', page.path);
  820. const result = {};
  821. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  822. res.json(ApiResponse.success(result));
  823. // global notification
  824. return globalNotificationService.notifyPageDelete(page);
  825. };
  826. /**
  827. * @api {post} /pages.revertRemove Revert removed page
  828. * @apiName RevertRemovePage
  829. * @apiGroup Page
  830. *
  831. * @apiParam {String} page_id Page Id.
  832. */
  833. api.revertRemove = async function(req, res, options) {
  834. const pageId = req.body.page_id;
  835. const socketClientId = req.body.socketClientId || undefined;
  836. // get recursively flag
  837. const isRecursively = (req.body.recursively !== undefined);
  838. let page;
  839. try {
  840. page = await Page.findByIdAndViewer(pageId, req.user);
  841. if (page == null) {
  842. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  843. }
  844. if (isRecursively) {
  845. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  846. }
  847. else {
  848. page = await Page.revertDeletedPage(page, req.user, { socketClientId });
  849. }
  850. }
  851. catch (err) {
  852. logger.error('Error occured while get setting', err);
  853. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  854. }
  855. const result = {};
  856. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  857. return res.json(ApiResponse.success(result));
  858. };
  859. /**
  860. * @api {post} /pages.rename Rename page
  861. * @apiName RenamePage
  862. * @apiGroup Page
  863. *
  864. * @apiParam {String} page_id Page Id.
  865. * @apiParam {String} path
  866. * @apiParam {String} revision_id
  867. * @apiParam {String} new_path New path name.
  868. * @apiParam {Bool} create_redirect
  869. */
  870. api.rename = async function(req, res) {
  871. const pageId = req.body.page_id;
  872. const previousRevision = req.body.revision_id || null;
  873. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  874. const options = {
  875. createRedirectPage: req.body.create_redirect || 0,
  876. moveUnderTrees: req.body.move_trees || 0,
  877. socketClientId: +req.body.socketClientId || undefined,
  878. };
  879. const isRecursively = req.body.recursively || 0;
  880. if (!Page.isCreatableName(newPagePath)) {
  881. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  882. }
  883. const isExist = await Page.count({ path: newPagePath }) > 0;
  884. if (isExist) {
  885. // if page found, cannot cannot rename to that path
  886. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  887. }
  888. let page;
  889. try {
  890. page = await Page.findByIdAndViewer(pageId, req.user);
  891. if (page == null) {
  892. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  893. }
  894. if (!page.isUpdatable(previousRevision)) {
  895. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  896. }
  897. if (isRecursively) {
  898. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  899. }
  900. else {
  901. page = await Page.rename(page, newPagePath, req.user, options);
  902. }
  903. }
  904. catch (err) {
  905. logger.error(err);
  906. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  907. }
  908. const result = {};
  909. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  910. res.json(ApiResponse.success(result));
  911. // global notification
  912. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  913. return page;
  914. };
  915. /**
  916. * @api {post} /pages.duplicate Duplicate page
  917. * @apiName DuplicatePage
  918. * @apiGroup Page
  919. *
  920. * @apiParam {String} page_id Page Id.
  921. * @apiParam {String} new_path New path name.
  922. */
  923. api.duplicate = async function(req, res) {
  924. const pageId = req.body.page_id;
  925. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  926. const page = await Page.findByIdAndViewer(pageId, req.user);
  927. if (page == null) {
  928. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  929. }
  930. await page.populateDataToShowRevision();
  931. const originTags = await page.findRelatedTagsById();
  932. req.body.path = newPagePath;
  933. req.body.body = page.revision.body;
  934. req.body.grant = page.grant;
  935. req.body.pageTags = originTags;
  936. return api.create(req, res);
  937. };
  938. /**
  939. * @api {post} /pages.unlink Remove the redirecting page
  940. * @apiName UnlinkPage
  941. * @apiGroup Page
  942. *
  943. * @apiParam {String} page_id Page Id.
  944. * @apiParam {String} revision_id
  945. */
  946. api.unlink = async function(req, res) {
  947. const path = req.body.path;
  948. try {
  949. await Page.removeRedirectOriginPageByPath(path);
  950. logger.debug('Redirect Page deleted', path);
  951. }
  952. catch (err) {
  953. logger.error('Error occured while get setting', err);
  954. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  955. }
  956. const result = { path };
  957. return res.json(ApiResponse.success(result));
  958. };
  959. api.recentCreated = async function(req, res) {
  960. const pageId = req.query.page_id;
  961. if (pageId == null) {
  962. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  963. }
  964. const page = await Page.findById(pageId);
  965. if (page == null) {
  966. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  967. }
  968. if (!isUserPage(page.path)) {
  969. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  970. }
  971. const limit = +req.query.limit || 50;
  972. const offset = +req.query.offset || 0;
  973. const queryOptions = { offset, limit };
  974. try {
  975. const result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  976. result.pages = pathUtils.encodePagesPath(result.pages);
  977. return res.json(ApiResponse.success(result));
  978. }
  979. catch (err) {
  980. return res.json(ApiResponse.error(err));
  981. }
  982. };
  983. return actions;
  984. };