page.js 49 KB

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