page.js 53 KB

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