page.js 54 KB

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