page.js 50 KB

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