page.js 48 KB

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