page.js 49 KB

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