page.js 48 KB

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