page.js 35 KB

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