page.js 47 KB

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