page.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. /**
  2. * @swagger
  3. * tags:
  4. * name: Pages
  5. */
  6. /**
  7. * @swagger
  8. *
  9. * components:
  10. * schemas:
  11. * Page:
  12. * description: Page
  13. * type: object
  14. * properties:
  15. * _id:
  16. * type: string
  17. * description: page ID
  18. * example: 5e07345972560e001761fa63
  19. * __v:
  20. * type: number
  21. * description: DB record version
  22. * example: 0
  23. * commentCount:
  24. * type: number
  25. * description: count of comments
  26. * example: 3
  27. * createdAt:
  28. * type: string
  29. * description: date created at
  30. * example: 2010-01-01T00:00:00.000Z
  31. * creator:
  32. * $ref: '#/components/schemas/User'
  33. * extended:
  34. * type: object
  35. * description: extend data
  36. * example: {}
  37. * grant:
  38. * type: number
  39. * description: grant
  40. * example: 1
  41. * grantedUsers:
  42. * type: array
  43. * description: granted users
  44. * items:
  45. * type: string
  46. * description: user ID
  47. * example: ["5ae5fccfc5577b0004dbd8ab"]
  48. * lastUpdateUser:
  49. * $ref: '#/components/schemas/User'
  50. * liker:
  51. * type: array
  52. * description: granted users
  53. * items:
  54. * type: string
  55. * description: user ID
  56. * example: []
  57. * path:
  58. * type: string
  59. * description: page path
  60. * example: /
  61. * redirectTo:
  62. * type: string
  63. * description: redirect path
  64. * example: ""
  65. * revision:
  66. * $ref: '#/components/schemas/Revision'
  67. * seenUsers:
  68. * type: array
  69. * description: granted users
  70. * items:
  71. * type: string
  72. * description: user ID
  73. * example: ["5ae5fccfc5577b0004dbd8ab"]
  74. * status:
  75. * type: string
  76. * description: status
  77. * enum:
  78. * - 'wip'
  79. * - 'published'
  80. * - 'deleted'
  81. * - 'deprecated'
  82. * example: published
  83. * updatedAt:
  84. * type: string
  85. * description: date updated at
  86. * example: 2010-01-01T00:00:00.000Z
  87. *
  88. * UpdatePost:
  89. * description: UpdatePost
  90. * type: object
  91. * properties:
  92. * _id:
  93. * type: string
  94. * description: update post ID
  95. * example: 5e0734e472560e001761fa68
  96. * __v:
  97. * type: number
  98. * description: DB record version
  99. * example: 0
  100. * pathPattern:
  101. * type: string
  102. * description: path pattern
  103. * example: /test
  104. * patternPrefix:
  105. * type: string
  106. * description: patternPrefix prefix
  107. * example: /
  108. * patternPrefix2:
  109. * type: string
  110. * description: path
  111. * example: test
  112. * channel:
  113. * type: string
  114. * description: channel
  115. * example: general
  116. * provider:
  117. * type: string
  118. * description: provider
  119. * enum:
  120. * - slack
  121. * example: slack
  122. * creator:
  123. * $ref: '#/components/schemas/User'
  124. * createdAt:
  125. * type: string
  126. * description: date created at
  127. * example: 2010-01-01T00:00:00.000Z
  128. */
  129. /* eslint-disable no-use-before-define */
  130. module.exports = function(crowi, app) {
  131. const debug = require('debug')('growi:routes:page');
  132. const logger = require('@alias/logger')('growi:routes:page');
  133. const swig = require('swig-templates');
  134. const pathUtils = require('growi-commons').pathUtils;
  135. const Page = crowi.model('Page');
  136. const User = crowi.model('User');
  137. const Bookmark = crowi.model('Bookmark');
  138. const PageTagRelation = crowi.model('PageTagRelation');
  139. const UpdatePost = crowi.model('UpdatePost');
  140. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  141. const ShareLink = crowi.model('ShareLink');
  142. const ApiResponse = require('../util/apiResponse');
  143. const getToday = require('../util/getToday');
  144. const { slackNotificationService, configManager } = crowi;
  145. const interceptorManager = crowi.getInterceptorManager();
  146. const globalNotificationService = crowi.getGlobalNotificationService();
  147. const pageService = crowi.pageService;
  148. const actions = {};
  149. function getPathFromRequest(req) {
  150. return pathUtils.normalizePath(req.params[0] || '');
  151. }
  152. function isUserPage(path) {
  153. if (path.match(/^\/user\/[^/]+\/?$/)) {
  154. return true;
  155. }
  156. return false;
  157. }
  158. function generatePager(offset, limit, totalCount) {
  159. let prev = null;
  160. if (offset > 0) {
  161. prev = offset - limit;
  162. if (prev < 0) {
  163. prev = 0;
  164. }
  165. }
  166. let next = offset + limit;
  167. if (totalCount < next) {
  168. next = null;
  169. }
  170. return {
  171. prev,
  172. next,
  173. offset,
  174. };
  175. }
  176. // user notification
  177. // TODO create '/service/user-notification' module
  178. /**
  179. *
  180. * @param {Page} page
  181. * @param {User} user
  182. * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
  183. * @param {boolean} updateOrCreate
  184. * @param {string} previousRevision
  185. */
  186. async function notifyToSlackByUser(page, user, slackChannelsStr, updateOrCreate, previousRevision) {
  187. await page.updateSlackChannel(slackChannelsStr)
  188. .catch((err) => {
  189. logger.error('Error occured in updating slack channels: ', err);
  190. });
  191. if (slackNotificationService.hasSlackConfig()) {
  192. const slackChannels = slackChannelsStr != null ? slackChannelsStr.split(',') : [null];
  193. const promises = slackChannels.map((chan) => {
  194. return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
  195. });
  196. Promise.all(promises)
  197. .catch((err) => {
  198. logger.error('Error occured in sending slack notification: ', err);
  199. });
  200. }
  201. }
  202. function addRenderVarsForPage(renderVars, page) {
  203. renderVars.page = page;
  204. renderVars.revision = page.revision;
  205. renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
  206. renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
  207. renderVars.hasDraftOnHackmd = page.hasDraftOnHackmd;
  208. if (page.creator != null) {
  209. renderVars.page.creator = renderVars.page.creator.toObject();
  210. }
  211. if (page.revision.author != null) {
  212. renderVars.revision.author = renderVars.revision.author.toObject();
  213. }
  214. }
  215. function addRenderVarsForPresentation(renderVars, page) {
  216. renderVars.page = page;
  217. renderVars.revision = page.revision;
  218. }
  219. async function addRenderVarsForUserPage(renderVars, page, requestUser) {
  220. const userData = await User.findUserByUsername(User.getUsernameByPath(page.path));
  221. if (userData != null) {
  222. renderVars.pageUser = userData.toObject();
  223. renderVars.bookmarkList = await Bookmark.findByUser(userData, { limit: 10, populatePage: true, requestUser });
  224. }
  225. }
  226. function addRenderVarsForScope(renderVars, page) {
  227. renderVars.grant = page.grant;
  228. renderVars.grantedGroupId = page.grantedGroup ? page.grantedGroup.id : null;
  229. renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
  230. }
  231. async function addRenderVarsForSlack(renderVars, page) {
  232. renderVars.slack = await getSlackChannels(page);
  233. }
  234. async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
  235. const SEENER_THRESHOLD = 10;
  236. const queryOptions = {
  237. offset,
  238. limit,
  239. includeTrashed: path.startsWith('/trash/'),
  240. isRegExpEscapedFromPath,
  241. };
  242. const result = await Page.findListWithDescendants(path, requestUser, queryOptions);
  243. if (result.pages.length > limit) {
  244. result.pages.pop();
  245. }
  246. renderVars.viewConfig = {
  247. seener_threshold: SEENER_THRESHOLD,
  248. };
  249. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  250. renderVars.pages = result.pages;
  251. }
  252. function replacePlaceholdersOfTemplate(template, req) {
  253. if (req.user == null) {
  254. return '';
  255. }
  256. const definitions = {
  257. pagepath: getPathFromRequest(req),
  258. username: req.user.name,
  259. today: getToday(),
  260. };
  261. const compiledTemplate = swig.compile(template);
  262. return compiledTemplate(definitions);
  263. }
  264. async function showPageForPresentation(req, res, next) {
  265. const path = getPathFromRequest(req);
  266. const { revisionId } = req.query;
  267. let page = await Page.findByPathAndViewer(path, req.user);
  268. if (page == null) {
  269. next();
  270. }
  271. const renderVars = {};
  272. // populate
  273. page = await page.populateDataToMakePresentation(revisionId);
  274. if (page != null) {
  275. addRenderVarsForPresentation(renderVars, page);
  276. }
  277. return res.render('page_presentation', renderVars);
  278. }
  279. async function showTopPage(req, res, next) {
  280. const portalPath = req.path;
  281. const revisionId = req.query.revision;
  282. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  283. const view = `layout-${layoutName}/page_list`;
  284. const renderVars = { path: portalPath };
  285. let portalPage = await Page.findByPathAndViewer(portalPath, req.user);
  286. portalPage.initLatestRevisionField(revisionId);
  287. // populate
  288. portalPage = await portalPage.populateDataToShowRevision();
  289. addRenderVarsForPage(renderVars, portalPage);
  290. await addRenderVarsForSlack(renderVars, portalPage);
  291. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: portalPage._id });
  292. renderVars.sharelinksNumber = sharelinksNumber;
  293. const limit = 50;
  294. const offset = parseInt(req.query.offset) || 0;
  295. await addRenderVarsForDescendants(renderVars, portalPath, req.user, offset, limit);
  296. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  297. return res.render(view, renderVars);
  298. }
  299. async function showPageForGrowiBehavior(req, res, next) {
  300. const path = getPathFromRequest(req);
  301. const revisionId = req.query.revision;
  302. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  303. let page = await Page.findByPathAndViewer(path, req.user);
  304. if (page == null) {
  305. // check the page is forbidden or just does not exist.
  306. req.isForbidden = await Page.count({ path }) > 0;
  307. return next();
  308. }
  309. if (page.redirectTo) {
  310. debug(`Redirect to '${page.redirectTo}'`);
  311. return res.redirect(`${encodeURI(page.redirectTo)}?redirectFrom=${encodeURIComponent(path)}`);
  312. }
  313. logger.debug('Page is found when processing pageShowForGrowiBehavior', page._id, page.path);
  314. const limit = 50;
  315. const offset = parseInt(req.query.offset) || 0;
  316. const renderVars = {};
  317. let view = `layout-${layoutName}/page`;
  318. page.initLatestRevisionField(revisionId);
  319. // populate
  320. page = await page.populateDataToShowRevision();
  321. addRenderVarsForPage(renderVars, page);
  322. addRenderVarsForScope(renderVars, page);
  323. await addRenderVarsForSlack(renderVars, page);
  324. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  325. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
  326. renderVars.sharelinksNumber = sharelinksNumber;
  327. if (isUserPage(page.path)) {
  328. // change template
  329. view = `layout-${layoutName}/user_page`;
  330. await addRenderVarsForUserPage(renderVars, page, req.user);
  331. }
  332. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  333. return res.render(view, renderVars);
  334. }
  335. const getSlackChannels = async(page) => {
  336. if (page.extended.slack) {
  337. return page.extended.slack;
  338. }
  339. const data = await UpdatePost.findSettingsByPath(page.path);
  340. const channels = data.map((e) => { return e.channel }).join(', ');
  341. return channels;
  342. };
  343. actions.showTopPage = function(req, res) {
  344. return showTopPage(req, res);
  345. };
  346. /**
  347. * Redirect to the page without trailing slash
  348. */
  349. actions.showPageWithEndOfSlash = function(req, res, next) {
  350. return res.redirect(pathUtils.removeTrailingSlash(req.path));
  351. };
  352. /**
  353. * switch action
  354. * - presentation mode
  355. * - by behaviorType
  356. */
  357. actions.showPage = async function(req, res, next) {
  358. // presentation mode
  359. if (req.query.presentation) {
  360. return showPageForPresentation(req, res, next);
  361. }
  362. // delegate to showPageForGrowiBehavior
  363. return showPageForGrowiBehavior(req, res, next);
  364. };
  365. actions.showSharedPage = async function(req, res, next) {
  366. const { linkId } = req.params;
  367. const revisionId = req.query.revision;
  368. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  369. const view = `layout-${layoutName}/shared_page`;
  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. let page = shareLink.relatedPage;
  376. // check if share link is expired
  377. if (shareLink.isExpired()) {
  378. // page is not found
  379. return res.render(`layout-${layoutName}/expired_shared_page`);
  380. }
  381. const renderVars = {};
  382. renderVars.sharelink = shareLink;
  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(view, 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.seen:
  980. * post:
  981. * tags: [Pages, CrowiCompatibles]
  982. * operationId: seenPage
  983. * summary: /pages.seen
  984. * description: Mark as seen user
  985. * requestBody:
  986. * content:
  987. * application/json:
  988. * schema:
  989. * properties:
  990. * page_id:
  991. * $ref: '#/components/schemas/Page/properties/_id'
  992. * required:
  993. * - page_id
  994. * responses:
  995. * 200:
  996. * description: Succeeded to be page seen.
  997. * content:
  998. * application/json:
  999. * schema:
  1000. * properties:
  1001. * ok:
  1002. * $ref: '#/components/schemas/V1Response/properties/ok'
  1003. * seenUser:
  1004. * $ref: '#/components/schemas/Page/properties/seenUsers'
  1005. * 403:
  1006. * $ref: '#/components/responses/403'
  1007. * 500:
  1008. * $ref: '#/components/responses/500'
  1009. */
  1010. /**
  1011. * @api {post} /pages.seen Mark as seen user
  1012. * @apiName SeenPage
  1013. * @apiGroup Page
  1014. *
  1015. * @apiParam {String} page_id Page Id.
  1016. */
  1017. api.seen = async function(req, res) {
  1018. const user = req.user;
  1019. const pageId = req.body.page_id;
  1020. if (!pageId) {
  1021. return res.json(ApiResponse.error('page_id required'));
  1022. }
  1023. if (!req.user) {
  1024. return res.json(ApiResponse.error('user required'));
  1025. }
  1026. let page;
  1027. try {
  1028. page = await Page.findByIdAndViewer(pageId, user);
  1029. if (user != null) {
  1030. page = await page.seen(user);
  1031. }
  1032. }
  1033. catch (err) {
  1034. debug('Seen user update error', err);
  1035. return res.json(ApiResponse.error(err));
  1036. }
  1037. const result = {};
  1038. result.seenUser = page.seenUsers;
  1039. return res.json(ApiResponse.success(result));
  1040. };
  1041. /**
  1042. * @swagger
  1043. *
  1044. * /pages.updatePost:
  1045. * get:
  1046. * tags: [Pages, CrowiCompatibles]
  1047. * operationId: getUpdatePostPage
  1048. * summary: /pages.updatePost
  1049. * description: Get UpdatePost setting list
  1050. * parameters:
  1051. * - in: query
  1052. * name: path
  1053. * schema:
  1054. * $ref: '#/components/schemas/Page/properties/path'
  1055. * responses:
  1056. * 200:
  1057. * description: Succeeded to get UpdatePost setting list.
  1058. * content:
  1059. * application/json:
  1060. * schema:
  1061. * properties:
  1062. * ok:
  1063. * $ref: '#/components/schemas/V1Response/properties/ok'
  1064. * updatePost:
  1065. * $ref: '#/components/schemas/UpdatePost'
  1066. * 403:
  1067. * $ref: '#/components/responses/403'
  1068. * 500:
  1069. * $ref: '#/components/responses/500'
  1070. */
  1071. /**
  1072. * @api {get} /pages.updatePost
  1073. * @apiName Get UpdatePost setting list
  1074. * @apiGroup Page
  1075. *
  1076. * @apiParam {String} path
  1077. */
  1078. api.getUpdatePost = function(req, res) {
  1079. const path = req.query.path;
  1080. const UpdatePost = crowi.model('UpdatePost');
  1081. if (!path) {
  1082. return res.json(ApiResponse.error({}));
  1083. }
  1084. UpdatePost.findSettingsByPath(path)
  1085. .then((data) => {
  1086. // eslint-disable-next-line no-param-reassign
  1087. data = data.map((e) => {
  1088. return e.channel;
  1089. });
  1090. debug('Found updatePost data', data);
  1091. const result = { updatePost: data };
  1092. return res.json(ApiResponse.success(result));
  1093. })
  1094. .catch((err) => {
  1095. debug('Error occured while get setting', err);
  1096. return res.json(ApiResponse.error({}));
  1097. });
  1098. };
  1099. /**
  1100. * @api {post} /pages.remove Remove page
  1101. * @apiName RemovePage
  1102. * @apiGroup Page
  1103. *
  1104. * @apiParam {String} page_id Page Id.
  1105. * @apiParam {String} revision_id
  1106. */
  1107. api.remove = async function(req, res) {
  1108. const pageId = req.body.page_id;
  1109. const previousRevision = req.body.revision_id || null;
  1110. const socketClientId = req.body.socketClientId || undefined;
  1111. // get completely flag
  1112. const isCompletely = (req.body.completely != null);
  1113. // get recursively flag
  1114. const isRecursively = (req.body.recursively != null);
  1115. const options = { socketClientId };
  1116. const page = await Page.findByIdAndViewer(pageId, req.user);
  1117. if (page == null) {
  1118. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1119. }
  1120. debug('Delete page', page._id, page.path);
  1121. try {
  1122. if (isCompletely) {
  1123. if (!req.user.canDeleteCompletely(page.creator)) {
  1124. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  1125. }
  1126. if (isRecursively) {
  1127. await Page.completelyDeletePageRecursively(page, req.user, options);
  1128. }
  1129. else {
  1130. await Page.completelyDeletePage(page, req.user, options);
  1131. }
  1132. }
  1133. else {
  1134. if (!page.isUpdatable(previousRevision)) {
  1135. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1136. }
  1137. if (isRecursively) {
  1138. await Page.deletePageRecursively(page, req.user, options);
  1139. }
  1140. else {
  1141. await Page.deletePage(page, req.user, options);
  1142. }
  1143. }
  1144. }
  1145. catch (err) {
  1146. logger.error('Error occured while get setting', err);
  1147. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  1148. }
  1149. debug('Page deleted', page.path);
  1150. const result = {};
  1151. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1152. res.json(ApiResponse.success(result));
  1153. try {
  1154. // global notification
  1155. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page, req.user);
  1156. }
  1157. catch (err) {
  1158. logger.error('Delete notification failed', err);
  1159. }
  1160. };
  1161. /**
  1162. * @api {post} /pages.revertRemove Revert removed page
  1163. * @apiName RevertRemovePage
  1164. * @apiGroup Page
  1165. *
  1166. * @apiParam {String} page_id Page Id.
  1167. */
  1168. api.revertRemove = async function(req, res, options) {
  1169. const pageId = req.body.page_id;
  1170. const socketClientId = req.body.socketClientId || undefined;
  1171. // get recursively flag
  1172. const isRecursively = (req.body.recursively != null);
  1173. let page;
  1174. try {
  1175. page = await Page.findByIdAndViewer(pageId, req.user);
  1176. if (page == null) {
  1177. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  1178. }
  1179. if (isRecursively) {
  1180. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  1181. }
  1182. else {
  1183. page = await Page.revertDeletedPage(page, req.user, { socketClientId });
  1184. }
  1185. }
  1186. catch (err) {
  1187. logger.error('Error occured while get setting', err);
  1188. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  1189. }
  1190. const result = {};
  1191. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1192. return res.json(ApiResponse.success(result));
  1193. };
  1194. /**
  1195. * @swagger
  1196. *
  1197. * /pages.rename:
  1198. * post:
  1199. * tags: [Pages, CrowiCompatibles]
  1200. * operationId: renamePage
  1201. * summary: /pages.rename
  1202. * description: Rename page
  1203. * requestBody:
  1204. * content:
  1205. * application/json:
  1206. * schema:
  1207. * properties:
  1208. * page_id:
  1209. * $ref: '#/components/schemas/Page/properties/_id'
  1210. * path:
  1211. * $ref: '#/components/schemas/Page/properties/path'
  1212. * revision_id:
  1213. * $ref: '#/components/schemas/Revision/properties/_id'
  1214. * new_path:
  1215. * type: string
  1216. * description: new path
  1217. * example: /user/alice/new_test
  1218. * create_redirect:
  1219. * type: boolean
  1220. * description: whether redirect page
  1221. * required:
  1222. * - page_id
  1223. * responses:
  1224. * 200:
  1225. * description: Succeeded to rename page.
  1226. * content:
  1227. * application/json:
  1228. * schema:
  1229. * properties:
  1230. * ok:
  1231. * $ref: '#/components/schemas/V1Response/properties/ok'
  1232. * page:
  1233. * $ref: '#/components/schemas/Page'
  1234. * 403:
  1235. * $ref: '#/components/responses/403'
  1236. * 500:
  1237. * $ref: '#/components/responses/500'
  1238. */
  1239. /**
  1240. * @api {post} /pages.rename Rename page
  1241. * @apiName RenamePage
  1242. * @apiGroup Page
  1243. *
  1244. * @apiParam {String} page_id Page Id.
  1245. * @apiParam {String} path
  1246. * @apiParam {String} revision_id
  1247. * @apiParam {String} new_path New path name.
  1248. * @apiParam {Bool} create_redirect
  1249. */
  1250. api.rename = async function(req, res) {
  1251. const pageId = req.body.page_id;
  1252. const previousRevision = req.body.revision_id || null;
  1253. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1254. const options = {
  1255. createRedirectPage: (req.body.create_redirect != null),
  1256. updateMetadata: (req.body.remain_metadata == null),
  1257. socketClientId: +req.body.socketClientId || undefined,
  1258. };
  1259. const isRecursively = (req.body.recursively != null);
  1260. if (!Page.isCreatableName(newPagePath)) {
  1261. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  1262. }
  1263. // check whether path starts slash
  1264. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1265. const isExist = await Page.count({ path: newPagePath }) > 0;
  1266. if (isExist) {
  1267. // if page found, cannot cannot rename to that path
  1268. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  1269. }
  1270. let page;
  1271. try {
  1272. page = await Page.findByIdAndViewer(pageId, req.user);
  1273. if (page == null) {
  1274. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1275. }
  1276. if (!page.isUpdatable(previousRevision)) {
  1277. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1278. }
  1279. if (isRecursively) {
  1280. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  1281. }
  1282. else {
  1283. page = await Page.rename(page, newPagePath, req.user, options);
  1284. }
  1285. }
  1286. catch (err) {
  1287. logger.error(err);
  1288. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  1289. }
  1290. const result = {};
  1291. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1292. res.json(ApiResponse.success(result));
  1293. try {
  1294. // global notification
  1295. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_MOVE, page, req.user, {
  1296. oldPath: req.body.path,
  1297. });
  1298. }
  1299. catch (err) {
  1300. logger.error('Move notification failed', err);
  1301. }
  1302. return page;
  1303. };
  1304. /**
  1305. * @swagger
  1306. *
  1307. * /pages.duplicate:
  1308. * post:
  1309. * tags: [Pages]
  1310. * operationId: duplicatePage
  1311. * summary: /pages.duplicate
  1312. * description: Duplicate page
  1313. * requestBody:
  1314. * content:
  1315. * application/json:
  1316. * schema:
  1317. * properties:
  1318. * page_id:
  1319. * $ref: '#/components/schemas/Page/properties/_id'
  1320. * new_path:
  1321. * $ref: '#/components/schemas/Page/properties/path'
  1322. * required:
  1323. * - page_id
  1324. * responses:
  1325. * 200:
  1326. * description: Succeeded to duplicate page.
  1327. * content:
  1328. * application/json:
  1329. * schema:
  1330. * properties:
  1331. * ok:
  1332. * $ref: '#/components/schemas/V1Response/properties/ok'
  1333. * page:
  1334. * $ref: '#/components/schemas/Page'
  1335. * tags:
  1336. * $ref: '#/components/schemas/Tags'
  1337. * 403:
  1338. * $ref: '#/components/responses/403'
  1339. * 500:
  1340. * $ref: '#/components/responses/500'
  1341. */
  1342. /**
  1343. * @api {post} /pages.duplicate Duplicate page
  1344. * @apiName DuplicatePage
  1345. * @apiGroup Page
  1346. *
  1347. * @apiParam {String} page_id Page Id.
  1348. * @apiParam {String} new_path New path name.
  1349. */
  1350. api.duplicate = async function(req, res) {
  1351. const pageId = req.body.page_id;
  1352. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1353. const page = await Page.findByIdAndViewer(pageId, req.user);
  1354. if (page == null) {
  1355. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1356. }
  1357. // check whether path starts slash
  1358. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1359. await page.populateDataToShowRevision();
  1360. const originTags = await page.findRelatedTagsById();
  1361. req.body.path = newPagePath;
  1362. req.body.body = page.revision.body;
  1363. req.body.grant = page.grant;
  1364. req.body.grantedUsers = page.grantedUsers;
  1365. req.body.grantUserGroupId = page.grantedGroup;
  1366. req.body.pageTags = originTags;
  1367. return api.create(req, res);
  1368. };
  1369. /**
  1370. * @api {post} /pages.unlink Remove the redirecting page
  1371. * @apiName UnlinkPage
  1372. * @apiGroup Page
  1373. *
  1374. * @apiParam {String} page_id Page Id.
  1375. * @apiParam {String} revision_id
  1376. */
  1377. api.unlink = async function(req, res) {
  1378. const path = req.body.path;
  1379. try {
  1380. await Page.removeRedirectOriginPageByPath(path);
  1381. logger.debug('Redirect Page deleted', path);
  1382. }
  1383. catch (err) {
  1384. logger.error('Error occured while get setting', err);
  1385. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1386. }
  1387. const result = { path };
  1388. return res.json(ApiResponse.success(result));
  1389. };
  1390. return actions;
  1391. };