page.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  1. /**
  2. * @swagger
  3. * tags:
  4. * name: Pages
  5. */
  6. /**
  7. * @swagger
  8. *
  9. * components:
  10. * schemas:
  11. * Page:
  12. * description: Page
  13. * type: object
  14. * properties:
  15. * _id:
  16. * type: string
  17. * description: page ID
  18. * example: 5e07345972560e001761fa63
  19. * __v:
  20. * type: number
  21. * description: DB record version
  22. * example: 0
  23. * commentCount:
  24. * type: number
  25. * description: count of comments
  26. * example: 3
  27. * createdAt:
  28. * type: string
  29. * description: date created at
  30. * example: 2010-01-01T00:00:00.000Z
  31. * creator:
  32. * $ref: '#/components/schemas/User'
  33. * extended:
  34. * type: object
  35. * description: extend data
  36. * example: {}
  37. * grant:
  38. * type: number
  39. * description: grant
  40. * example: 1
  41. * grantedUsers:
  42. * type: array
  43. * description: granted users
  44. * items:
  45. * type: string
  46. * description: user ID
  47. * example: ["5ae5fccfc5577b0004dbd8ab"]
  48. * lastUpdateUser:
  49. * $ref: '#/components/schemas/User'
  50. * liker:
  51. * type: array
  52. * description: granted users
  53. * items:
  54. * type: string
  55. * description: user ID
  56. * example: []
  57. * path:
  58. * type: string
  59. * description: page path
  60. * example: /
  61. * redirectTo:
  62. * type: string
  63. * description: redirect path
  64. * example: ""
  65. * revision:
  66. * $ref: '#/components/schemas/Revision'
  67. * seenUsers:
  68. * type: array
  69. * description: granted users
  70. * items:
  71. * type: string
  72. * description: user ID
  73. * example: ["5ae5fccfc5577b0004dbd8ab"]
  74. * status:
  75. * type: string
  76. * description: status
  77. * enum:
  78. * - 'wip'
  79. * - 'published'
  80. * - 'deleted'
  81. * - 'deprecated'
  82. * example: published
  83. * updatedAt:
  84. * type: string
  85. * description: date updated at
  86. * example: 2010-01-01T00:00:00.000Z
  87. *
  88. * UpdatePost:
  89. * description: UpdatePost
  90. * type: object
  91. * properties:
  92. * _id:
  93. * type: string
  94. * description: update post ID
  95. * example: 5e0734e472560e001761fa68
  96. * __v:
  97. * type: number
  98. * description: DB record version
  99. * example: 0
  100. * pathPattern:
  101. * type: string
  102. * description: path pattern
  103. * example: /test
  104. * patternPrefix:
  105. * type: string
  106. * description: patternPrefix prefix
  107. * example: /
  108. * patternPrefix2:
  109. * type: string
  110. * description: path
  111. * example: test
  112. * channel:
  113. * type: string
  114. * description: channel
  115. * example: general
  116. * provider:
  117. * type: string
  118. * description: provider
  119. * enum:
  120. * - slack
  121. * example: slack
  122. * creator:
  123. * $ref: '#/components/schemas/User'
  124. * createdAt:
  125. * type: string
  126. * description: date created at
  127. * example: 2010-01-01T00:00:00.000Z
  128. */
  129. /* eslint-disable no-use-before-define */
  130. module.exports = function(crowi, app) {
  131. const debug = require('debug')('growi:routes:page');
  132. const logger = require('@alias/logger')('growi:routes:page');
  133. const swig = require('swig-templates');
  134. const pathUtils = require('growi-commons').pathUtils;
  135. const Page = crowi.model('Page');
  136. const User = crowi.model('User');
  137. const Bookmark = crowi.model('Bookmark');
  138. const PageTagRelation = crowi.model('PageTagRelation');
  139. const UpdatePost = crowi.model('UpdatePost');
  140. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  141. const ShareLink = crowi.model('ShareLink');
  142. const ApiResponse = require('../util/apiResponse');
  143. const getToday = require('../util/getToday');
  144. const { slackNotificationService, configManager } = crowi;
  145. const interceptorManager = crowi.getInterceptorManager();
  146. const globalNotificationService = crowi.getGlobalNotificationService();
  147. const pageService = crowi.pageService;
  148. const actions = {};
  149. function getPathFromRequest(req) {
  150. return pathUtils.normalizePath(req.params[0] || '');
  151. }
  152. function isUserPage(path) {
  153. if (path.match(/^\/user\/[^/]+\/?$/)) {
  154. return true;
  155. }
  156. return false;
  157. }
  158. function generatePager(offset, limit, totalCount) {
  159. let prev = null;
  160. if (offset > 0) {
  161. prev = offset - limit;
  162. if (prev < 0) {
  163. prev = 0;
  164. }
  165. }
  166. let next = offset + limit;
  167. if (totalCount < next) {
  168. next = null;
  169. }
  170. return {
  171. prev,
  172. next,
  173. offset,
  174. };
  175. }
  176. // user notification
  177. // TODO create '/service/user-notification' module
  178. /**
  179. *
  180. * @param {Page} page
  181. * @param {User} user
  182. * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
  183. * @param {boolean} updateOrCreate
  184. * @param {string} previousRevision
  185. */
  186. async function notifyToSlackByUser(page, user, slackChannelsStr, updateOrCreate, previousRevision) {
  187. await page.updateSlackChannel(slackChannelsStr)
  188. .catch((err) => {
  189. logger.error('Error occured in updating slack channels: ', err);
  190. });
  191. if (slackNotificationService.hasSlackConfig()) {
  192. const slackChannels = slackChannelsStr != null ? slackChannelsStr.split(',') : [null];
  193. const promises = slackChannels.map((chan) => {
  194. return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
  195. });
  196. Promise.all(promises)
  197. .catch((err) => {
  198. logger.error('Error occured in sending slack notification: ', err);
  199. });
  200. }
  201. }
  202. function addRendarVarsForPage(renderVars, page) {
  203. renderVars.page = page;
  204. renderVars.revision = page.revision;
  205. renderVars.author = page.revision.author;
  206. renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
  207. renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
  208. renderVars.hasDraftOnHackmd = page.hasDraftOnHackmd;
  209. }
  210. async function addRenderVarsForUserPage(renderVars, page, requestUser) {
  211. const userData = await User.findUserByUsername(User.getUsernameByPath(page.path));
  212. if (userData != null) {
  213. renderVars.pageUser = userData;
  214. renderVars.bookmarkList = await Bookmark.findByUser(userData, { limit: 10, populatePage: true, requestUser });
  215. }
  216. }
  217. function addRendarVarsForScope(renderVars, page) {
  218. renderVars.grant = page.grant;
  219. renderVars.grantedGroupId = page.grantedGroup ? page.grantedGroup.id : null;
  220. renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
  221. }
  222. async function addRenderVarsForSlack(renderVars, page) {
  223. renderVars.slack = await getSlackChannels(page);
  224. }
  225. async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
  226. const SEENER_THRESHOLD = 10;
  227. const queryOptions = {
  228. offset,
  229. limit,
  230. includeTrashed: path.startsWith('/trash/'),
  231. isRegExpEscapedFromPath,
  232. };
  233. const result = await Page.findListWithDescendants(path, requestUser, queryOptions);
  234. if (result.pages.length > limit) {
  235. result.pages.pop();
  236. }
  237. renderVars.viewConfig = {
  238. seener_threshold: SEENER_THRESHOLD,
  239. };
  240. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  241. renderVars.pages = result.pages;
  242. }
  243. function replacePlaceholdersOfTemplate(template, req) {
  244. if (req.user == null) {
  245. return '';
  246. }
  247. const definitions = {
  248. pagepath: getPathFromRequest(req),
  249. username: req.user.name,
  250. today: getToday(),
  251. };
  252. const compiledTemplate = swig.compile(template);
  253. return compiledTemplate(definitions);
  254. }
  255. async function showPageForPresentation(req, res, next) {
  256. const path = getPathFromRequest(req);
  257. const revisionId = req.query.revision;
  258. let page = await Page.findByPathAndViewer(path, req.user);
  259. if (page == null) {
  260. next();
  261. }
  262. const renderVars = {};
  263. // populate
  264. page = await page.populateDataToMakePresentation(revisionId);
  265. addRendarVarsForPage(renderVars, page);
  266. return res.render('page_presentation', renderVars);
  267. }
  268. async function showTopPage(req, res, next) {
  269. const portalPath = req.path;
  270. const revisionId = req.query.revision;
  271. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  272. const view = `layout-${layoutName}/page_list`;
  273. const renderVars = { path: portalPath };
  274. let portalPage = await Page.findByPathAndViewer(portalPath, req.user);
  275. portalPage.initLatestRevisionField(revisionId);
  276. // populate
  277. portalPage = await portalPage.populateDataToShowRevision();
  278. addRendarVarsForPage(renderVars, portalPage);
  279. await addRenderVarsForSlack(renderVars, portalPage);
  280. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: portalPage._id });
  281. renderVars.sharelinksNumber = sharelinksNumber;
  282. const limit = 50;
  283. const offset = parseInt(req.query.offset) || 0;
  284. await addRenderVarsForDescendants(renderVars, portalPath, req.user, offset, limit);
  285. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  286. return res.render(view, renderVars);
  287. }
  288. async function showPageForGrowiBehavior(req, res, next) {
  289. const path = getPathFromRequest(req);
  290. const revisionId = req.query.revision;
  291. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  292. let page = await Page.findByPathAndViewer(path, req.user);
  293. if (page == null) {
  294. // check the page is forbidden or just does not exist.
  295. req.isForbidden = await Page.count({ path }) > 0;
  296. return next();
  297. }
  298. if (page.redirectTo) {
  299. debug(`Redirect to '${page.redirectTo}'`);
  300. return res.redirect(`${encodeURI(page.redirectTo)}?redirectFrom=${encodeURIComponent(path)}`);
  301. }
  302. logger.debug('Page is found when processing pageShowForGrowiBehavior', page._id, page.path);
  303. const limit = 50;
  304. const offset = parseInt(req.query.offset) || 0;
  305. const renderVars = {};
  306. let view = `layout-${layoutName}/page`;
  307. page.initLatestRevisionField(revisionId);
  308. // populate
  309. page = await page.populateDataToShowRevision();
  310. addRendarVarsForPage(renderVars, page);
  311. addRendarVarsForScope(renderVars, page);
  312. await addRenderVarsForSlack(renderVars, page);
  313. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  314. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
  315. renderVars.sharelinksNumber = sharelinksNumber;
  316. if (isUserPage(page.path)) {
  317. // change template
  318. view = `layout-${layoutName}/user_page`;
  319. await addRenderVarsForUserPage(renderVars, page, req.user);
  320. }
  321. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  322. return res.render(view, renderVars);
  323. }
  324. const getSlackChannels = async(page) => {
  325. if (page.extended.slack) {
  326. return page.extended.slack;
  327. }
  328. const data = await UpdatePost.findSettingsByPath(page.path);
  329. const channels = data.map((e) => { return e.channel }).join(', ');
  330. return channels;
  331. };
  332. actions.showTopPage = function(req, res) {
  333. return showTopPage(req, res);
  334. };
  335. /**
  336. * Redirect to the page without trailing slash
  337. */
  338. actions.showPageWithEndOfSlash = function(req, res, next) {
  339. return res.redirect(pathUtils.removeTrailingSlash(req.path));
  340. };
  341. /**
  342. * switch action
  343. * - presentation mode
  344. * - by behaviorType
  345. */
  346. actions.showPage = async function(req, res, next) {
  347. // presentation mode
  348. if (req.query.presentation) {
  349. return showPageForPresentation(req, res, next);
  350. }
  351. // delegate to showPageForGrowiBehavior
  352. return showPageForGrowiBehavior(req, res, next);
  353. };
  354. actions.showSharedPage = async function(req, res, next) {
  355. const { linkId } = req.params;
  356. const revisionId = req.query.revision;
  357. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  358. const view = `layout-${layoutName}/shared_page`;
  359. const shareLink = await ShareLink.findOne({ _id: linkId }).populate('relatedPage');
  360. if (shareLink == null || shareLink.relatedPage == null) {
  361. // page or sharelink are not found
  362. return res.render(`layout-${layoutName}/not_found_shared_page`);
  363. }
  364. let page = shareLink.relatedPage;
  365. // check if share link is expired
  366. if (shareLink.isExpired()) {
  367. // page is not found
  368. return res.render(`layout-${layoutName}/expired_shared_page`);
  369. }
  370. const renderVars = {};
  371. renderVars.sharelink = shareLink;
  372. // presentation mode
  373. if (req.query.presentation) {
  374. page = await page.populateDataToMakePresentation(revisionId);
  375. // populate
  376. addRendarVarsForPage(renderVars, page);
  377. return res.render('page_presentation', renderVars);
  378. }
  379. page.initLatestRevisionField(revisionId);
  380. // populate
  381. page = await page.populateDataToShowRevision();
  382. addRendarVarsForPage(renderVars, page);
  383. addRendarVarsForScope(renderVars, page);
  384. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  385. return res.render(view, renderVars);
  386. };
  387. /**
  388. * switch action by behaviorType
  389. */
  390. /* eslint-disable no-else-return */
  391. actions.trashPageListShowWrapper = function(req, res) {
  392. // redirect to '/trash'
  393. return res.redirect('/trash');
  394. };
  395. /* eslint-enable no-else-return */
  396. /**
  397. * switch action by behaviorType
  398. */
  399. /* eslint-disable no-else-return */
  400. actions.trashPageShowWrapper = function(req, res) {
  401. // Crowi behavior for '/trash/*'
  402. return actions.deletedPageListShow(req, res);
  403. };
  404. /* eslint-enable no-else-return */
  405. /**
  406. * switch action by behaviorType
  407. */
  408. /* eslint-disable no-else-return */
  409. actions.deletedPageListShowWrapper = function(req, res) {
  410. const path = `/trash${getPathFromRequest(req)}`;
  411. return res.redirect(path);
  412. };
  413. /* eslint-enable no-else-return */
  414. actions.notFound = async function(req, res) {
  415. const path = getPathFromRequest(req);
  416. const isCreatable = Page.isCreatableName(path);
  417. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  418. let view;
  419. const renderVars = { path };
  420. if (!isCreatable) {
  421. view = `layout-${layoutName}/not_creatable`;
  422. }
  423. else if (req.isForbidden) {
  424. view = `layout-${layoutName}/forbidden`;
  425. }
  426. else {
  427. view = `layout-${layoutName}/not_found`;
  428. // retrieve templates
  429. if (req.user != null) {
  430. const template = await Page.findTemplate(path);
  431. if (template.templateBody) {
  432. const body = replacePlaceholdersOfTemplate(template.templateBody, req);
  433. const tags = template.templateTags;
  434. renderVars.template = body;
  435. renderVars.templateTags = tags;
  436. }
  437. }
  438. // add scope variables by ancestor page
  439. const ancestor = await Page.findAncestorByPathAndViewer(path, req.user);
  440. if (ancestor != null) {
  441. await ancestor.populate('grantedGroup').execPopulate();
  442. addRendarVarsForScope(renderVars, ancestor);
  443. }
  444. }
  445. const limit = 50;
  446. const offset = parseInt(req.query.offset) || 0;
  447. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  448. return res.render(view, renderVars);
  449. };
  450. actions.deletedPageListShow = async function(req, res) {
  451. // normalizePath makes '/trash/' -> '/trash'
  452. const path = pathUtils.normalizePath(`/trash${getPathFromRequest(req)}`);
  453. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  454. const limit = 50;
  455. const offset = parseInt(req.query.offset) || 0;
  456. const queryOptions = {
  457. offset,
  458. limit,
  459. includeTrashed: true,
  460. };
  461. const renderVars = {
  462. page: null,
  463. path,
  464. pages: [],
  465. };
  466. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  467. if (result.pages.length > limit) {
  468. result.pages.pop();
  469. }
  470. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  471. renderVars.pages = result.pages;
  472. res.render(`layout-${layoutName}/page_list`, renderVars);
  473. };
  474. /**
  475. * redirector
  476. */
  477. actions.redirector = async function(req, res) {
  478. const id = req.params.id;
  479. const page = await Page.findByIdAndViewer(id, req.user);
  480. if (page != null) {
  481. return res.redirect(encodeURI(page.path));
  482. }
  483. return res.redirect('/');
  484. };
  485. const api = {};
  486. actions.api = api;
  487. /**
  488. * @swagger
  489. *
  490. * /pages.list:
  491. * get:
  492. * tags: [Pages, CrowiCompatibles]
  493. * operationId: listPages
  494. * summary: /pages.list
  495. * description: Get list of pages
  496. * parameters:
  497. * - in: query
  498. * name: path
  499. * schema:
  500. * $ref: '#/components/schemas/Page/properties/path'
  501. * - in: query
  502. * name: user
  503. * schema:
  504. * $ref: '#/components/schemas/User/properties/username'
  505. * - in: query
  506. * name: limit
  507. * schema:
  508. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  509. * - in: query
  510. * name: offset
  511. * schema:
  512. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  513. * responses:
  514. * 200:
  515. * description: Succeeded to get list of pages.
  516. * content:
  517. * application/json:
  518. * schema:
  519. * properties:
  520. * ok:
  521. * $ref: '#/components/schemas/V1Response/properties/ok'
  522. * pages:
  523. * type: array
  524. * items:
  525. * $ref: '#/components/schemas/Page'
  526. * description: page list
  527. * 403:
  528. * $ref: '#/components/responses/403'
  529. * 500:
  530. * $ref: '#/components/responses/500'
  531. */
  532. /**
  533. * @api {get} /pages.list List pages by user
  534. * @apiName ListPage
  535. * @apiGroup Page
  536. *
  537. * @apiParam {String} path
  538. * @apiParam {String} user
  539. */
  540. api.list = async function(req, res) {
  541. const username = req.query.user || null;
  542. const path = req.query.path || null;
  543. const limit = +req.query.limit || 50;
  544. const offset = parseInt(req.query.offset) || 0;
  545. const queryOptions = { offset, limit: limit + 1 };
  546. // Accepts only one of these
  547. if (username === null && path === null) {
  548. return res.json(ApiResponse.error('Parameter user or path is required.'));
  549. }
  550. if (username !== null && path !== null) {
  551. return res.json(ApiResponse.error('Parameter user or path is required.'));
  552. }
  553. try {
  554. let result = null;
  555. if (path == null) {
  556. const user = await User.findUserByUsername(username);
  557. if (user === null) {
  558. throw new Error('The user not found.');
  559. }
  560. result = await Page.findListByCreator(user, req.user, queryOptions);
  561. }
  562. else {
  563. result = await Page.findListByStartWith(path, req.user, queryOptions);
  564. }
  565. if (result.pages.length > limit) {
  566. result.pages.pop();
  567. }
  568. return res.json(ApiResponse.success(result));
  569. }
  570. catch (err) {
  571. return res.json(ApiResponse.error(err));
  572. }
  573. };
  574. // TODO If everything that depends on this route, delete it too
  575. api.create = async function(req, res) {
  576. const body = req.body.body || null;
  577. let pagePath = req.body.path || null;
  578. const grant = req.body.grant || null;
  579. const grantUserGroupId = req.body.grantUserGroupId || null;
  580. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  581. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  582. const slackChannels = req.body.slackChannels || null;
  583. const socketClientId = req.body.socketClientId || undefined;
  584. const pageTags = req.body.pageTags || undefined;
  585. if (body === null || pagePath === null) {
  586. return res.json(ApiResponse.error('Parameters body and path are required.'));
  587. }
  588. // check whether path starts slash
  589. pagePath = pathUtils.addHeadingSlash(pagePath);
  590. // check page existence
  591. const isExist = await Page.count({ path: pagePath }) > 0;
  592. if (isExist) {
  593. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  594. }
  595. const options = { socketClientId };
  596. if (grant != null) {
  597. options.grant = grant;
  598. options.grantUserGroupId = grantUserGroupId;
  599. }
  600. const createdPage = await Page.create(pagePath, body, req.user, options);
  601. let savedTags;
  602. if (pageTags != null) {
  603. await PageTagRelation.updatePageTags(createdPage.id, pageTags);
  604. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  605. }
  606. const result = { page: pageService.serializeToObj(createdPage), tags: savedTags };
  607. res.json(ApiResponse.success(result));
  608. // update scopes for descendants
  609. if (overwriteScopesOfDescendants) {
  610. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  611. }
  612. // global notification
  613. try {
  614. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage, req.user);
  615. }
  616. catch (err) {
  617. logger.error('Create notification failed', err);
  618. }
  619. // user notification
  620. if (isSlackEnabled) {
  621. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  622. }
  623. };
  624. /**
  625. * @swagger
  626. *
  627. * /pages.update:
  628. * post:
  629. * tags: [Pages, CrowiCompatibles]
  630. * operationId: updatePage
  631. * summary: /pages.update
  632. * description: Update page
  633. * requestBody:
  634. * content:
  635. * application/json:
  636. * schema:
  637. * properties:
  638. * body:
  639. * $ref: '#/components/schemas/Revision/properties/body'
  640. * page_id:
  641. * $ref: '#/components/schemas/Page/properties/_id'
  642. * revision_id:
  643. * $ref: '#/components/schemas/Revision/properties/_id'
  644. * grant:
  645. * $ref: '#/components/schemas/Page/properties/grant'
  646. * required:
  647. * - body
  648. * - page_id
  649. * - revision_id
  650. * responses:
  651. * 200:
  652. * description: Succeeded to update page.
  653. * content:
  654. * application/json:
  655. * schema:
  656. * properties:
  657. * ok:
  658. * $ref: '#/components/schemas/V1Response/properties/ok'
  659. * page:
  660. * $ref: '#/components/schemas/Page'
  661. * 403:
  662. * $ref: '#/components/responses/403'
  663. * 500:
  664. * $ref: '#/components/responses/500'
  665. */
  666. /**
  667. * @api {post} /pages.update Update page
  668. * @apiName UpdatePage
  669. * @apiGroup Page
  670. *
  671. * @apiParam {String} body
  672. * @apiParam {String} page_id
  673. * @apiParam {String} revision_id
  674. * @apiParam {String} grant
  675. *
  676. * In the case of the page exists:
  677. * - If revision_id is specified => update the page,
  678. * - If revision_id is not specified => force update by the new contents.
  679. */
  680. api.update = async function(req, res) {
  681. const pageBody = req.body.body || null;
  682. const pageId = req.body.page_id || null;
  683. const revisionId = req.body.revision_id || null;
  684. const grant = req.body.grant || null;
  685. const grantUserGroupId = req.body.grantUserGroupId || null;
  686. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  687. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  688. const slackChannels = req.body.slackChannels || null;
  689. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  690. const socketClientId = req.body.socketClientId || undefined;
  691. const pageTags = req.body.pageTags || undefined;
  692. if (pageId === null || pageBody === null || revisionId === null) {
  693. return res.json(ApiResponse.error('page_id, body and revision_id are required.'));
  694. }
  695. // check page existence
  696. const isExist = await Page.count({ _id: pageId }) > 0;
  697. if (!isExist) {
  698. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  699. }
  700. // check revision
  701. let page = await Page.findByIdAndViewer(pageId, req.user);
  702. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  703. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  704. }
  705. const options = { isSyncRevisionToHackmd, socketClientId };
  706. if (grant != null) {
  707. options.grant = grant;
  708. options.grantUserGroupId = grantUserGroupId;
  709. }
  710. const Revision = crowi.model('Revision');
  711. const previousRevision = await Revision.findById(revisionId);
  712. try {
  713. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  714. }
  715. catch (err) {
  716. logger.error('error on _api/pages.update', err);
  717. return res.json(ApiResponse.error(err));
  718. }
  719. let savedTags;
  720. if (pageTags != null) {
  721. await PageTagRelation.updatePageTags(pageId, pageTags);
  722. savedTags = await PageTagRelation.listTagNamesByPage(pageId);
  723. }
  724. const result = { page: pageService.serializeToObj(page), tags: savedTags };
  725. res.json(ApiResponse.success(result));
  726. // update scopes for descendants
  727. if (overwriteScopesOfDescendants) {
  728. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  729. }
  730. // global notification
  731. try {
  732. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_EDIT, page, req.user);
  733. }
  734. catch (err) {
  735. logger.error('Edit notification failed', err);
  736. }
  737. // user notification
  738. if (isSlackEnabled) {
  739. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  740. }
  741. };
  742. /**
  743. * @swagger
  744. *
  745. * /pages.get:
  746. * get:
  747. * tags: [Pages, CrowiCompatibles]
  748. * operationId: getPage
  749. * summary: /pages.get
  750. * description: Get page data
  751. * parameters:
  752. * - in: query
  753. * name: page_id
  754. * schema:
  755. * $ref: '#/components/schemas/Page/properties/_id'
  756. * - in: query
  757. * name: path
  758. * schema:
  759. * $ref: '#/components/schemas/Page/properties/path'
  760. * - in: query
  761. * name: revision_id
  762. * schema:
  763. * $ref: '#/components/schemas/Revision/properties/_id'
  764. * responses:
  765. * 200:
  766. * description: Succeeded to get page data.
  767. * content:
  768. * application/json:
  769. * schema:
  770. * properties:
  771. * ok:
  772. * $ref: '#/components/schemas/V1Response/properties/ok'
  773. * page:
  774. * $ref: '#/components/schemas/Page'
  775. * 403:
  776. * $ref: '#/components/responses/403'
  777. * 500:
  778. * $ref: '#/components/responses/500'
  779. */
  780. /**
  781. * @api {get} /pages.get Get page data
  782. * @apiName GetPage
  783. * @apiGroup Page
  784. *
  785. * @apiParam {String} page_id
  786. * @apiParam {String} path
  787. * @apiParam {String} revision_id
  788. */
  789. api.get = async function(req, res) {
  790. const pagePath = req.query.path || null;
  791. const pageId = req.query.page_id || null; // TODO: handling
  792. if (!pageId && !pagePath) {
  793. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  794. }
  795. let page;
  796. try {
  797. if (pageId) { // prioritized
  798. page = await Page.findByIdAndViewer(pageId, req.user);
  799. }
  800. else if (pagePath) {
  801. page = await Page.findByPathAndViewer(pagePath, req.user);
  802. }
  803. if (page == null) {
  804. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  805. }
  806. page.initLatestRevisionField();
  807. // populate
  808. page = await page.populateDataToShowRevision();
  809. }
  810. catch (err) {
  811. return res.json(ApiResponse.error(err));
  812. }
  813. const result = {};
  814. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  815. return res.json(ApiResponse.success(result));
  816. };
  817. /**
  818. * @swagger
  819. *
  820. * /pages.exist:
  821. * get:
  822. * tags: [Pages]
  823. * operationId: getPageExistence
  824. * summary: /pages.exist
  825. * description: Get page existence
  826. * parameters:
  827. * - in: query
  828. * name: pagePaths
  829. * schema:
  830. * type: string
  831. * description: Page path list in JSON Array format
  832. * example: '["/", "/user/unknown"]'
  833. * responses:
  834. * 200:
  835. * description: Succeeded to get page existence.
  836. * content:
  837. * application/json:
  838. * schema:
  839. * properties:
  840. * ok:
  841. * $ref: '#/components/schemas/V1Response/properties/ok'
  842. * pages:
  843. * type: string
  844. * description: Properties of page path and existence
  845. * example: '{"/": true, "/user/unknown": false}'
  846. * 403:
  847. * $ref: '#/components/responses/403'
  848. * 500:
  849. * $ref: '#/components/responses/500'
  850. */
  851. /**
  852. * @api {get} /pages.exist Get if page exists
  853. * @apiName GetPage
  854. * @apiGroup Page
  855. *
  856. * @apiParam {String} pages (stringified JSON)
  857. */
  858. api.exist = async function(req, res) {
  859. const pagePaths = JSON.parse(req.query.pagePaths || '[]');
  860. const pages = {};
  861. await Promise.all(pagePaths.map(async(path) => {
  862. // check page existence
  863. const isExist = await Page.count({ path }) > 0;
  864. pages[path] = isExist;
  865. return;
  866. }));
  867. const result = { pages };
  868. return res.json(ApiResponse.success(result));
  869. };
  870. /**
  871. * @swagger
  872. *
  873. * /pages.getPageTag:
  874. * get:
  875. * tags: [Pages]
  876. * operationId: getPageTag
  877. * summary: /pages.getPageTag
  878. * description: Get page tag
  879. * parameters:
  880. * - in: query
  881. * name: pageId
  882. * schema:
  883. * $ref: '#/components/schemas/Page/properties/_id'
  884. * responses:
  885. * 200:
  886. * description: Succeeded to get page tags.
  887. * content:
  888. * application/json:
  889. * schema:
  890. * properties:
  891. * ok:
  892. * $ref: '#/components/schemas/V1Response/properties/ok'
  893. * tags:
  894. * $ref: '#/components/schemas/Tags'
  895. * 403:
  896. * $ref: '#/components/responses/403'
  897. * 500:
  898. * $ref: '#/components/responses/500'
  899. */
  900. /**
  901. * @api {get} /pages.getPageTag get page tags
  902. * @apiName GetPageTag
  903. * @apiGroup Page
  904. *
  905. * @apiParam {String} pageId
  906. */
  907. api.getPageTag = async function(req, res) {
  908. const result = {};
  909. try {
  910. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  911. }
  912. catch (err) {
  913. return res.json(ApiResponse.error(err));
  914. }
  915. return res.json(ApiResponse.success(result));
  916. };
  917. /**
  918. * @swagger
  919. *
  920. * /pages.seen:
  921. * post:
  922. * tags: [Pages, CrowiCompatibles]
  923. * operationId: seenPage
  924. * summary: /pages.seen
  925. * description: Mark as seen user
  926. * requestBody:
  927. * content:
  928. * application/json:
  929. * schema:
  930. * properties:
  931. * page_id:
  932. * $ref: '#/components/schemas/Page/properties/_id'
  933. * required:
  934. * - page_id
  935. * responses:
  936. * 200:
  937. * description: Succeeded to be page seen.
  938. * content:
  939. * application/json:
  940. * schema:
  941. * properties:
  942. * ok:
  943. * $ref: '#/components/schemas/V1Response/properties/ok'
  944. * seenUser:
  945. * $ref: '#/components/schemas/Page/properties/seenUsers'
  946. * 403:
  947. * $ref: '#/components/responses/403'
  948. * 500:
  949. * $ref: '#/components/responses/500'
  950. */
  951. /**
  952. * @api {post} /pages.seen Mark as seen user
  953. * @apiName SeenPage
  954. * @apiGroup Page
  955. *
  956. * @apiParam {String} page_id Page Id.
  957. */
  958. api.seen = async function(req, res) {
  959. const user = req.user;
  960. const pageId = req.body.page_id;
  961. if (!pageId) {
  962. return res.json(ApiResponse.error('page_id required'));
  963. }
  964. if (!req.user) {
  965. return res.json(ApiResponse.error('user required'));
  966. }
  967. let page;
  968. try {
  969. page = await Page.findByIdAndViewer(pageId, user);
  970. if (user != null) {
  971. page = await page.seen(user);
  972. }
  973. }
  974. catch (err) {
  975. debug('Seen user update error', err);
  976. return res.json(ApiResponse.error(err));
  977. }
  978. const result = {};
  979. result.seenUser = page.seenUsers;
  980. return res.json(ApiResponse.success(result));
  981. };
  982. /**
  983. * @swagger
  984. *
  985. * /pages.updatePost:
  986. * get:
  987. * tags: [Pages, CrowiCompatibles]
  988. * operationId: getUpdatePostPage
  989. * summary: /pages.updatePost
  990. * description: Get UpdatePost setting list
  991. * parameters:
  992. * - in: query
  993. * name: path
  994. * schema:
  995. * $ref: '#/components/schemas/Page/properties/path'
  996. * responses:
  997. * 200:
  998. * description: Succeeded to get UpdatePost setting list.
  999. * content:
  1000. * application/json:
  1001. * schema:
  1002. * properties:
  1003. * ok:
  1004. * $ref: '#/components/schemas/V1Response/properties/ok'
  1005. * updatePost:
  1006. * $ref: '#/components/schemas/UpdatePost'
  1007. * 403:
  1008. * $ref: '#/components/responses/403'
  1009. * 500:
  1010. * $ref: '#/components/responses/500'
  1011. */
  1012. /**
  1013. * @api {get} /pages.updatePost
  1014. * @apiName Get UpdatePost setting list
  1015. * @apiGroup Page
  1016. *
  1017. * @apiParam {String} path
  1018. */
  1019. api.getUpdatePost = function(req, res) {
  1020. const path = req.query.path;
  1021. const UpdatePost = crowi.model('UpdatePost');
  1022. if (!path) {
  1023. return res.json(ApiResponse.error({}));
  1024. }
  1025. UpdatePost.findSettingsByPath(path)
  1026. .then((data) => {
  1027. // eslint-disable-next-line no-param-reassign
  1028. data = data.map((e) => {
  1029. return e.channel;
  1030. });
  1031. debug('Found updatePost data', data);
  1032. const result = { updatePost: data };
  1033. return res.json(ApiResponse.success(result));
  1034. })
  1035. .catch((err) => {
  1036. debug('Error occured while get setting', err);
  1037. return res.json(ApiResponse.error({}));
  1038. });
  1039. };
  1040. /**
  1041. * @api {post} /pages.remove Remove page
  1042. * @apiName RemovePage
  1043. * @apiGroup Page
  1044. *
  1045. * @apiParam {String} page_id Page Id.
  1046. * @apiParam {String} revision_id
  1047. */
  1048. api.remove = async function(req, res) {
  1049. const pageId = req.body.page_id;
  1050. const previousRevision = req.body.revision_id || null;
  1051. const socketClientId = req.body.socketClientId || undefined;
  1052. // get completely flag
  1053. const isCompletely = (req.body.completely != null);
  1054. // get recursively flag
  1055. const isRecursively = (req.body.recursively != null);
  1056. const options = { socketClientId };
  1057. const page = await Page.findByIdAndViewer(pageId, req.user);
  1058. if (page == null) {
  1059. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1060. }
  1061. debug('Delete page', page._id, page.path);
  1062. try {
  1063. if (isCompletely) {
  1064. if (!req.user.canDeleteCompletely(page.creator)) {
  1065. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  1066. }
  1067. if (isRecursively) {
  1068. await Page.completelyDeletePageRecursively(page, req.user, options);
  1069. }
  1070. else {
  1071. await Page.completelyDeletePage(page, req.user, options);
  1072. }
  1073. }
  1074. else {
  1075. if (!page.isUpdatable(previousRevision)) {
  1076. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1077. }
  1078. if (isRecursively) {
  1079. await Page.deletePageRecursively(page, req.user, options);
  1080. }
  1081. else {
  1082. await Page.deletePage(page, req.user, options);
  1083. }
  1084. }
  1085. }
  1086. catch (err) {
  1087. logger.error('Error occured while get setting', err);
  1088. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  1089. }
  1090. debug('Page deleted', page.path);
  1091. const result = {};
  1092. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1093. res.json(ApiResponse.success(result));
  1094. try {
  1095. // global notification
  1096. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page, req.user);
  1097. }
  1098. catch (err) {
  1099. logger.error('Delete notification failed', err);
  1100. }
  1101. };
  1102. /**
  1103. * @api {post} /pages.revertRemove Revert removed page
  1104. * @apiName RevertRemovePage
  1105. * @apiGroup Page
  1106. *
  1107. * @apiParam {String} page_id Page Id.
  1108. */
  1109. api.revertRemove = async function(req, res, options) {
  1110. const pageId = req.body.page_id;
  1111. const socketClientId = req.body.socketClientId || undefined;
  1112. // get recursively flag
  1113. const isRecursively = (req.body.recursively != null);
  1114. let page;
  1115. try {
  1116. page = await Page.findByIdAndViewer(pageId, req.user);
  1117. if (page == null) {
  1118. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  1119. }
  1120. if (isRecursively) {
  1121. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  1122. }
  1123. else {
  1124. page = await Page.revertDeletedPage(page, req.user, { socketClientId });
  1125. }
  1126. }
  1127. catch (err) {
  1128. logger.error('Error occured while get setting', err);
  1129. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  1130. }
  1131. const result = {};
  1132. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1133. return res.json(ApiResponse.success(result));
  1134. };
  1135. /**
  1136. * @swagger
  1137. *
  1138. * /pages.duplicate:
  1139. * post:
  1140. * tags: [Pages]
  1141. * operationId: duplicatePage
  1142. * summary: /pages.duplicate
  1143. * description: Duplicate page
  1144. * requestBody:
  1145. * content:
  1146. * application/json:
  1147. * schema:
  1148. * properties:
  1149. * page_id:
  1150. * $ref: '#/components/schemas/Page/properties/_id'
  1151. * new_path:
  1152. * $ref: '#/components/schemas/Page/properties/path'
  1153. * required:
  1154. * - page_id
  1155. * responses:
  1156. * 200:
  1157. * description: Succeeded to duplicate page.
  1158. * content:
  1159. * application/json:
  1160. * schema:
  1161. * properties:
  1162. * ok:
  1163. * $ref: '#/components/schemas/V1Response/properties/ok'
  1164. * page:
  1165. * $ref: '#/components/schemas/Page'
  1166. * tags:
  1167. * $ref: '#/components/schemas/Tags'
  1168. * 403:
  1169. * $ref: '#/components/responses/403'
  1170. * 500:
  1171. * $ref: '#/components/responses/500'
  1172. */
  1173. /**
  1174. * @api {post} /pages.duplicate Duplicate page
  1175. * @apiName DuplicatePage
  1176. * @apiGroup Page
  1177. *
  1178. * @apiParam {String} page_id Page Id.
  1179. * @apiParam {String} new_path New path name.
  1180. */
  1181. api.duplicate = async function(req, res) {
  1182. const pageId = req.body.page_id;
  1183. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1184. const page = await Page.findByIdAndViewer(pageId, req.user);
  1185. if (page == null) {
  1186. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1187. }
  1188. // check whether path starts slash
  1189. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1190. await page.populateDataToShowRevision();
  1191. const originTags = await page.findRelatedTagsById();
  1192. req.body.path = newPagePath;
  1193. req.body.body = page.revision.body;
  1194. req.body.grant = page.grant;
  1195. req.body.grantedUsers = page.grantedUsers;
  1196. req.body.grantUserGroupId = page.grantedGroup;
  1197. req.body.pageTags = originTags;
  1198. return api.create(req, res);
  1199. };
  1200. /**
  1201. * @api {post} /pages.unlink Remove the redirecting page
  1202. * @apiName UnlinkPage
  1203. * @apiGroup Page
  1204. *
  1205. * @apiParam {String} page_id Page Id.
  1206. * @apiParam {String} revision_id
  1207. */
  1208. api.unlink = async function(req, res) {
  1209. const path = req.body.path;
  1210. try {
  1211. await Page.removeRedirectOriginPageByPath(path);
  1212. logger.debug('Redirect Page deleted', path);
  1213. }
  1214. catch (err) {
  1215. logger.error('Error occured while get setting', err);
  1216. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1217. }
  1218. const result = { path };
  1219. return res.json(ApiResponse.success(result));
  1220. };
  1221. /**
  1222. * @swagger
  1223. *
  1224. * /pages.recentCreated:
  1225. * get:
  1226. * tags: [Pages]
  1227. * operationId: getRecentCreatedPages
  1228. * summary: /pages.recentCreated
  1229. * description: Get recent created page list
  1230. * parameters:
  1231. * - in: query
  1232. * name: page_id
  1233. * required: true
  1234. * schema:
  1235. * $ref: '#/components/schemas/Page/properties/_id'
  1236. * - in: query
  1237. * name: offset
  1238. * schema:
  1239. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  1240. * - in: query
  1241. * name: limit
  1242. * schema:
  1243. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  1244. * responses:
  1245. * 200:
  1246. * description: Succeeded to get recent created page list.
  1247. * content:
  1248. * application/json:
  1249. * schema:
  1250. * properties:
  1251. * ok:
  1252. * $ref: '#/components/schemas/V1Response/properties/ok'
  1253. * pages:
  1254. * type: array
  1255. * description: recent created page list
  1256. * items:
  1257. * $ref: '#/components/schemas/Page'
  1258. * totalCount:
  1259. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/total'
  1260. * offset:
  1261. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  1262. * limit:
  1263. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  1264. * 403:
  1265. * $ref: '#/components/responses/403'
  1266. * 500:
  1267. * $ref: '#/components/responses/500'
  1268. */
  1269. api.recentCreated = async function(req, res) {
  1270. const pageId = req.query.page_id;
  1271. if (pageId == null) {
  1272. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  1273. }
  1274. const page = await Page.findById(pageId);
  1275. if (page == null) {
  1276. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  1277. }
  1278. if (!isUserPage(page.path)) {
  1279. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  1280. }
  1281. const limit = +req.query.limit || 50;
  1282. const offset = +req.query.offset || 0;
  1283. const queryOptions = { offset, limit };
  1284. try {
  1285. const result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  1286. return res.json(ApiResponse.success(result));
  1287. }
  1288. catch (err) {
  1289. return res.json(ApiResponse.error(err));
  1290. }
  1291. };
  1292. return actions;
  1293. };