page.js 39 KB

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