page.js 49 KB

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