page.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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 != null) {
  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. if (isRecursively) {
  792. page = await Page.completelyDeletePageRecursively(page, req.user, options);
  793. }
  794. else {
  795. page = await Page.completelyDeletePage(page, req.user, options);
  796. }
  797. }
  798. else {
  799. if (!page.isUpdatable(previousRevision)) {
  800. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  801. }
  802. if (isRecursively) {
  803. page = await Page.deletePageRecursively(page, req.user, options);
  804. }
  805. else {
  806. page = await Page.deletePage(page, req.user, options);
  807. }
  808. }
  809. }
  810. catch (err) {
  811. logger.error('Error occured while get setting', err);
  812. return res.json(ApiResponse.error('Failed to delete page.', 'unknown'));
  813. }
  814. debug('Page deleted', page.path);
  815. const result = {};
  816. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  817. res.json(ApiResponse.success(result));
  818. // global notification
  819. return globalNotificationService.notifyPageDelete(page);
  820. };
  821. /**
  822. * @api {post} /pages.revertRemove Revert removed page
  823. * @apiName RevertRemovePage
  824. * @apiGroup Page
  825. *
  826. * @apiParam {String} page_id Page Id.
  827. */
  828. api.revertRemove = async function(req, res, options) {
  829. const pageId = req.body.page_id;
  830. const socketClientId = req.body.socketClientId || undefined;
  831. // get recursively flag
  832. const isRecursively = (req.body.recursively !== undefined);
  833. let page;
  834. try {
  835. page = await Page.findByIdAndViewer(pageId, req.user);
  836. if (page == null) {
  837. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  838. }
  839. if (isRecursively) {
  840. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  841. }
  842. else {
  843. page = await Page.revertDeletedPage(page, req.user, { socketClientId });
  844. }
  845. }
  846. catch (err) {
  847. logger.error('Error occured while get setting', err);
  848. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  849. }
  850. const result = {};
  851. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  852. return res.json(ApiResponse.success(result));
  853. };
  854. /**
  855. * @api {post} /pages.rename Rename page
  856. * @apiName RenamePage
  857. * @apiGroup Page
  858. *
  859. * @apiParam {String} page_id Page Id.
  860. * @apiParam {String} path
  861. * @apiParam {String} revision_id
  862. * @apiParam {String} new_path New path name.
  863. * @apiParam {Bool} create_redirect
  864. */
  865. api.rename = async function(req, res) {
  866. const pageId = req.body.page_id;
  867. const previousRevision = req.body.revision_id || null;
  868. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  869. const options = {
  870. createRedirectPage: req.body.create_redirect || 0,
  871. moveUnderTrees: req.body.move_trees || 0,
  872. socketClientId: +req.body.socketClientId || undefined,
  873. };
  874. const isRecursively = req.body.recursively || 0;
  875. if (!Page.isCreatableName(newPagePath)) {
  876. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  877. }
  878. const isExist = await Page.count({ path: newPagePath }) > 0;
  879. if (isExist) {
  880. // if page found, cannot cannot rename to that path
  881. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  882. }
  883. let page;
  884. try {
  885. page = await Page.findByIdAndViewer(pageId, req.user);
  886. if (page == null) {
  887. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  888. }
  889. if (!page.isUpdatable(previousRevision)) {
  890. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  891. }
  892. if (isRecursively) {
  893. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  894. }
  895. else {
  896. page = await Page.rename(page, newPagePath, req.user, options);
  897. }
  898. }
  899. catch (err) {
  900. logger.error(err);
  901. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  902. }
  903. const result = {};
  904. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  905. res.json(ApiResponse.success(result));
  906. // global notification
  907. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  908. return page;
  909. };
  910. /**
  911. * @api {post} /pages.duplicate Duplicate page
  912. * @apiName DuplicatePage
  913. * @apiGroup Page
  914. *
  915. * @apiParam {String} page_id Page Id.
  916. * @apiParam {String} new_path New path name.
  917. */
  918. api.duplicate = async function(req, res) {
  919. const pageId = req.body.page_id;
  920. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  921. const page = await Page.findByIdAndViewer(pageId, req.user);
  922. if (page == null) {
  923. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  924. }
  925. await page.populateDataToShowRevision();
  926. const originTags = await page.findRelatedTagsById();
  927. req.body.path = newPagePath;
  928. req.body.body = page.revision.body;
  929. req.body.grant = page.grant;
  930. req.body.pageTags = originTags;
  931. return api.create(req, res);
  932. };
  933. /**
  934. * @api {post} /pages.unlink Remove the redirecting page
  935. * @apiName UnlinkPage
  936. * @apiGroup Page
  937. *
  938. * @apiParam {String} page_id Page Id.
  939. * @apiParam {String} revision_id
  940. */
  941. api.unlink = async function(req, res) {
  942. const path = req.body.path;
  943. try {
  944. await Page.removeRedirectOriginPageByPath(path);
  945. logger.debug('Redirect Page deleted', path);
  946. }
  947. catch (err) {
  948. logger.error('Error occured while get setting', err);
  949. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  950. }
  951. const result = { path };
  952. return res.json(ApiResponse.success(result));
  953. };
  954. api.recentCreated = async function(req, res) {
  955. const pageId = req.query.page_id;
  956. if (pageId == null) {
  957. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  958. }
  959. const page = await Page.findById(pageId);
  960. if (page == null) {
  961. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  962. }
  963. if (!isUserPage(page.path)) {
  964. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  965. }
  966. const limit = +req.query.limit || 50;
  967. const offset = +req.query.offset || 0;
  968. const queryOptions = { offset, limit };
  969. try {
  970. const result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  971. result.pages = pathUtils.encodePagesPath(result.pages);
  972. return res.json(ApiResponse.success(result));
  973. }
  974. catch (err) {
  975. return res.json(ApiResponse.error(err));
  976. }
  977. };
  978. return actions;
  979. };