page.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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. , pathUtils = require('@commons/util/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. return pathUtils.normalizePath(req.params[0] || '');
  44. }
  45. function isUserPage(path) {
  46. if (path.match(/^\/user\/[^/]+\/?$/)) {
  47. return true;
  48. }
  49. return false;
  50. }
  51. function generatePager(offset, limit, totalCount) {
  52. let next = null,
  53. prev = null;
  54. if (offset > 0) {
  55. prev = offset - limit;
  56. if (prev < 0) {
  57. prev = 0;
  58. }
  59. }
  60. if (totalCount < limit) {
  61. next = null;
  62. }
  63. else {
  64. next = offset + limit;
  65. }
  66. return {
  67. prev: prev,
  68. next: next,
  69. offset: offset,
  70. };
  71. }
  72. // user notification
  73. // TODO create '/service/user-notification' module
  74. async function notifyToSlackByUser(page, user, slackChannels, updateOrCreate, previousRevision) {
  75. await page.updateSlackChannel(slackChannels)
  76. .catch(err => {
  77. logger.error('Error occured in updating slack channels: ', err);
  78. });
  79. if (crowi.slack) {
  80. const promises = slackChannels.split(',').map(function(chan) {
  81. return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
  82. });
  83. Promise.all(promises)
  84. .catch(err => {
  85. logger.error('Error occured in sending slack notification: ', err);
  86. });
  87. }
  88. }
  89. function addRendarVarsForPage(renderVars, page) {
  90. renderVars.page = page;
  91. renderVars.path = page.path;
  92. renderVars.revision = page.revision;
  93. renderVars.author = page.revision.author;
  94. renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
  95. renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
  96. renderVars.hasDraftOnHackmd = page.hasDraftOnHackmd;
  97. }
  98. async function addRenderVarsForUserPage(renderVars, page, requestUser) {
  99. const userData = await User.findUserByUsername(User.getUsernameByPath(page.path))
  100. .populate(User.IMAGE_POPULATION);
  101. if (userData != null) {
  102. renderVars.pageUser = userData;
  103. renderVars.bookmarkList = await Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: requestUser});
  104. }
  105. }
  106. function addRendarVarsForScope(renderVars, page) {
  107. renderVars.grant = page.grant;
  108. renderVars.grantedGroupId = page.grantedGroup ? page.grantedGroup.id : null;
  109. renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
  110. }
  111. async function addRenderVarsForSlack(renderVars, page) {
  112. renderVars.slack = await getSlackChannels(page);
  113. }
  114. async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
  115. const SEENER_THRESHOLD = 10;
  116. const queryOptions = {
  117. offset: offset,
  118. limit: limit + 1,
  119. includeTrashed: path.startsWith('/trash/'),
  120. isRegExpEscapedFromPath,
  121. };
  122. const result = await Page.findListWithDescendants(path, requestUser, queryOptions);
  123. if (result.pages.length > limit) {
  124. result.pages.pop();
  125. }
  126. renderVars.viewConfig = {
  127. seener_threshold: SEENER_THRESHOLD,
  128. };
  129. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  130. renderVars.pages = pathUtils.encodePagesPath(result.pages);
  131. }
  132. function replacePlaceholdersOfTemplate(template, req) {
  133. const definitions = {
  134. pagepath: getPathFromRequest(req),
  135. username: req.user.name,
  136. today: getToday(),
  137. };
  138. const compiledTemplate = swig.compile(template);
  139. return compiledTemplate(definitions);
  140. }
  141. async function showPageForPresentation(req, res, next) {
  142. let path = getPathFromRequest(req);
  143. const revisionId = req.query.revision;
  144. let page = await Page.findByPathAndViewer(path, req.user);
  145. if (page == null) {
  146. next();
  147. }
  148. const renderVars = {};
  149. // populate
  150. page = await page.populateDataToMakePresentation(revisionId);
  151. addRendarVarsForPage(renderVars, page);
  152. return res.render('page_presentation', renderVars);
  153. }
  154. async function showPageListForCrowiBehavior(req, res, next) {
  155. const portalPath = pathUtils.addTrailingSlash(getPathFromRequest(req));
  156. const revisionId = req.query.revision;
  157. // check whether this page has portal page
  158. const portalPageStatus = await getPortalPageState(portalPath, req.user);
  159. let view = 'customlayout-selector/page_list';
  160. const renderVars = { path: portalPath };
  161. if (portalPageStatus === PORTAL_STATUS_FORBIDDEN) {
  162. // inject to req
  163. req.isForbidden = true;
  164. view = 'customlayout-selector/forbidden';
  165. }
  166. else if (portalPageStatus === PORTAL_STATUS_EXISTS) {
  167. let portalPage = await Page.findByPathAndViewer(portalPath, req.user);
  168. portalPage.initLatestRevisionField(revisionId);
  169. // populate
  170. portalPage = await portalPage.populateDataToShowRevision();
  171. addRendarVarsForPage(renderVars, portalPage);
  172. await addRenderVarsForSlack(renderVars, portalPage);
  173. }
  174. const limit = 50;
  175. const offset = parseInt(req.query.offset) || 0;
  176. await addRenderVarsForDescendants(renderVars, portalPath, req.user, offset, limit);
  177. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  178. return res.render(view, renderVars);
  179. }
  180. async function showPageForGrowiBehavior(req, res, next) {
  181. const path = getPathFromRequest(req);
  182. const revisionId = req.query.revision;
  183. let page = await Page.findByPathAndViewer(path, req.user);
  184. if (page == null) {
  185. // check the page is forbidden or just does not exist.
  186. req.isForbidden = await Page.count({path}) > 0;
  187. return next();
  188. }
  189. else if (page.redirectTo) {
  190. debug(`Redirect to '${page.redirectTo}'`);
  191. return res.redirect(encodeURI(page.redirectTo + '?redirectFrom=' + pathUtils.encodePagePath(path)));
  192. }
  193. logger.debug('Page is found when processing pageShowForGrowiBehavior', page._id, page.path);
  194. const limit = 50;
  195. const offset = parseInt(req.query.offset) || 0;
  196. const renderVars = {};
  197. let view = 'customlayout-selector/page';
  198. page.initLatestRevisionField(revisionId);
  199. // populate
  200. page = await page.populateDataToShowRevision();
  201. addRendarVarsForPage(renderVars, page);
  202. addRendarVarsForScope(renderVars, page);
  203. await addRenderVarsForSlack(renderVars, page);
  204. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit);
  205. if (isUserPage(page.path)) {
  206. // change template
  207. view = 'customlayout-selector/user_page';
  208. await addRenderVarsForUserPage(renderVars, page, req.user);
  209. }
  210. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  211. return res.render(view, renderVars);
  212. }
  213. const getSlackChannels = async page => {
  214. if (page.extended.slack) {
  215. return page.extended.slack;
  216. }
  217. else {
  218. const data = await UpdatePost.findSettingsByPath(page.path);
  219. const channels = data.map(e => e.channel).join(', ');
  220. return channels;
  221. }
  222. };
  223. /**
  224. *
  225. * @param {string} path
  226. * @param {User} user
  227. * @returns {number} PORTAL_STATUS_NOT_EXISTS(0) or PORTAL_STATUS_EXISTS(1) or PORTAL_STATUS_FORBIDDEN(2)
  228. */
  229. async function getPortalPageState(path, user) {
  230. const portalPath = Page.addSlashOfEnd(path);
  231. let page = await Page.findByPathAndViewer(portalPath, user);
  232. if (page == null) {
  233. // check the page is forbidden or just does not exist.
  234. const isForbidden = await Page.count({ path: portalPath }) > 0;
  235. return isForbidden ? PORTAL_STATUS_FORBIDDEN : PORTAL_STATUS_NOT_EXISTS;
  236. }
  237. return PORTAL_STATUS_EXISTS;
  238. }
  239. actions.showTopPage = function(req, res) {
  240. return showPageListForCrowiBehavior(req, res);
  241. };
  242. /**
  243. * switch action by behaviorType
  244. */
  245. actions.showPageWithEndOfSlash = function(req, res, next) {
  246. const behaviorType = Config.behaviorType(config);
  247. if (!behaviorType || 'crowi' === behaviorType) {
  248. return showPageListForCrowiBehavior(req, res, next);
  249. }
  250. else {
  251. let 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. /**
  257. * switch action
  258. * - presentation mode
  259. * - by behaviorType
  260. */
  261. actions.showPage = async function(req, res, next) {
  262. // presentation mode
  263. if (req.query.presentation) {
  264. return showPageForPresentation(req, res, next);
  265. }
  266. const behaviorType = Config.behaviorType(config);
  267. // check whether this page has portal page
  268. if (!behaviorType || 'crowi' === behaviorType) {
  269. const portalPagePath = pathUtils.addTrailingSlash(getPathFromRequest(req));
  270. let hasPortalPage = await Page.count({ path: portalPagePath }) > 0;
  271. if (hasPortalPage) {
  272. logger.debug('The portal page is found', portalPagePath);
  273. return res.redirect(encodeURI(portalPagePath + '?redirectFrom=' + pathUtils.encodePagePath(req.path)));
  274. }
  275. }
  276. // delegate to showPageForGrowiBehavior
  277. return showPageForGrowiBehavior(req, res, next);
  278. };
  279. /**
  280. * switch action by behaviorType
  281. */
  282. actions.trashPageListShowWrapper = function(req, res) {
  283. const behaviorType = Config.behaviorType(config);
  284. if (!behaviorType || 'crowi' === behaviorType) {
  285. // Crowi behavior for '/trash/*'
  286. return actions.deletedPageListShow(req, res);
  287. }
  288. else {
  289. // redirect to '/trash'
  290. return res.redirect('/trash');
  291. }
  292. };
  293. /**
  294. * switch action by behaviorType
  295. */
  296. actions.trashPageShowWrapper = function(req, res) {
  297. const behaviorType = Config.behaviorType(config);
  298. if (!behaviorType || 'crowi' === behaviorType) {
  299. // redirect to '/trash/'
  300. return res.redirect('/trash/');
  301. }
  302. else {
  303. // Crowi behavior for '/trash/*'
  304. return actions.deletedPageListShow(req, res);
  305. }
  306. };
  307. /**
  308. * switch action by behaviorType
  309. */
  310. actions.deletedPageListShowWrapper = function(req, res) {
  311. const behaviorType = Config.behaviorType(config);
  312. if (!behaviorType || 'crowi' === behaviorType) {
  313. // Crowi behavior for '/trash/*'
  314. return actions.deletedPageListShow(req, res);
  315. }
  316. else {
  317. const path = '/trash' + getPathFromRequest(req);
  318. return res.redirect(path);
  319. }
  320. };
  321. actions.notFound = async function(req, res) {
  322. const path = getPathFromRequest(req);
  323. const isCreatable = Page.isCreatableName(path);
  324. let view;
  325. const renderVars = { path };
  326. if (!isCreatable || 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 = pathUtils.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(pathUtils.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 = pathUtils.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 pageTags = req.body.pageTags || null;
  498. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  499. const socketClientId = req.body.socketClientId || undefined;
  500. if (pageId === null || pageBody === null) {
  501. return res.json(ApiResponse.error('page_id and body are required.'));
  502. }
  503. // check page existence
  504. const isExist = await Page.count({_id: pageId}) > 0;
  505. if (!isExist) {
  506. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  507. }
  508. // check revision
  509. let page = await Page.findByIdAndViewer(pageId, req.user);
  510. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  511. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  512. }
  513. const options = {isSyncRevisionToHackmd, socketClientId};
  514. if (grant != null) {
  515. options.grant = grant;
  516. }
  517. if (grantUserGroupId != null) {
  518. options.grantUserGroupId = grantUserGroupId;
  519. }
  520. const Revision = crowi.model('Revision');
  521. const previousRevision = await Revision.findById(revisionId);
  522. try {
  523. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  524. }
  525. catch (err) {
  526. logger.error('error on _api/pages.update', err);
  527. return res.json(ApiResponse.error(err));
  528. }
  529. const result = { page: serializeToObj(page) };
  530. result.page.lastUpdateUser = User.filterToPublicFields(page.lastUpdateUser);
  531. res.json(ApiResponse.success(result));
  532. // update scopes for descendants
  533. if (overwriteScopesOfDescendants) {
  534. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  535. }
  536. // global notification
  537. try {
  538. await globalNotificationService.notifyPageEdit(page);
  539. }
  540. catch (err) {
  541. logger.error(err);
  542. }
  543. // user notification
  544. if (isSlackEnabled && slackChannels != null) {
  545. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  546. }
  547. // // update page tag
  548. // await page.updateTags(pageTags); [pagetag]
  549. };
  550. /**
  551. * @api {get} /pages.get Get page data
  552. * @apiName GetPage
  553. * @apiGroup Page
  554. *
  555. * @apiParam {String} page_id
  556. * @apiParam {String} path
  557. * @apiParam {String} revision_id
  558. */
  559. api.get = async function(req, res) {
  560. const pagePath = req.query.path || null;
  561. const pageId = req.query.page_id || null; // TODO: handling
  562. if (!pageId && !pagePath) {
  563. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  564. }
  565. let page;
  566. try {
  567. if (pageId) { // prioritized
  568. page = await Page.findByIdAndViewer(pageId, req.user);
  569. }
  570. else if (pagePath) {
  571. page = await Page.findByPathAndViewer(pagePath, req.user);
  572. }
  573. if (page == null) {
  574. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  575. }
  576. page.initLatestRevisionField();
  577. // populate
  578. page = await page.populateDataToShowRevision();
  579. }
  580. catch (err) {
  581. return res.json(ApiResponse.error(err));
  582. }
  583. const result = {};
  584. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  585. return res.json(ApiResponse.success(result));
  586. };
  587. /**
  588. * @api {post} /pages.seen Mark as seen user
  589. * @apiName SeenPage
  590. * @apiGroup Page
  591. *
  592. * @apiParam {String} page_id Page Id.
  593. */
  594. api.seen = async function(req, res) {
  595. const user = req.user;
  596. const pageId = req.body.page_id;
  597. if (!pageId) {
  598. return res.json(ApiResponse.error('page_id required'));
  599. }
  600. else if (!req.user) {
  601. return res.json(ApiResponse.error('user required'));
  602. }
  603. let page;
  604. try {
  605. page = await Page.findByIdAndViewer(pageId, user);
  606. if (user != null) {
  607. page = await page.seen(user);
  608. }
  609. }
  610. catch (err) {
  611. debug('Seen user update error', err);
  612. return res.json(ApiResponse.error(err));
  613. }
  614. const result = {};
  615. result.seenUser = page.seenUsers;
  616. return res.json(ApiResponse.success(result));
  617. };
  618. /**
  619. * @api {post} /likes.add Like page
  620. * @apiName LikePage
  621. * @apiGroup Page
  622. *
  623. * @apiParam {String} page_id Page Id.
  624. */
  625. api.like = async function(req, res) {
  626. const pageId = req.body.page_id;
  627. if (!pageId) {
  628. return res.json(ApiResponse.error('page_id required'));
  629. }
  630. else if (!req.user) {
  631. return res.json(ApiResponse.error('user required'));
  632. }
  633. let page;
  634. try {
  635. page = await Page.findByIdAndViewer(pageId, req.user);
  636. if (page == null) {
  637. throw new Error(`Page '${pageId}' is not found or forbidden`);
  638. }
  639. page = await page.like(req.user);
  640. }
  641. catch (err) {
  642. debug('Seen user update error', err);
  643. return res.json(ApiResponse.error(err));
  644. }
  645. const result = { page };
  646. result.seenUser = page.seenUsers;
  647. res.json(ApiResponse.success(result));
  648. try {
  649. // global notification
  650. globalNotificationService.notifyPageLike(page, req.user);
  651. }
  652. catch (err) {
  653. logger.error('Like failed', err);
  654. }
  655. };
  656. /**
  657. * @api {post} /likes.remove Unlike page
  658. * @apiName UnlikePage
  659. * @apiGroup Page
  660. *
  661. * @apiParam {String} page_id Page Id.
  662. */
  663. api.unlike = async function(req, res) {
  664. const pageId = req.body.page_id;
  665. if (!pageId) {
  666. return res.json(ApiResponse.error('page_id required'));
  667. }
  668. else if (req.user == null) {
  669. return res.json(ApiResponse.error('user required'));
  670. }
  671. let page;
  672. try {
  673. page = await Page.findByIdAndViewer(pageId, req.user);
  674. if (page == null) {
  675. throw new Error(`Page '${pageId}' is not found or forbidden`);
  676. }
  677. page = await page.unlike(req.user);
  678. }
  679. catch (err) {
  680. debug('Seen user update error', err);
  681. return res.json(ApiResponse.error(err));
  682. }
  683. const result = { page };
  684. result.seenUser = page.seenUsers;
  685. return res.json(ApiResponse.success(result));
  686. };
  687. /**
  688. * @api {get} /pages.updatePost
  689. * @apiName Get UpdatePost setting list
  690. * @apiGroup Page
  691. *
  692. * @apiParam {String} path
  693. */
  694. api.getUpdatePost = function(req, res) {
  695. const path = req.query.path;
  696. const UpdatePost = crowi.model('UpdatePost');
  697. if (!path) {
  698. return res.json(ApiResponse.error({}));
  699. }
  700. UpdatePost.findSettingsByPath(path)
  701. .then(function(data) {
  702. data = data.map(function(e) {
  703. return e.channel;
  704. });
  705. debug('Found updatePost data', data);
  706. const result = {updatePost: data};
  707. return res.json(ApiResponse.success(result));
  708. }).catch(function(err) {
  709. debug('Error occured while get setting', err);
  710. return res.json(ApiResponse.error({}));
  711. });
  712. };
  713. /**
  714. * @api {post} /pages.remove Remove page
  715. * @apiName RemovePage
  716. * @apiGroup Page
  717. *
  718. * @apiParam {String} page_id Page Id.
  719. * @apiParam {String} revision_id
  720. */
  721. api.remove = async function(req, res) {
  722. const pageId = req.body.page_id;
  723. const previousRevision = req.body.revision_id || null;
  724. const socketClientId = req.body.socketClientId || undefined;
  725. // get completely flag
  726. const isCompletely = (req.body.completely != null);
  727. // get recursively flag
  728. const isRecursively = (req.body.recursively != null);
  729. const options = {socketClientId};
  730. let page = await Page.findByIdAndViewer(pageId, req.user);
  731. if (page == null) {
  732. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  733. }
  734. debug('Delete page', page._id, page.path);
  735. try {
  736. if (isCompletely) {
  737. if (isRecursively) {
  738. page = await Page.completelyDeletePageRecursively(page, req.user, options);
  739. }
  740. else {
  741. page = await Page.completelyDeletePage(page, req.user, options);
  742. }
  743. }
  744. else {
  745. if (!page.isUpdatable(previousRevision)) {
  746. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  747. }
  748. if (isRecursively) {
  749. page = await Page.deletePageRecursively(page, req.user, options);
  750. }
  751. else {
  752. page = await Page.deletePage(page, req.user, options);
  753. }
  754. }
  755. }
  756. catch (err) {
  757. logger.error('Error occured while get setting', err);
  758. return res.json(ApiResponse.error('Failed to delete page.', 'unknown'));
  759. }
  760. debug('Page deleted', page.path);
  761. const result = {};
  762. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  763. res.json(ApiResponse.success(result));
  764. // global notification
  765. return globalNotificationService.notifyPageDelete(page);
  766. };
  767. /**
  768. * @api {post} /pages.revertRemove Revert removed page
  769. * @apiName RevertRemovePage
  770. * @apiGroup Page
  771. *
  772. * @apiParam {String} page_id Page Id.
  773. */
  774. api.revertRemove = async function(req, res, options) {
  775. const pageId = req.body.page_id;
  776. const socketClientId = req.body.socketClientId || undefined;
  777. // get recursively flag
  778. const isRecursively = (req.body.recursively !== undefined);
  779. let page;
  780. try {
  781. page = await Page.findByIdAndViewer(pageId, req.user);
  782. if (page == null) {
  783. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  784. }
  785. if (isRecursively) {
  786. page = await Page.revertDeletedPageRecursively(page, req.user, {socketClientId});
  787. }
  788. else {
  789. page = await Page.revertDeletedPage(page, req.user, {socketClientId});
  790. }
  791. }
  792. catch (err) {
  793. logger.error('Error occured while get setting', err);
  794. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  795. }
  796. const result = {};
  797. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  798. return res.json(ApiResponse.success(result));
  799. };
  800. /**
  801. * @api {post} /pages.rename Rename page
  802. * @apiName RenamePage
  803. * @apiGroup Page
  804. *
  805. * @apiParam {String} page_id Page Id.
  806. * @apiParam {String} path
  807. * @apiParam {String} revision_id
  808. * @apiParam {String} new_path New path name.
  809. * @apiParam {Bool} create_redirect
  810. */
  811. api.rename = async function(req, res) {
  812. const pageId = req.body.page_id;
  813. const previousRevision = req.body.revision_id || null;
  814. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  815. const options = {
  816. createRedirectPage: req.body.create_redirect || 0,
  817. moveUnderTrees: req.body.move_trees || 0,
  818. socketClientId: +req.body.socketClientId || undefined,
  819. };
  820. const isRecursively = req.body.recursively || 0;
  821. if (!Page.isCreatableName(newPagePath)) {
  822. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  823. }
  824. const isExist = await Page.count({ path: newPagePath }) > 0;
  825. if (isExist) {
  826. // if page found, cannot cannot rename to that path
  827. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  828. }
  829. let page;
  830. try {
  831. page = await Page.findByIdAndViewer(pageId, req.user);
  832. if (page == null) {
  833. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  834. }
  835. if (!page.isUpdatable(previousRevision)) {
  836. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  837. }
  838. if (isRecursively) {
  839. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  840. }
  841. else {
  842. page = await Page.rename(page, newPagePath, req.user, options);
  843. }
  844. }
  845. catch (err) {
  846. logger.error(err);
  847. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  848. }
  849. const result = {};
  850. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  851. res.json(ApiResponse.success(result));
  852. // global notification
  853. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  854. return page;
  855. };
  856. /**
  857. * @api {post} /pages.duplicate Duplicate page
  858. * @apiName DuplicatePage
  859. * @apiGroup Page
  860. *
  861. * @apiParam {String} page_id Page Id.
  862. * @apiParam {String} new_path New path name.
  863. */
  864. api.duplicate = async function(req, res) {
  865. const pageId = req.body.page_id;
  866. const newPagePath = pathUtils.normalizePath(req.body.new_path);
  867. const page = await Page.findByIdAndViewer(pageId, req.user);
  868. if (page == null) {
  869. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  870. }
  871. await page.populateDataToShowRevision();
  872. req.body.path = newPagePath;
  873. req.body.body = page.revision.body;
  874. req.body.grant = page.grant;
  875. return api.create(req, res);
  876. };
  877. /**
  878. * @api {post} /pages.unlink Remove the redirecting page
  879. * @apiName UnlinkPage
  880. * @apiGroup Page
  881. *
  882. * @apiParam {String} page_id Page Id.
  883. * @apiParam {String} revision_id
  884. */
  885. api.unlink = async function(req, res) {
  886. const path = req.body.path;
  887. try {
  888. await Page.removeRedirectOriginPageByPath(path);
  889. logger.debug('Redirect Page deleted', path);
  890. }
  891. catch (err) {
  892. logger.error('Error occured while get setting', err);
  893. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  894. }
  895. const result = { path };
  896. return res.json(ApiResponse.success(result));
  897. };
  898. api.recentCreated = async function(req, res) {
  899. const pageId = req.query.page_id;
  900. if (pageId == null) {
  901. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  902. }
  903. const page = await Page.findById(pageId);
  904. if (page == null) {
  905. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  906. }
  907. if (!isUserPage(page.path)) {
  908. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  909. }
  910. const limit = + req.query.limit || 50;
  911. const offset = + req.query.offset || 0;
  912. const queryOptions = { offset: offset, limit: limit };
  913. try {
  914. let result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  915. result.pages = pathUtils.encodePagesPath(result.pages);
  916. return res.json(ApiResponse.success(result));
  917. }
  918. catch (err) {
  919. return res.json(ApiResponse.error(err));
  920. }
  921. };
  922. return actions;
  923. };