page.js 48 KB

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