page.js 46 KB

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