page.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. const debug = require('debug')('growi:routes:page')
  4. , logger = require('@alias/logger')('growi:routes:page')
  5. , pagePathUtils = require('@commons/util/page-path-utils')
  6. , Page = crowi.model('Page')
  7. , User = crowi.model('User')
  8. , Config = crowi.model('Config')
  9. , config = crowi.getConfig()
  10. , Bookmark = crowi.model('Bookmark')
  11. , UpdatePost = crowi.model('UpdatePost')
  12. , ApiResponse = require('../util/apiResponse')
  13. , interceptorManager = crowi.getInterceptorManager()
  14. , swig = require('swig-templates')
  15. , getToday = require('../util/getToday')
  16. , globalNotificationService = crowi.getGlobalNotificationService()
  17. , 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', function(page, user, socketClientId) {
  24. page = serializeToObj(page);
  25. crowi.getIo().sockets.emit('page:create', {page, user, socketClientId});
  26. });
  27. pageEvent.on('update', function(page, user, socketClientId) {
  28. page = serializeToObj(page);
  29. crowi.getIo().sockets.emit('page:update', {page, user, socketClientId});
  30. });
  31. pageEvent.on('delete', function(page, user, socketClientId) {
  32. page = serializeToObj(page);
  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. return returnObj;
  41. }
  42. function getPathFromRequest(req) {
  43. const path = '/' + (req.params[0] || '');
  44. return path.replace(/\.md$/, '');
  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. 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: prev,
  69. next: next,
  70. offset: 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 (crowi.slack) {
  81. const promises = slackChannels.split(',').map(function(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: 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: 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 = pagePathUtils.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. let 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 = Page.addSlashOfEnd(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. else if (page.redirectTo) {
  191. debug(`Redirect to '${page.redirectTo}'`);
  192. return res.redirect(encodeURI(page.redirectTo + '?redirectFrom=' + pagePathUtils.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);
  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. else {
  219. const data = await UpdatePost.findSettingsByPath(page.path);
  220. const channels = data.map(e => e.channel).join(', ');
  221. return channels;
  222. }
  223. };
  224. /**
  225. *
  226. * @param {string} path
  227. * @param {User} user
  228. * @returns {number} PORTAL_STATUS_NOT_EXISTS(0) or PORTAL_STATUS_EXISTS(1) or PORTAL_STATUS_FORBIDDEN(2)
  229. */
  230. async function getPortalPageState(path, user) {
  231. const portalPath = Page.addSlashOfEnd(path);
  232. let page = await Page.findByPathAndViewer(portalPath, user);
  233. if (page == null) {
  234. // check the page is forbidden or just does not exist.
  235. const isForbidden = await Page.count({ path: portalPath }) > 0;
  236. return isForbidden ? PORTAL_STATUS_FORBIDDEN : PORTAL_STATUS_NOT_EXISTS;
  237. }
  238. return PORTAL_STATUS_EXISTS;
  239. }
  240. actions.showTopPage = function(req, res) {
  241. return showPageListForCrowiBehavior(req, res);
  242. };
  243. /**
  244. * switch action by behaviorType
  245. */
  246. actions.showPageWithEndOfSlash = function(req, res, next) {
  247. const behaviorType = Config.behaviorType(config);
  248. if (!behaviorType || 'crowi' === behaviorType) {
  249. return showPageListForCrowiBehavior(req, res, next);
  250. }
  251. else {
  252. let path = getPathFromRequest(req); // end of slash should be omitted
  253. // redirect and showPage action will be triggered
  254. return res.redirect(path);
  255. }
  256. };
  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 || 'crowi' === behaviorType) {
  270. const portalPagePath = Page.addSlashOfEnd(getPathFromRequest(req));
  271. let 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=' + pagePathUtils.encodePagePath(req.path)));
  275. }
  276. }
  277. // delegate to showPageForGrowiBehavior
  278. return showPageForGrowiBehavior(req, res, next);
  279. };
  280. /**
  281. * switch action by behaviorType
  282. */
  283. actions.trashPageListShowWrapper = function(req, res) {
  284. const behaviorType = Config.behaviorType(config);
  285. if (!behaviorType || 'crowi' === behaviorType) {
  286. // Crowi behavior for '/trash/*'
  287. return actions.deletedPageListShow(req, res);
  288. }
  289. else {
  290. // redirect to '/trash'
  291. return res.redirect('/trash');
  292. }
  293. };
  294. /**
  295. * switch action by behaviorType
  296. */
  297. actions.trashPageShowWrapper = function(req, res) {
  298. const behaviorType = Config.behaviorType(config);
  299. if (!behaviorType || 'crowi' === behaviorType) {
  300. // redirect to '/trash/'
  301. return res.redirect('/trash/');
  302. }
  303. else {
  304. // Crowi behavior for '/trash/*'
  305. return actions.deletedPageListShow(req, res);
  306. }
  307. };
  308. /**
  309. * switch action by behaviorType
  310. */
  311. actions.deletedPageListShowWrapper = function(req, res) {
  312. const behaviorType = Config.behaviorType(config);
  313. if (!behaviorType || 'crowi' === behaviorType) {
  314. // Crowi behavior for '/trash/*'
  315. return actions.deletedPageListShow(req, res);
  316. }
  317. else {
  318. const path = '/trash' + getPathFromRequest(req);
  319. return res.redirect(path);
  320. }
  321. };
  322. actions.notFound = async function(req, res) {
  323. const path = getPathFromRequest(req);
  324. let view;
  325. const renderVars = { path };
  326. if (req.isForbidden) {
  327. view = 'customlayout-selector/forbidden';
  328. }
  329. else {
  330. view = 'customlayout-selector/not_found';
  331. // retrieve templates
  332. let template = await Page.findTemplate(path);
  333. if (template != null) {
  334. template = replacePlaceholdersOfTemplate(template, req);
  335. renderVars.template = template;
  336. }
  337. // add scope variables by ancestor page
  338. const ancestor = await Page.findAncestorByPathAndViewer(path, req.user);
  339. if (ancestor != null) {
  340. await ancestor.populate('grantedGroup').execPopulate();
  341. addRendarVarsForScope(renderVars, ancestor);
  342. }
  343. }
  344. const limit = 50;
  345. const offset = parseInt(req.query.offset) || 0;
  346. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit);
  347. return res.render(view, renderVars);
  348. };
  349. actions.deletedPageListShow = async function(req, res) {
  350. const path = '/trash' + getPathFromRequest(req);
  351. const limit = 50;
  352. const offset = parseInt(req.query.offset) || 0;
  353. const queryOptions = {
  354. offset: offset,
  355. limit: limit + 1,
  356. includeTrashed: true,
  357. };
  358. const renderVars = {
  359. page: null,
  360. path: path,
  361. pages: [],
  362. };
  363. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  364. if (result.pages.length > limit) {
  365. result.pages.pop();
  366. }
  367. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  368. renderVars.pages = pagePathUtils.encodePagesPath(result.pages);
  369. res.render('customlayout-selector/page_list', renderVars);
  370. };
  371. /**
  372. * redirector
  373. */
  374. actions.redirector = async function(req, res) {
  375. const id = req.params.id;
  376. const page = await Page.findByIdAndViewer(id, req.user);
  377. if (page != null) {
  378. return res.redirect(pagePathUtils.encodePagePath(page.path));
  379. }
  380. return res.redirect('/');
  381. };
  382. const api = actions.api = {};
  383. /**
  384. * @api {get} /pages.list List pages by user
  385. * @apiName ListPage
  386. * @apiGroup Page
  387. *
  388. * @apiParam {String} path
  389. * @apiParam {String} user
  390. */
  391. api.list = async function(req, res) {
  392. const username = req.query.user || null;
  393. const path = req.query.path || null;
  394. const limit = + req.query.limit || 50;
  395. const offset = parseInt(req.query.offset) || 0;
  396. const queryOptions = { offset, limit: limit + 1 };
  397. // Accepts only one of these
  398. if (username === null && path === null) {
  399. return res.json(ApiResponse.error('Parameter user or path is required.'));
  400. }
  401. if (username !== null && path !== null) {
  402. return res.json(ApiResponse.error('Parameter user or path is required.'));
  403. }
  404. try {
  405. let result = null;
  406. if (path == null) {
  407. const user = await User.findUserByUsername(username);
  408. if (user === null) {
  409. throw new Error('The user not found.');
  410. }
  411. result = await Page.findListByCreator(user, req.user, queryOptions);
  412. }
  413. else {
  414. result = await Page.findListByStartWith(path, req.user, queryOptions);
  415. }
  416. if (result.pages.length > limit) {
  417. result.pages.pop();
  418. }
  419. result.pages = pagePathUtils.encodePagesPath(result.pages);
  420. return res.json(ApiResponse.success(result));
  421. }
  422. catch (err) {
  423. return res.json(ApiResponse.error(err));
  424. }
  425. };
  426. /**
  427. * @api {post} /pages.create Create new page
  428. * @apiName CreatePage
  429. * @apiGroup Page
  430. *
  431. * @apiParam {String} body
  432. * @apiParam {String} path
  433. * @apiParam {String} grant
  434. */
  435. api.create = async function(req, res) {
  436. const body = req.body.body || null;
  437. const pagePath = req.body.path || null;
  438. const grant = req.body.grant || null;
  439. const grantUserGroupId = req.body.grantUserGroupId || null;
  440. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  441. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  442. const slackChannels = req.body.slackChannels || null;
  443. const socketClientId = req.body.socketClientId || undefined;
  444. if (body === null || pagePath === null) {
  445. return res.json(ApiResponse.error('Parameters body and path are required.'));
  446. }
  447. // check page existence
  448. const isExist = await Page.count({path: pagePath}) > 0;
  449. if (isExist) {
  450. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  451. }
  452. const options = {grant, grantUserGroupId, overwriteScopesOfDescendants, socketClientId};
  453. const createdPage = await Page.create(pagePath, body, req.user, options);
  454. const result = { page: serializeToObj(createdPage) };
  455. result.page.lastUpdateUser = User.filterToPublicFields(createdPage.lastUpdateUser);
  456. result.page.creator = User.filterToPublicFields(createdPage.creator);
  457. res.json(ApiResponse.success(result));
  458. // update scopes for descendants
  459. if (overwriteScopesOfDescendants) {
  460. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  461. }
  462. // global notification
  463. try {
  464. await globalNotificationService.notifyPageCreate(createdPage);
  465. }
  466. catch (err) {
  467. logger.error(err);
  468. }
  469. // user notification
  470. if (isSlackEnabled && slackChannels != null) {
  471. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  472. }
  473. };
  474. /**
  475. * @api {post} /pages.update Update page
  476. * @apiName UpdatePage
  477. * @apiGroup Page
  478. *
  479. * @apiParam {String} body
  480. * @apiParam {String} page_id
  481. * @apiParam {String} revision_id
  482. * @apiParam {String} grant
  483. *
  484. * In the case of the page exists:
  485. * - If revision_id is specified => update the page,
  486. * - If revision_id is not specified => force update by the new contents.
  487. */
  488. api.update = async function(req, res) {
  489. const pageBody = req.body.body || null;
  490. const pageId = req.body.page_id || null;
  491. const revisionId = req.body.revision_id || null;
  492. const grant = req.body.grant || null;
  493. const grantUserGroupId = req.body.grantUserGroupId || null;
  494. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  495. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  496. const slackChannels = req.body.slackChannels || null;
  497. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  498. const socketClientId = req.body.socketClientId || undefined;
  499. if (pageId === null || pageBody === null) {
  500. return res.json(ApiResponse.error('page_id and body are required.'));
  501. }
  502. // check page existence
  503. const isExist = await Page.count({_id: pageId}) > 0;
  504. if (!isExist) {
  505. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  506. }
  507. // check revision
  508. let page = await Page.findByIdAndViewer(pageId, req.user);
  509. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  510. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  511. }
  512. const options = {isSyncRevisionToHackmd, socketClientId};
  513. if (grant != null) {
  514. options.grant = grant;
  515. }
  516. if (grantUserGroupId != null) {
  517. options.grantUserGroupId = grantUserGroupId;
  518. }
  519. const Revision = crowi.model('Revision');
  520. const previousRevision = await Revision.findById(revisionId);
  521. try {
  522. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  523. }
  524. catch (err) {
  525. logger.error('error on _api/pages.update', err);
  526. return res.json(ApiResponse.error(err));
  527. }
  528. const result = { page: serializeToObj(page) };
  529. result.page.lastUpdateUser = User.filterToPublicFields(page.lastUpdateUser);
  530. res.json(ApiResponse.success(result));
  531. // update scopes for descendants
  532. if (overwriteScopesOfDescendants) {
  533. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  534. }
  535. // global notification
  536. try {
  537. await globalNotificationService.notifyPageEdit(page);
  538. }
  539. catch (err) {
  540. logger.error(err);
  541. }
  542. // user notification
  543. if (isSlackEnabled && slackChannels != null) {
  544. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  545. }
  546. };
  547. /**
  548. * @api {get} /pages.get Get page data
  549. * @apiName GetPage
  550. * @apiGroup Page
  551. *
  552. * @apiParam {String} page_id
  553. * @apiParam {String} path
  554. * @apiParam {String} revision_id
  555. */
  556. api.get = async function(req, res) {
  557. const pagePath = req.query.path || null;
  558. const pageId = req.query.page_id || null; // TODO: handling
  559. if (!pageId && !pagePath) {
  560. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  561. }
  562. let page;
  563. try {
  564. if (pageId) { // prioritized
  565. page = await Page.findByIdAndViewer(pageId, req.user);
  566. }
  567. else if (pagePath) {
  568. page = await Page.findByPathAndViewer(pagePath, req.user);
  569. }
  570. if (page == null) {
  571. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  572. }
  573. page.initLatestRevisionField();
  574. // populate
  575. page = await page.populateDataToShowRevision();
  576. }
  577. catch (err) {
  578. return res.json(ApiResponse.error(err));
  579. }
  580. const result = {};
  581. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  582. return res.json(ApiResponse.success(result));
  583. };
  584. /**
  585. * @api {post} /pages.seen Mark as seen user
  586. * @apiName SeenPage
  587. * @apiGroup Page
  588. *
  589. * @apiParam {String} page_id Page Id.
  590. */
  591. api.seen = async function(req, res) {
  592. const user = req.user;
  593. const pageId = req.body.page_id;
  594. if (!pageId) {
  595. return res.json(ApiResponse.error('page_id required'));
  596. }
  597. else if (!req.user) {
  598. return res.json(ApiResponse.error('user required'));
  599. }
  600. let page;
  601. try {
  602. page = await Page.findByIdAndViewer(pageId, user);
  603. if (user != null) {
  604. page = await page.seen(user);
  605. }
  606. }
  607. catch (err) {
  608. debug('Seen user update error', err);
  609. return res.json(ApiResponse.error(err));
  610. }
  611. const result = {};
  612. result.seenUser = page.seenUsers;
  613. return res.json(ApiResponse.success(result));
  614. };
  615. /**
  616. * @api {post} /likes.add Like page
  617. * @apiName LikePage
  618. * @apiGroup Page
  619. *
  620. * @apiParam {String} page_id Page Id.
  621. */
  622. api.like = async function(req, res) {
  623. const pageId = req.body.page_id;
  624. if (!pageId) {
  625. return res.json(ApiResponse.error('page_id required'));
  626. }
  627. else if (!req.user) {
  628. return res.json(ApiResponse.error('user required'));
  629. }
  630. let page;
  631. try {
  632. page = await Page.findByIdAndViewer(pageId, req.user);
  633. if (page == null) {
  634. throw new Error(`Page '${pageId}' is not found or forbidden`);
  635. }
  636. page = await page.like(req.user);
  637. }
  638. catch (err) {
  639. debug('Seen user update error', err);
  640. return res.json(ApiResponse.error(err));
  641. }
  642. const result = { page };
  643. result.seenUser = page.seenUsers;
  644. res.json(ApiResponse.success(result));
  645. try {
  646. // global notification
  647. globalNotificationService.notifyPageLike(page, req.user);
  648. }
  649. catch (err) {
  650. logger.error('Like failed', err);
  651. }
  652. };
  653. /**
  654. * @api {post} /likes.remove Unlike page
  655. * @apiName UnlikePage
  656. * @apiGroup Page
  657. *
  658. * @apiParam {String} page_id Page Id.
  659. */
  660. api.unlike = async function(req, res) {
  661. const pageId = req.body.page_id;
  662. if (!pageId) {
  663. return res.json(ApiResponse.error('page_id required'));
  664. }
  665. else if (req.user == null) {
  666. return res.json(ApiResponse.error('user required'));
  667. }
  668. let page;
  669. try {
  670. page = await Page.findByIdAndViewer(pageId, req.user);
  671. if (page == null) {
  672. throw new Error(`Page '${pageId}' is not found or forbidden`);
  673. }
  674. page = await page.unlike(req.user);
  675. }
  676. catch (err) {
  677. debug('Seen user update error', err);
  678. return res.json(ApiResponse.error(err));
  679. }
  680. const result = { page };
  681. result.seenUser = page.seenUsers;
  682. return res.json(ApiResponse.success(result));
  683. };
  684. /**
  685. * @api {get} /pages.updatePost
  686. * @apiName Get UpdatePost setting list
  687. * @apiGroup Page
  688. *
  689. * @apiParam {String} path
  690. */
  691. api.getUpdatePost = function(req, res) {
  692. const path = req.query.path;
  693. const UpdatePost = crowi.model('UpdatePost');
  694. if (!path) {
  695. return res.json(ApiResponse.error({}));
  696. }
  697. UpdatePost.findSettingsByPath(path)
  698. .then(function(data) {
  699. data = data.map(function(e) {
  700. return e.channel;
  701. });
  702. debug('Found updatePost data', data);
  703. const result = {updatePost: data};
  704. return res.json(ApiResponse.success(result));
  705. }).catch(function(err) {
  706. debug('Error occured while get setting', err);
  707. return res.json(ApiResponse.error({}));
  708. });
  709. };
  710. /**
  711. * @api {post} /pages.remove Remove page
  712. * @apiName RemovePage
  713. * @apiGroup Page
  714. *
  715. * @apiParam {String} page_id Page Id.
  716. * @apiParam {String} revision_id
  717. */
  718. api.remove = async function(req, res) {
  719. const pageId = req.body.page_id;
  720. const previousRevision = req.body.revision_id || null;
  721. const socketClientId = req.body.socketClientId || undefined;
  722. // get completely flag
  723. const isCompletely = (req.body.completely != null);
  724. // get recursively flag
  725. const isRecursively = (req.body.recursively != null);
  726. const options = {socketClientId};
  727. let page = await Page.findByIdAndViewer(pageId, req.user);
  728. if (page == null) {
  729. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  730. }
  731. debug('Delete page', page._id, page.path);
  732. try {
  733. if (isCompletely) {
  734. if (isRecursively) {
  735. page = await Page.completelyDeletePageRecursively(page, req.user, options);
  736. }
  737. else {
  738. page = await Page.completelyDeletePage(page, req.user, options);
  739. }
  740. }
  741. else {
  742. if (!page.isUpdatable(previousRevision)) {
  743. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  744. }
  745. if (isRecursively) {
  746. page = await Page.deletePageRecursively(page, req.user, options);
  747. }
  748. else {
  749. page = await Page.deletePage(page, req.user, options);
  750. }
  751. }
  752. }
  753. catch (err) {
  754. logger.error('Error occured while get setting', err);
  755. return res.json(ApiResponse.error('Failed to delete page.', 'unknown'));
  756. }
  757. debug('Page deleted', page.path);
  758. const result = {};
  759. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  760. res.json(ApiResponse.success(result));
  761. // global notification
  762. return globalNotificationService.notifyPageDelete(page);
  763. };
  764. /**
  765. * @api {post} /pages.revertRemove Revert removed page
  766. * @apiName RevertRemovePage
  767. * @apiGroup Page
  768. *
  769. * @apiParam {String} page_id Page Id.
  770. */
  771. api.revertRemove = async function(req, res, options) {
  772. const pageId = req.body.page_id;
  773. const socketClientId = req.body.socketClientId || undefined;
  774. // get recursively flag
  775. const isRecursively = (req.body.recursively !== undefined);
  776. let page;
  777. try {
  778. page = await Page.findByIdAndViewer(pageId, req.user);
  779. if (page == null) {
  780. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  781. }
  782. if (isRecursively) {
  783. page = await Page.revertDeletedPageRecursively(page, req.user, {socketClientId});
  784. }
  785. else {
  786. page = await Page.revertDeletedPage(page, req.user, {socketClientId});
  787. }
  788. }
  789. catch (err) {
  790. logger.error('Error occured while get setting', err);
  791. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  792. }
  793. const result = {};
  794. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  795. return res.json(ApiResponse.success(result));
  796. };
  797. /**
  798. * @api {post} /pages.rename Rename page
  799. * @apiName RenamePage
  800. * @apiGroup Page
  801. *
  802. * @apiParam {String} page_id Page Id.
  803. * @apiParam {String} path
  804. * @apiParam {String} revision_id
  805. * @apiParam {String} new_path New path name.
  806. * @apiParam {Bool} create_redirect
  807. */
  808. api.rename = async function(req, res) {
  809. const pageId = req.body.page_id;
  810. const previousRevision = req.body.revision_id || null;
  811. const newPagePath = Page.normalizePath(req.body.new_path);
  812. const options = {
  813. createRedirectPage: req.body.create_redirect || 0,
  814. moveUnderTrees: req.body.move_trees || 0,
  815. socketClientId: +req.body.socketClientId || undefined,
  816. };
  817. const isRecursively = req.body.recursively || 0;
  818. if (!Page.isCreatableName(newPagePath)) {
  819. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  820. }
  821. const isExist = await Page.count({ path: newPagePath }) > 0;
  822. if (isExist) {
  823. // if page found, cannot cannot rename to that path
  824. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  825. }
  826. let page;
  827. try {
  828. page = await Page.findByIdAndViewer(pageId, req.user);
  829. if (page == null) {
  830. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  831. }
  832. if (!page.isUpdatable(previousRevision)) {
  833. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  834. }
  835. if (isRecursively) {
  836. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  837. }
  838. else {
  839. page = await Page.rename(page, newPagePath, req.user, options);
  840. }
  841. }
  842. catch (err) {
  843. logger.error(err);
  844. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  845. }
  846. const result = {};
  847. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  848. res.json(ApiResponse.success(result));
  849. // global notification
  850. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  851. return page;
  852. };
  853. /**
  854. * @api {post} /pages.duplicate Duplicate page
  855. * @apiName DuplicatePage
  856. * @apiGroup Page
  857. *
  858. * @apiParam {String} page_id Page Id.
  859. * @apiParam {String} new_path New path name.
  860. */
  861. api.duplicate = async function(req, res) {
  862. const pageId = req.body.page_id;
  863. const newPagePath = Page.normalizePath(req.body.new_path);
  864. const page = await Page.findByIdAndViewer(pageId, req.user);
  865. if (page == null) {
  866. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  867. }
  868. await page.populateDataToShowRevision();
  869. req.body.path = newPagePath;
  870. req.body.body = page.revision.body;
  871. req.body.grant = page.grant;
  872. return api.create(req, res);
  873. };
  874. /**
  875. * @api {post} /pages.unlink Remove the redirecting page
  876. * @apiName UnlinkPage
  877. * @apiGroup Page
  878. *
  879. * @apiParam {String} page_id Page Id.
  880. * @apiParam {String} revision_id
  881. */
  882. api.unlink = async function(req, res) {
  883. const path = req.body.path;
  884. try {
  885. await Page.removeRedirectOriginPageByPath(path);
  886. logger.debug('Redirect Page deleted', path);
  887. }
  888. catch (err) {
  889. logger.error('Error occured while get setting', err);
  890. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  891. }
  892. const result = { path };
  893. return res.json(ApiResponse.success(result));
  894. };
  895. api.recentCreated = async function(req, res) {
  896. const pageId = req.query.page_id;
  897. if (pageId == null) {
  898. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  899. }
  900. const page = await Page.findById(pageId);
  901. if (page == null) {
  902. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  903. }
  904. if (!isUserPage(page.path)) {
  905. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  906. }
  907. const limit = + req.query.limit || 50;
  908. const offset = + req.query.offset || 0;
  909. const queryOptions = { offset: offset, limit: limit };
  910. try {
  911. let result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  912. result.pages = pagePathUtils.encodePagesPath(result.pages);
  913. return res.json(ApiResponse.success(result));
  914. }
  915. catch (err) {
  916. return res.json(ApiResponse.error(err));
  917. }
  918. };
  919. return actions;
  920. };