page.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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 = getPathFromRequest(req);
  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. const limit = 50;
  332. const offset = parseInt(req.query.offset) || 0;
  333. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit);
  334. return res.render(view, renderVars);
  335. };
  336. actions.deletedPageListShow = async function(req, res) {
  337. const path = '/trash' + getPathFromRequest(req);
  338. const limit = 50;
  339. const offset = parseInt(req.query.offset) || 0;
  340. const queryOptions = {
  341. offset: offset,
  342. limit: limit + 1,
  343. includeTrashed: true,
  344. };
  345. const renderVars = {
  346. page: null,
  347. path: path,
  348. pages: [],
  349. };
  350. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  351. if (result.pages.length > limit) {
  352. result.pages.pop();
  353. }
  354. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  355. renderVars.pages = pagePathUtils.encodePagesPath(result.pages);
  356. res.render('customlayout-selector/page_list', renderVars);
  357. };
  358. /**
  359. * redirector
  360. */
  361. actions.redirector = async function(req, res) {
  362. const id = req.params.id;
  363. const page = await Page.findByIdAndViewer(id, req.user);
  364. if (page != null) {
  365. return res.redirect(pagePathUtils.encodePagePath(page.path));
  366. }
  367. return res.redirect('/');
  368. };
  369. const api = actions.api = {};
  370. /**
  371. * @api {get} /pages.list List pages by user
  372. * @apiName ListPage
  373. * @apiGroup Page
  374. *
  375. * @apiParam {String} path
  376. * @apiParam {String} user
  377. */
  378. api.list = async function(req, res) {
  379. const username = req.query.user || null;
  380. const path = req.query.path || null;
  381. const limit = + req.query.limit || 50;
  382. const offset = parseInt(req.query.offset) || 0;
  383. const queryOptions = { offset, limit: limit + 1 };
  384. // Accepts only one of these
  385. if (username === null && path === null) {
  386. return res.json(ApiResponse.error('Parameter user or path is required.'));
  387. }
  388. if (username !== null && path !== null) {
  389. return res.json(ApiResponse.error('Parameter user or path is required.'));
  390. }
  391. try {
  392. let result = null;
  393. if (path == null) {
  394. const user = await User.findUserByUsername(username);
  395. if (user === null) {
  396. throw new Error('The user not found.');
  397. }
  398. result = await Page.findListByCreator(user, req.user, queryOptions);
  399. }
  400. else {
  401. result = await Page.findListByStartWith(path, req.user, queryOptions);
  402. }
  403. if (result.pages.length > limit) {
  404. result.pages.pop();
  405. }
  406. result.pages = pagePathUtils.encodePagesPath(result.pages);
  407. return res.json(ApiResponse.success(result));
  408. }
  409. catch (err) {
  410. return res.json(ApiResponse.error(err));
  411. }
  412. };
  413. /**
  414. * @api {post} /pages.create Create new page
  415. * @apiName CreatePage
  416. * @apiGroup Page
  417. *
  418. * @apiParam {String} body
  419. * @apiParam {String} path
  420. * @apiParam {String} grant
  421. */
  422. api.create = async function(req, res) {
  423. const body = req.body.body || null;
  424. const pagePath = req.body.path || null;
  425. const grant = req.body.grant || null;
  426. const grantUserGroupId = req.body.grantUserGroupId || null;
  427. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  428. const slackChannels = req.body.slackChannels || null;
  429. const socketClientId = req.body.socketClientId || undefined;
  430. if (body === null || pagePath === null) {
  431. return res.json(ApiResponse.error('Parameters body and path are required.'));
  432. }
  433. // check page existence
  434. const isExist = await Page.count({path: pagePath}) > 0;
  435. if (isExist) {
  436. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  437. }
  438. const options = {grant, grantUserGroupId, socketClientId};
  439. const createdPage = await Page.create(pagePath, body, req.user, options);
  440. const result = { page: serializeToObj(createdPage) };
  441. result.page.lastUpdateUser = User.filterToPublicFields(createdPage.lastUpdateUser);
  442. result.page.creator = User.filterToPublicFields(createdPage.creator);
  443. res.json(ApiResponse.success(result));
  444. // global notification
  445. try {
  446. await globalNotificationService.notifyPageCreate(createdPage);
  447. }
  448. catch (err) {
  449. logger.error(err);
  450. }
  451. // user notification
  452. if (isSlackEnabled && slackChannels != null) {
  453. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  454. }
  455. };
  456. /**
  457. * @api {post} /pages.update Update page
  458. * @apiName UpdatePage
  459. * @apiGroup Page
  460. *
  461. * @apiParam {String} body
  462. * @apiParam {String} page_id
  463. * @apiParam {String} revision_id
  464. * @apiParam {String} grant
  465. *
  466. * In the case of the page exists:
  467. * - If revision_id is specified => update the page,
  468. * - If revision_id is not specified => force update by the new contents.
  469. */
  470. api.update = async function(req, res) {
  471. const pageBody = req.body.body || null;
  472. const pageId = req.body.page_id || null;
  473. const revisionId = req.body.revision_id || null;
  474. const grant = req.body.grant || null;
  475. const grantUserGroupId = req.body.grantUserGroupId || null;
  476. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  477. const slackChannels = req.body.slackChannels || null;
  478. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  479. const socketClientId = req.body.socketClientId || undefined;
  480. if (pageId === null || pageBody === null) {
  481. return res.json(ApiResponse.error('page_id and body are required.'));
  482. }
  483. // check page existence
  484. const isExist = await Page.count({_id: pageId}) > 0;
  485. if (!isExist) {
  486. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  487. }
  488. // check revision
  489. let page = await Page.findByIdAndViewer(pageId, req.user);
  490. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  491. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  492. }
  493. const options = {isSyncRevisionToHackmd, socketClientId};
  494. if (grant != null) {
  495. options.grant = grant;
  496. }
  497. if (grantUserGroupId != null) {
  498. options.grantUserGroupId = grantUserGroupId;
  499. }
  500. try {
  501. const Revision = crowi.model('Revision');
  502. const previousRevision = await Revision.findById(revisionId);
  503. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  504. }
  505. catch (err) {
  506. logger.error('error on _api/pages.update', err);
  507. return res.json(ApiResponse.error(err));
  508. }
  509. const result = { page: serializeToObj(page) };
  510. result.page.lastUpdateUser = User.filterToPublicFields(page.lastUpdateUser);
  511. res.json(ApiResponse.success(result));
  512. // global notification
  513. try {
  514. await globalNotificationService.notifyPageEdit(page);
  515. }
  516. catch (err) {
  517. logger.error(err);
  518. }
  519. // user notification
  520. if (isSlackEnabled && slackChannels != null) {
  521. const Revision = crowi.model('Revision');
  522. const previousRevision = await Revision.findById(page.revision);
  523. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  524. }
  525. };
  526. /**
  527. * @api {get} /pages.get Get page data
  528. * @apiName GetPage
  529. * @apiGroup Page
  530. *
  531. * @apiParam {String} page_id
  532. * @apiParam {String} path
  533. * @apiParam {String} revision_id
  534. */
  535. api.get = async function(req, res) {
  536. const pagePath = req.query.path || null;
  537. const pageId = req.query.page_id || null; // TODO: handling
  538. if (!pageId && !pagePath) {
  539. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  540. }
  541. let page;
  542. try {
  543. if (pageId) { // prioritized
  544. page = await Page.findByIdAndViewer(pageId, req.user);
  545. }
  546. else if (pagePath) {
  547. page = await Page.findByPathAndViewer(pagePath, req.user);
  548. }
  549. if (page == null) {
  550. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  551. }
  552. page.initLatestRevisionField();
  553. // populate
  554. page = await page.populateDataToShowRevision();
  555. }
  556. catch (err) {
  557. return res.json(ApiResponse.error(err));
  558. }
  559. const result = {};
  560. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  561. return res.json(ApiResponse.success(result));
  562. };
  563. /**
  564. * @api {post} /pages.seen Mark as seen user
  565. * @apiName SeenPage
  566. * @apiGroup Page
  567. *
  568. * @apiParam {String} page_id Page Id.
  569. */
  570. api.seen = async function(req, res) {
  571. const pageId = req.body.page_id;
  572. if (!pageId) {
  573. return res.json(ApiResponse.error('page_id required'));
  574. }
  575. else if (!req.user) {
  576. return res.json(ApiResponse.error('user required'));
  577. }
  578. let page;
  579. try {
  580. page = await Page.findByIdAndViewer(pageId, req.user);
  581. if (req.user != null) {
  582. page = await page.seen(req.user);
  583. }
  584. }
  585. catch (err) {
  586. debug('Seen user update error', err);
  587. return res.json(ApiResponse.error(err));
  588. }
  589. const result = {};
  590. result.seenUser = page.seenUsers;
  591. return res.json(ApiResponse.success(result));
  592. };
  593. /**
  594. * @api {post} /likes.add Like page
  595. * @apiName LikePage
  596. * @apiGroup Page
  597. *
  598. * @apiParam {String} page_id Page Id.
  599. */
  600. api.like = async function(req, res) {
  601. const pageId = req.body.page_id;
  602. if (!pageId) {
  603. return res.json(ApiResponse.error('page_id required'));
  604. }
  605. else if (!req.user) {
  606. return res.json(ApiResponse.error('user required'));
  607. }
  608. let page;
  609. try {
  610. page = await Page.findByIdAndViewer(pageId, req.user);
  611. if (page == null) {
  612. throw new Error(`Page '${pageId}' is not found or forbidden`);
  613. }
  614. page = await page.like(req.user);
  615. }
  616. catch (err) {
  617. debug('Seen user update error', err);
  618. return res.json(ApiResponse.error(err));
  619. }
  620. const result = { page };
  621. result.seenUser = page.seenUsers;
  622. res.json(ApiResponse.success(result));
  623. try {
  624. // global notification
  625. globalNotificationService.notifyPageLike(page, req.user);
  626. }
  627. catch (err) {
  628. logger.error('Like failed', err);
  629. }
  630. };
  631. /**
  632. * @api {post} /likes.remove Unlike page
  633. * @apiName UnlikePage
  634. * @apiGroup Page
  635. *
  636. * @apiParam {String} page_id Page Id.
  637. */
  638. api.unlike = async function(req, res) {
  639. const pageId = req.body.page_id;
  640. if (!pageId) {
  641. return res.json(ApiResponse.error('page_id required'));
  642. }
  643. else if (req.user == null) {
  644. return res.json(ApiResponse.error('user required'));
  645. }
  646. let page;
  647. try {
  648. page = await Page.findByIdAndViewer(pageId, req.user);
  649. if (page == null) {
  650. throw new Error(`Page '${pageId}' is not found or forbidden`);
  651. }
  652. page = await page.unlike(req.user);
  653. }
  654. catch (err) {
  655. debug('Seen user update error', err);
  656. return res.json(ApiResponse.error(err));
  657. }
  658. const result = { page };
  659. result.seenUser = page.seenUsers;
  660. return res.json(ApiResponse.success(result));
  661. };
  662. /**
  663. * @api {get} /pages.updatePost
  664. * @apiName Get UpdatePost setting list
  665. * @apiGroup Page
  666. *
  667. * @apiParam {String} path
  668. */
  669. api.getUpdatePost = function(req, res) {
  670. const path = req.query.path;
  671. const UpdatePost = crowi.model('UpdatePost');
  672. if (!path) {
  673. return res.json(ApiResponse.error({}));
  674. }
  675. UpdatePost.findSettingsByPath(path)
  676. .then(function(data) {
  677. data = data.map(function(e) {
  678. return e.channel;
  679. });
  680. debug('Found updatePost data', data);
  681. const result = {updatePost: data};
  682. return res.json(ApiResponse.success(result));
  683. }).catch(function(err) {
  684. debug('Error occured while get setting', err);
  685. return res.json(ApiResponse.error({}));
  686. });
  687. };
  688. /**
  689. * @api {post} /pages.remove Remove page
  690. * @apiName RemovePage
  691. * @apiGroup Page
  692. *
  693. * @apiParam {String} page_id Page Id.
  694. * @apiParam {String} revision_id
  695. */
  696. api.remove = async function(req, res) {
  697. const pageId = req.body.page_id;
  698. const previousRevision = req.body.revision_id || null;
  699. const socketClientId = req.body.socketClientId || undefined;
  700. // get completely flag
  701. const isCompletely = (req.body.completely != null);
  702. // get recursively flag
  703. const isRecursively = (req.body.recursively != null);
  704. const options = {socketClientId};
  705. let page = await Page.findByIdAndViewer(pageId, req.user);
  706. if (page == null) {
  707. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  708. }
  709. debug('Delete page', page._id, page.path);
  710. try {
  711. if (isCompletely) {
  712. if (isRecursively) {
  713. page = await Page.completelyDeletePageRecursively(page, req.user, options);
  714. }
  715. else {
  716. page = await Page.completelyDeletePage(page, req.user, options);
  717. }
  718. }
  719. else {
  720. if (!page.isUpdatable(previousRevision)) {
  721. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  722. }
  723. if (isRecursively) {
  724. page = await Page.deletePageRecursively(page, req.user, options);
  725. }
  726. else {
  727. page = await Page.deletePage(page, req.user, options);
  728. }
  729. }
  730. }
  731. catch (err) {
  732. logger.error('Error occured while get setting', err);
  733. return res.json(ApiResponse.error('Failed to delete page.', 'unknown'));
  734. }
  735. debug('Page deleted', page.path);
  736. const result = {};
  737. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  738. res.json(ApiResponse.success(result));
  739. // global notification
  740. return globalNotificationService.notifyPageDelete(page);
  741. };
  742. /**
  743. * @api {post} /pages.revertRemove Revert removed page
  744. * @apiName RevertRemovePage
  745. * @apiGroup Page
  746. *
  747. * @apiParam {String} page_id Page Id.
  748. */
  749. api.revertRemove = async function(req, res, options) {
  750. const pageId = req.body.page_id;
  751. const socketClientId = req.body.socketClientId || undefined;
  752. // get recursively flag
  753. const isRecursively = (req.body.recursively !== undefined);
  754. let page;
  755. try {
  756. page = await Page.findByIdAndViewer(pageId, req.user);
  757. if (page == null) {
  758. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  759. }
  760. if (isRecursively) {
  761. page = await Page.revertDeletedPageRecursively(page, req.user, {socketClientId});
  762. }
  763. else {
  764. page = await Page.revertDeletedPage(page, req.user, {socketClientId});
  765. }
  766. }
  767. catch (err) {
  768. logger.error('Error occured while get setting', err);
  769. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  770. }
  771. const result = {};
  772. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  773. return res.json(ApiResponse.success(result));
  774. };
  775. /**
  776. * @api {post} /pages.rename Rename page
  777. * @apiName RenamePage
  778. * @apiGroup Page
  779. *
  780. * @apiParam {String} page_id Page Id.
  781. * @apiParam {String} path
  782. * @apiParam {String} revision_id
  783. * @apiParam {String} new_path
  784. * @apiParam {Bool} create_redirect
  785. */
  786. api.rename = async function(req, res) {
  787. const pageId = req.body.page_id;
  788. const previousRevision = req.body.revision_id || null;
  789. const newPagePath = Page.normalizePath(req.body.new_path);
  790. const options = {
  791. createRedirectPage: req.body.create_redirect || 0,
  792. moveUnderTrees: req.body.move_trees || 0,
  793. socketClientId: +req.body.socketClientId || undefined,
  794. };
  795. const isRecursively = req.body.recursively || 0;
  796. if (!Page.isCreatableName(newPagePath)) {
  797. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  798. }
  799. const isExist = await Page.count({ path: newPagePath }) > 0;
  800. if (isExist) {
  801. // if page found, cannot cannot rename to that path
  802. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  803. }
  804. let page;
  805. try {
  806. page = await Page.findByIdAndViewer(pageId, req.user);
  807. if (page == null) {
  808. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  809. }
  810. if (!page.isUpdatable(previousRevision)) {
  811. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  812. }
  813. if (isRecursively) {
  814. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  815. }
  816. else {
  817. page = await Page.rename(page, newPagePath, req.user, options);
  818. }
  819. }
  820. catch (err) {
  821. logger.error(err);
  822. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  823. }
  824. const result = {};
  825. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  826. res.json(ApiResponse.success(result));
  827. // global notification
  828. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  829. return page;
  830. };
  831. /**
  832. * @api {post} /pages.duplicate Duplicate page
  833. * @apiName DuplicatePage
  834. * @apiGroup Page
  835. *
  836. * @apiParam {String} page_id Page Id.
  837. * @apiParam {String} new_path
  838. */
  839. api.duplicate = async function(req, res) {
  840. const pageId = req.body.page_id;
  841. const newPagePath = Page.normalizePath(req.body.new_path);
  842. const page = await Page.findByIdAndViewer(pageId, req.user);
  843. if (page == null) {
  844. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  845. }
  846. await page.populateDataToShowRevision();
  847. req.body.path = newPagePath;
  848. req.body.body = page.revision.body;
  849. req.body.grant = page.grant;
  850. return api.create(req, res);
  851. };
  852. /**
  853. * @api {post} /pages.unlink Remove the redirecting page
  854. * @apiName UnlinkPage
  855. * @apiGroup Page
  856. *
  857. * @apiParam {String} page_id Page Id.
  858. * @apiParam {String} revision_id
  859. */
  860. api.unlink = async function(req, res) {
  861. const path = req.body.path;
  862. try {
  863. await Page.removeRedirectOriginPageByPath(path);
  864. logger.debug('Redirect Page deleted', path);
  865. }
  866. catch (err) {
  867. logger.error('Error occured while get setting', err);
  868. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  869. }
  870. const result = { path };
  871. return res.json(ApiResponse.success(result));
  872. };
  873. api.recentCreated = async function(req, res) {
  874. const pageId = req.query.page_id;
  875. if (pageId == null) {
  876. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  877. }
  878. const page = await Page.findById(pageId);
  879. if (page == null) {
  880. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  881. }
  882. if (!isUserPage(page.path)) {
  883. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  884. }
  885. const limit = + req.query.limit || 50;
  886. const offset = + req.query.offset || 0;
  887. const queryOptions = { offset: offset, limit: limit };
  888. try {
  889. let result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  890. result.pages = pagePathUtils.encodePagesPath(result.pages);
  891. return res.json(ApiResponse.success(result));
  892. }
  893. catch (err) {
  894. return res.json(ApiResponse.error(err));
  895. }
  896. };
  897. return actions;
  898. };