page.js 32 KB

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