page.js 30 KB

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