page.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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 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 = pathUtils.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 = pathUtils.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 = pathUtils.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. };