page.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. const debug = require('debug')('growi:routes:page')
  4. , logger = require('@alias/logger')('growi:routes:page')
  5. , Page = crowi.model('Page')
  6. , User = crowi.model('User')
  7. , Config = crowi.model('Config')
  8. , config = crowi.getConfig()
  9. , Revision = crowi.model('Revision')
  10. , Bookmark = crowi.model('Bookmark')
  11. , PageGroupRelation = crowi.model('PageGroupRelation')
  12. , UpdatePost = crowi.model('UpdatePost')
  13. , ApiResponse = require('../util/apiResponse')
  14. , interceptorManager = crowi.getInterceptorManager()
  15. , pagePathUtil = require('../util/pagePathUtil')
  16. , swig = require('swig-templates')
  17. , getToday = require('../util/getToday')
  18. , globalNotificationService = crowi.getGlobalNotificationService()
  19. , actions = {};
  20. // register page events
  21. const pageEvent = crowi.event('page');
  22. pageEvent.on('create', function(page, user, socketClientId) {
  23. page = serializeToObj(page);
  24. crowi.getIo().sockets.emit('page:create', {page, user, socketClientId});
  25. });
  26. pageEvent.on('update', function(page, user, socketClientId) {
  27. page = serializeToObj(page);
  28. crowi.getIo().sockets.emit('page:update', {page, user, socketClientId});
  29. });
  30. pageEvent.on('delete', function(page, user, socketClientId) {
  31. page = serializeToObj(page);
  32. crowi.getIo().sockets.emit('page:delete', {page, user, socketClientId});
  33. });
  34. function serializeToObj(page) {
  35. const returnObj = page.toObject();
  36. if (page.revisionHackmdSynced != null && page.revisionHackmdSynced._id != null) {
  37. returnObj.revisionHackmdSynced = page.revisionHackmdSynced._id;
  38. }
  39. return returnObj;
  40. }
  41. function getPathFromRequest(req) {
  42. const path = '/' + (req.params[0] || '');
  43. return path.replace(/\.md$/, '');
  44. }
  45. function isUserPage(path) {
  46. if (path.match(/^\/user\/[^/]+\/?$/)) {
  47. return true;
  48. }
  49. return false;
  50. }
  51. // TODO: total とかでちゃんと計算する
  52. function generatePager(options) {
  53. let next = null,
  54. prev = null;
  55. const offset = parseInt(options.offset, 10),
  56. limit = parseInt(options.limit, 10),
  57. length = options.length || 0;
  58. if (offset > 0) {
  59. prev = offset - limit;
  60. if (prev < 0) {
  61. prev = 0;
  62. }
  63. }
  64. if (length < limit) {
  65. next = null;
  66. }
  67. else {
  68. next = offset + limit;
  69. }
  70. return {
  71. prev: prev,
  72. next: next,
  73. offset: offset,
  74. };
  75. }
  76. // user notification
  77. // TODO create '/service/user-notification' module
  78. async function notifyToSlackByUser(page, user, slackChannels, updateOrCreate, previousRevision) {
  79. await page.updateSlackChannel(slackChannels)
  80. .catch(err => {
  81. logger.error('Error occured in updating slack channels: ', err);
  82. });
  83. if (crowi.slack) {
  84. const promises = slackChannels.split(',').map(function(chan) {
  85. return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
  86. });
  87. Promise.all(promises)
  88. .catch(err => {
  89. logger.error('Error occured in sending slack notification: ', err);
  90. });
  91. }
  92. }
  93. /**
  94. * switch action by behaviorType
  95. */
  96. actions.pageListShowWrapper = function(req, res) {
  97. const behaviorType = Config.behaviorType(config);
  98. if (!behaviorType || 'crowi' === behaviorType) {
  99. return actions.pageListShow(req, res);
  100. }
  101. else {
  102. return actions.pageListShowForCrowiPlus(req, res);
  103. }
  104. };
  105. /**
  106. * switch action by behaviorType
  107. */
  108. actions.pageShowWrapper = function(req, res) {
  109. const behaviorType = Config.behaviorType(config);
  110. if (!behaviorType || 'crowi' === behaviorType) {
  111. return actions.pageShow(req, res);
  112. }
  113. else {
  114. return actions.pageShowForCrowiPlus(req, res);
  115. }
  116. };
  117. /**
  118. * switch action by behaviorType
  119. */
  120. actions.trashPageListShowWrapper = function(req, res) {
  121. const behaviorType = Config.behaviorType(config);
  122. if (!behaviorType || 'crowi' === behaviorType) {
  123. // Crowi behavior for '/trash/*'
  124. return actions.deletedPageListShow(req, res);
  125. }
  126. else {
  127. // redirect to '/trash'
  128. return res.redirect('/trash');
  129. }
  130. };
  131. /**
  132. * switch action by behaviorType
  133. */
  134. actions.trashPageShowWrapper = function(req, res) {
  135. const behaviorType = Config.behaviorType(config);
  136. if (!behaviorType || 'crowi' === behaviorType) {
  137. // redirect to '/trash/'
  138. return res.redirect('/trash/');
  139. }
  140. else {
  141. // Crowi behavior for '/trash/*'
  142. return actions.deletedPageListShow(req, res);
  143. }
  144. };
  145. /**
  146. * switch action by behaviorType
  147. */
  148. actions.deletedPageListShowWrapper = function(req, res) {
  149. const behaviorType = Config.behaviorType(config);
  150. if (!behaviorType || 'crowi' === behaviorType) {
  151. // Crowi behavior for '/trash/*'
  152. return actions.deletedPageListShow(req, res);
  153. }
  154. else {
  155. const path = '/trash' + getPathFromRequest(req);
  156. return res.redirect(path);
  157. }
  158. };
  159. actions.pageListShow = function(req, res) {
  160. let path = getPathFromRequest(req);
  161. const limit = 50;
  162. const offset = parseInt(req.query.offset) || 0;
  163. const SEENER_THRESHOLD = 10;
  164. // add slash if root
  165. path = path + (path == '/' ? '' : '/');
  166. debug('Page list show', path);
  167. // index page
  168. const pagerOptions = {
  169. offset: offset,
  170. limit: limit
  171. };
  172. const queryOptions = {
  173. offset: offset,
  174. limit: limit + 1,
  175. isPopulateRevisionBody: Config.isEnabledTimeline(config),
  176. };
  177. const renderVars = {
  178. page: null,
  179. path: path,
  180. isPortal: false,
  181. pages: [],
  182. tree: [],
  183. };
  184. Page.hasPortalPage(path, req.user, req.query.revision)
  185. .then(function(portalPage) {
  186. renderVars.page = portalPage;
  187. renderVars.isPortal = (portalPage != null);
  188. if (portalPage) {
  189. renderVars.revision = portalPage.revision;
  190. renderVars.pageIdOnHackmd = portalPage.pageIdOnHackmd;
  191. renderVars.revisionHackmdSynced = portalPage.revisionHackmdSynced;
  192. renderVars.hasDraftOnHackmd = portalPage.hasDraftOnHackmd;
  193. return Revision.findRevisionList(portalPage.path, {});
  194. }
  195. else {
  196. return Promise.resolve([]);
  197. }
  198. })
  199. .then(function(tree) {
  200. renderVars.tree = tree;
  201. return Page.findListByStartWith(path, req.user, queryOptions);
  202. })
  203. .then(function(pageList) {
  204. if (pageList.length > limit) {
  205. pageList.pop();
  206. }
  207. pagerOptions.length = pageList.length;
  208. renderVars.viewConfig = {
  209. seener_threshold: SEENER_THRESHOLD,
  210. };
  211. renderVars.pager = generatePager(pagerOptions);
  212. renderVars.pages = pagePathUtil.encodePagesPath(pageList);
  213. })
  214. .then(() => {
  215. return PageGroupRelation.findByPage(renderVars.page);
  216. })
  217. .then((pageGroupRelation) => {
  218. if (pageGroupRelation != null) {
  219. renderVars.pageRelatedGroup = pageGroupRelation.relatedGroup;
  220. }
  221. })
  222. .then(() => {
  223. res.render('customlayout-selector/page_list', renderVars);
  224. }).catch(function(err) {
  225. debug('Error on rendering pageListShow', err);
  226. });
  227. };
  228. actions.pageListShowForCrowiPlus = function(req, res) {
  229. let path = getPathFromRequest(req);
  230. // omit the slash of the last
  231. path = path.replace((/\/$/), '');
  232. // redirect
  233. return res.redirect(path);
  234. };
  235. actions.pageShowForCrowiPlus = function(req, res) {
  236. const path = getPathFromRequest(req);
  237. const limit = 50;
  238. const offset = parseInt(req.query.offset) || 0;
  239. const SEENER_THRESHOLD = 10;
  240. // index page
  241. const pagerOptions = {
  242. offset: offset,
  243. limit: limit
  244. };
  245. const queryOptions = {
  246. offset: offset,
  247. limit: limit + 1,
  248. isPopulateRevisionBody: Config.isEnabledTimeline(config),
  249. includeDeletedPage: path.startsWith('/trash/'),
  250. };
  251. const renderVars = {
  252. path: path,
  253. page: null,
  254. revision: {},
  255. author: false,
  256. pages: [],
  257. tree: [],
  258. pageRelatedGroup: null,
  259. template: null,
  260. revisionHackmdSynced: null,
  261. hasDraftOnHackmd: false,
  262. slack: '',
  263. };
  264. let view = 'customlayout-selector/page';
  265. let isRedirect = false;
  266. Page.findPage(path, req.user, req.query.revision)
  267. .then(function(page) {
  268. debug('Page found', page._id, page.path);
  269. // redirect
  270. if (page.redirectTo) {
  271. debug(`Redirect to '${page.redirectTo}'`);
  272. isRedirect = true;
  273. return res.redirect(encodeURI(page.redirectTo + '?redirectFrom=' + pagePathUtil.encodePagePath(page.path)));
  274. }
  275. renderVars.page = page;
  276. if (page) {
  277. renderVars.path = page.path;
  278. renderVars.revision = page.revision;
  279. renderVars.author = page.revision.author;
  280. renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
  281. renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
  282. renderVars.hasDraftOnHackmd = page.hasDraftOnHackmd;
  283. return Revision.findRevisionList(page.path, {})
  284. .then(function(tree) {
  285. renderVars.tree = tree;
  286. })
  287. .then(() => {
  288. return PageGroupRelation.findByPage(renderVars.page);
  289. })
  290. .then((pageGroupRelation) => {
  291. if (pageGroupRelation != null) {
  292. renderVars.pageRelatedGroup = pageGroupRelation.relatedGroup;
  293. }
  294. })
  295. .then(() => {
  296. return getSlackChannels(page);
  297. })
  298. .then((channels) => {
  299. renderVars.slack = channels;
  300. })
  301. .then(function() {
  302. const userPage = isUserPage(page.path);
  303. let userData = null;
  304. if (userPage) {
  305. // change template
  306. view = 'customlayout-selector/user_page';
  307. return User.findUserByUsername(User.getUsernameByPath(page.path))
  308. .then(function(data) {
  309. if (data === null) {
  310. throw new Error('The user not found.');
  311. }
  312. userData = data;
  313. renderVars.pageUser = userData;
  314. return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
  315. }).then(function(bookmarkList) {
  316. renderVars.bookmarkList = bookmarkList;
  317. return Page.findListByCreator(userData, {limit: 10}, req.user);
  318. }).then(function(createdList) {
  319. renderVars.createdList = createdList;
  320. return Promise.resolve();
  321. }).catch(function(err) {
  322. debug('Error on finding user related entities', err);
  323. // pass
  324. });
  325. }
  326. });
  327. }
  328. })
  329. // page is not found or user is forbidden
  330. .catch(function(err) {
  331. let isForbidden = false;
  332. if (err.name === 'UserHasNoGrantException') {
  333. isForbidden = true;
  334. }
  335. if (isForbidden) {
  336. view = 'customlayout-selector/forbidden';
  337. return;
  338. }
  339. else {
  340. view = 'customlayout-selector/not_found';
  341. // look for templates
  342. return Page.findTemplate(path)
  343. .then(template => {
  344. if (template) {
  345. template = replacePlaceholders(template, req);
  346. }
  347. renderVars.template = template;
  348. });
  349. }
  350. })
  351. // get list pages
  352. .then(function() {
  353. if (!isRedirect) {
  354. Page.findListWithDescendants(path, req.user, queryOptions)
  355. .then(function(pageList) {
  356. if (pageList.length > limit) {
  357. pageList.pop();
  358. }
  359. pagerOptions.length = pageList.length;
  360. renderVars.viewConfig = {
  361. seener_threshold: SEENER_THRESHOLD,
  362. };
  363. renderVars.pager = generatePager(pagerOptions);
  364. renderVars.pages = pagePathUtil.encodePagesPath(pageList);
  365. return;
  366. })
  367. .then(function() {
  368. return interceptorManager.process('beforeRenderPage', req, res, renderVars);
  369. })
  370. .then(function() {
  371. res.render(req.query.presentation ? 'page_presentation' : view, renderVars);
  372. })
  373. .catch(function(err) {
  374. logger.error('Error on rendering pageListShowForCrowiPlus', err);
  375. });
  376. }
  377. });
  378. };
  379. const getSlackChannels = async page => {
  380. if (page.extended.slack) {
  381. return page.extended.slack;
  382. }
  383. else {
  384. const data = await UpdatePost.findSettingsByPath(page.path);
  385. const channels = data.map(e => e.channel).join(', ');
  386. return channels;
  387. }
  388. };
  389. const replacePlaceholders = (template, req) => {
  390. const definitions = {
  391. pagepath: getPathFromRequest(req),
  392. username: req.user.name,
  393. today: getToday(),
  394. };
  395. const compiledTemplate = swig.compile(template);
  396. return compiledTemplate(definitions);
  397. };
  398. actions.deletedPageListShow = function(req, res) {
  399. const path = '/trash' + getPathFromRequest(req);
  400. const limit = 50;
  401. const offset = parseInt(req.query.offset) || 0;
  402. // index page
  403. const pagerOptions = {
  404. offset: offset,
  405. limit: limit
  406. };
  407. const queryOptions = {
  408. offset: offset,
  409. limit: limit + 1,
  410. includeDeletedPage: true,
  411. };
  412. const renderVars = {
  413. page: null,
  414. path: path,
  415. pages: [],
  416. };
  417. Page.findListWithDescendants(path, req.user, queryOptions)
  418. .then(function(pageList) {
  419. if (pageList.length > limit) {
  420. pageList.pop();
  421. }
  422. pagerOptions.length = pageList.length;
  423. renderVars.pager = generatePager(pagerOptions);
  424. renderVars.pages = pagePathUtil.encodePagesPath(pageList);
  425. res.render('customlayout-selector/page_list', renderVars);
  426. }).catch(function(err) {
  427. debug('Error on rendering deletedPageListShow', err);
  428. });
  429. };
  430. actions.search = function(req, res) {
  431. // spec: ?q=query&sort=sort_order&author=author_filter
  432. const query = req.query.q;
  433. const search = require('../util/search')(crowi);
  434. search.searchPageByKeyword(query)
  435. .then(function(pages) {
  436. debug('pages', pages);
  437. if (pages.hits.total <= 0) {
  438. return Promise.resolve([]);
  439. }
  440. const ids = pages.hits.hits.map(function(page) {
  441. return page._id;
  442. });
  443. return Page.findListByPageIds(ids);
  444. }).then(function(pages) {
  445. res.render('customlayout-selector/page_list', {
  446. path: '/',
  447. pages: pagePathUtil.encodePagesPath(pages),
  448. pager: generatePager({offset: 0, limit: 50})
  449. });
  450. }).catch(function(err) {
  451. debug('search error', err);
  452. });
  453. };
  454. async function renderPage(pageData, req, res, isForbidden) {
  455. if (!pageData) {
  456. let view = 'customlayout-selector/not_found';
  457. let template = undefined;
  458. // forbidden
  459. if (isForbidden) {
  460. view = 'customlayout-selector/forbidden';
  461. }
  462. else {
  463. const path = getPathFromRequest(req);
  464. template = await Page.findTemplate(path);
  465. if (template != null) {
  466. template = replacePlaceholders(template, req);
  467. }
  468. }
  469. return res.render(view, {
  470. author: {},
  471. page: false,
  472. template,
  473. });
  474. }
  475. if (pageData.redirectTo) {
  476. return res.redirect(encodeURI(pageData.redirectTo + '?redirectFrom=' + pagePathUtil.encodePagePath(pageData.path)));
  477. }
  478. const renderVars = {
  479. path: pageData.path,
  480. page: pageData,
  481. revision: pageData.revision || {},
  482. author: pageData.revision.author || false,
  483. slack: '',
  484. };
  485. const userPage = isUserPage(pageData.path);
  486. let userData = null;
  487. Revision.findRevisionList(pageData.path, {})
  488. .then(function(tree) {
  489. renderVars.tree = tree;
  490. })
  491. .then(() => {
  492. return PageGroupRelation.findByPage(renderVars.page);
  493. })
  494. .then((pageGroupRelation) => {
  495. if (pageGroupRelation != null) {
  496. renderVars.pageRelatedGroup = pageGroupRelation.relatedGroup;
  497. }
  498. })
  499. .then(() => {
  500. return getSlackChannels(pageData);
  501. })
  502. .then(channels => {
  503. renderVars.slack = channels;
  504. })
  505. .then(function() {
  506. if (userPage) {
  507. return User.findUserByUsername(User.getUsernameByPath(pageData.path))
  508. .then(function(data) {
  509. if (data === null) {
  510. throw new Error('The user not found.');
  511. }
  512. userData = data;
  513. renderVars.pageUser = userData;
  514. return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
  515. }).then(function(bookmarkList) {
  516. renderVars.bookmarkList = bookmarkList;
  517. return Page.findListByCreator(userData, {limit: 10}, req.user);
  518. }).then(function(createdList) {
  519. renderVars.createdList = createdList;
  520. return Promise.resolve();
  521. }).catch(function(err) {
  522. debug('Error on finding user related entities', err);
  523. // pass
  524. });
  525. }
  526. else {
  527. return Promise.resolve();
  528. }
  529. }).then(function() {
  530. return interceptorManager.process('beforeRenderPage', req, res, renderVars);
  531. }).then(function() {
  532. let view = 'customlayout-selector/page';
  533. if (userData) {
  534. view = 'customlayout-selector/user_page';
  535. }
  536. res.render(req.query.presentation ? 'page_presentation' : view, renderVars);
  537. }).catch(function(err) {
  538. debug('Error: renderPage()', err);
  539. if (err) {
  540. res.redirect('/');
  541. }
  542. });
  543. }
  544. actions.pageShow = function(req, res) {
  545. const path = getPathFromRequest(req);
  546. // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ
  547. const isMarkdown = req.params[0].match(/.+\.md$/) || false;
  548. res.locals.path = path;
  549. Page.findPage(path, req.user, req.query.revision)
  550. .then(function(page) {
  551. debug('Page found', page._id, page.path);
  552. if (isMarkdown) {
  553. res.set('Content-Type', 'text/plain');
  554. return res.send(page.revision.body);
  555. }
  556. return renderPage(page, req, res);
  557. })
  558. // page is not found or the user is forbidden
  559. .catch(function(err) {
  560. let isForbidden = false;
  561. if (err.name === 'UserHasNoGrantException') {
  562. isForbidden = true;
  563. }
  564. const normalizedPath = Page.normalizePath(path);
  565. if (normalizedPath !== path) {
  566. return res.redirect(normalizedPath);
  567. }
  568. // pageShow は /* にマッチしてる最後の砦なので、creatableName でない routing は
  569. // これ以前に定義されているはずなので、こうしてしまって問題ない。
  570. if (!Page.isCreatableName(path)) {
  571. // 削除済みページの場合 /trash 以下に移動しているので creatableName になっていないので、表示を許可
  572. logger.warn('Page is not creatable name.', path);
  573. res.redirect('/');
  574. return ;
  575. }
  576. if (req.query.revision) {
  577. return res.redirect(pagePathUtil.encodePagePath(path));
  578. }
  579. if (isMarkdown) {
  580. return res.redirect('/');
  581. }
  582. Page.hasPortalPage(path + '/', req.user)
  583. .then(function(page) {
  584. if (page) {
  585. return res.redirect(pagePathUtil.encodePagePath(path) + '/');
  586. }
  587. else {
  588. const fixed = Page.fixToCreatableName(path);
  589. if (fixed !== path) {
  590. logger.warn('fixed page name', fixed);
  591. res.redirect(pagePathUtil.encodePagePath(fixed));
  592. return ;
  593. }
  594. // if guest user
  595. if (!req.user) {
  596. res.redirect('/');
  597. }
  598. // render editor
  599. debug('Catch pageShow', err);
  600. return renderPage(null, req, res, isForbidden);
  601. }
  602. }).catch(function(err) {
  603. debug('Error on rendering pageShow (redirect to portal)', err);
  604. });
  605. });
  606. };
  607. const api = actions.api = {};
  608. /**
  609. * redirector
  610. */
  611. api.redirector = function(req, res) {
  612. const id = req.params.id;
  613. Page.findPageById(id)
  614. .then(function(pageData) {
  615. if (pageData.grant == Page.GRANT_RESTRICTED && !pageData.isGrantedFor(req.user)) {
  616. return Page.pushToGrantedUsers(pageData, req.user);
  617. }
  618. return Promise.resolve(pageData);
  619. }).then(function(page) {
  620. return res.redirect(pagePathUtil.encodePagePath(page.path));
  621. }).catch(function(err) {
  622. return res.redirect('/');
  623. });
  624. };
  625. /**
  626. * @api {get} /pages.list List pages by user
  627. * @apiName ListPage
  628. * @apiGroup Page
  629. *
  630. * @apiParam {String} path
  631. * @apiParam {String} user
  632. */
  633. api.list = function(req, res) {
  634. const username = req.query.user || null;
  635. const path = req.query.path || null;
  636. const limit = 50;
  637. const offset = parseInt(req.query.offset) || 0;
  638. const pagerOptions = { offset: offset, limit: limit };
  639. const queryOptions = { offset: offset, limit: limit + 1};
  640. // Accepts only one of these
  641. if (username === null && path === null) {
  642. return res.json(ApiResponse.error('Parameter user or path is required.'));
  643. }
  644. if (username !== null && path !== null) {
  645. return res.json(ApiResponse.error('Parameter user or path is required.'));
  646. }
  647. let pageFetcher;
  648. if (path === null) {
  649. pageFetcher = User.findUserByUsername(username)
  650. .then(function(user) {
  651. if (user === null) {
  652. throw new Error('The user not found.');
  653. }
  654. return Page.findListByCreator(user, queryOptions, req.user);
  655. });
  656. }
  657. else {
  658. pageFetcher = Page.findListByStartWith(path, req.user, queryOptions);
  659. }
  660. pageFetcher
  661. .then(function(pages) {
  662. if (pages.length > limit) {
  663. pages.pop();
  664. }
  665. pagerOptions.length = pages.length;
  666. const result = {};
  667. result.pages = pagePathUtil.encodePagesPath(pages);
  668. return res.json(ApiResponse.success(result));
  669. }).catch(function(err) {
  670. return res.json(ApiResponse.error(err));
  671. });
  672. };
  673. /**
  674. * @api {post} /pages.create Create new page
  675. * @apiName CreatePage
  676. * @apiGroup Page
  677. *
  678. * @apiParam {String} body
  679. * @apiParam {String} path
  680. * @apiParam {String} grant
  681. */
  682. api.create = async function(req, res) {
  683. const body = req.body.body || null;
  684. const pagePath = req.body.path || null;
  685. const grant = req.body.grant || null;
  686. const grantUserGroupId = req.body.grantUserGroupId || null;
  687. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  688. const slackChannels = req.body.slackChannels || null;
  689. const socketClientId = req.body.socketClientId || undefined;
  690. if (body === null || pagePath === null) {
  691. return res.json(ApiResponse.error('Parameters body and path are required.'));
  692. }
  693. const ignoreNotFound = true;
  694. const createdPage = await Page.findPage(pagePath, req.user, null, ignoreNotFound)
  695. .then(function(data) {
  696. if (data !== null) {
  697. throw new Error('Page exists');
  698. }
  699. const options = {grant, grantUserGroupId, socketClientId};
  700. return Page.create(pagePath, body, req.user, options);
  701. })
  702. .catch(function(err) {
  703. return res.json(ApiResponse.error(err));
  704. });
  705. const result = { page: serializeToObj(createdPage) };
  706. result.page.lastUpdateUser = User.filterToPublicFields(createdPage.lastUpdateUser);
  707. result.page.creator = User.filterToPublicFields(createdPage.creator);
  708. res.json(ApiResponse.success(result));
  709. // global notification
  710. try {
  711. await globalNotificationService.notifyPageCreate(createdPage);
  712. }
  713. catch (err) {
  714. logger.error(err);
  715. }
  716. // user notification
  717. if (isSlackEnabled && slackChannels != null) {
  718. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  719. }
  720. };
  721. /**
  722. * @api {post} /pages.update Update page
  723. * @apiName UpdatePage
  724. * @apiGroup Page
  725. *
  726. * @apiParam {String} body
  727. * @apiParam {String} page_id
  728. * @apiParam {String} revision_id
  729. * @apiParam {String} grant
  730. *
  731. * In the case of the page exists:
  732. * - If revision_id is specified => update the page,
  733. * - If revision_id is not specified => force update by the new contents.
  734. */
  735. api.update = async function(req, res) {
  736. const pageBody = req.body.body || null;
  737. const pageId = req.body.page_id || null;
  738. const revisionId = req.body.revision_id || null;
  739. const grant = req.body.grant || null;
  740. const grantUserGroupId = req.body.grantUserGroupId || null;
  741. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  742. const slackChannels = req.body.slackChannels || null;
  743. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  744. const socketClientId = req.body.socketClientId || undefined;
  745. if (pageId === null || pageBody === null) {
  746. return res.json(ApiResponse.error('page_id and body are required.'));
  747. }
  748. let previousRevision = undefined;
  749. let updatedPage = await Page.findPageByIdAndGrantedUser(pageId, req.user)
  750. .then(function(pageData) {
  751. if (pageData && revisionId !== null && !pageData.isUpdatable(revisionId)) {
  752. throw new Error('Posted param "revisionId" is outdated.');
  753. }
  754. const options = {isSyncRevisionToHackmd, socketClientId};
  755. if (grant != null) {
  756. options.grant = grant;
  757. }
  758. if (grantUserGroupId != null) {
  759. options.grantUserGroupId = grantUserGroupId;
  760. }
  761. // store previous revision
  762. previousRevision = pageData.revision;
  763. return Page.updatePage(pageData, pageBody, req.user, options);
  764. })
  765. .catch(function(err) {
  766. logger.error('error on _api/pages.update', err);
  767. res.json(ApiResponse.error(err));
  768. });
  769. const result = { page: serializeToObj(updatedPage) };
  770. result.page.lastUpdateUser = User.filterToPublicFields(updatedPage.lastUpdateUser);
  771. res.json(ApiResponse.success(result));
  772. // global notification
  773. try {
  774. await globalNotificationService.notifyPageEdit(updatedPage);
  775. }
  776. catch (err) {
  777. logger.error(err);
  778. }
  779. // user notification
  780. if (isSlackEnabled && slackChannels != null) {
  781. await notifyToSlackByUser(updatedPage, req.user, slackChannels, 'update', previousRevision);
  782. }
  783. };
  784. /**
  785. * @api {get} /pages.get Get page data
  786. * @apiName GetPage
  787. * @apiGroup Page
  788. *
  789. * @apiParam {String} page_id
  790. * @apiParam {String} path
  791. * @apiParam {String} revision_id
  792. */
  793. api.get = function(req, res) {
  794. const pagePath = req.query.path || null;
  795. const pageId = req.query.page_id || null; // TODO: handling
  796. const revisionId = req.query.revision_id || null;
  797. if (!pageId && !pagePath) {
  798. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  799. }
  800. let pageFinder;
  801. if (pageId) { // prioritized
  802. pageFinder = Page.findPageByIdAndGrantedUser(pageId, req.user);
  803. }
  804. else if (pagePath) {
  805. pageFinder = Page.findPage(pagePath, req.user, revisionId);
  806. }
  807. pageFinder.then(function(pageData) {
  808. const result = {};
  809. result.page = pageData; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  810. return res.json(ApiResponse.success(result));
  811. }).catch(function(err) {
  812. return res.json(ApiResponse.error(err));
  813. });
  814. };
  815. /**
  816. * @api {post} /pages.seen Mark as seen user
  817. * @apiName SeenPage
  818. * @apiGroup Page
  819. *
  820. * @apiParam {String} page_id Page Id.
  821. */
  822. api.seen = function(req, res) {
  823. const pageId = req.body.page_id;
  824. if (!pageId) {
  825. return res.json(ApiResponse.error('page_id required'));
  826. }
  827. Page.findPageByIdAndGrantedUser(pageId, req.user)
  828. .then(function(page) {
  829. return page.seen(req.user);
  830. }).then(function(user) {
  831. const result = {};
  832. result.seenUser = user;
  833. return res.json(ApiResponse.success(result));
  834. }).catch(function(err) {
  835. debug('Seen user update error', err);
  836. return res.json(ApiResponse.error(err));
  837. });
  838. };
  839. /**
  840. * @api {post} /likes.add Like page
  841. * @apiName LikePage
  842. * @apiGroup Page
  843. *
  844. * @apiParam {String} page_id Page Id.
  845. */
  846. api.like = function(req, res) {
  847. const id = req.body.page_id;
  848. Page.findPageByIdAndGrantedUser(id, req.user)
  849. .then(function(pageData) {
  850. return pageData.like(req.user);
  851. })
  852. .then(function(page) {
  853. const result = {page: page};
  854. res.json(ApiResponse.success(result));
  855. return page;
  856. })
  857. .then((page) => {
  858. // global notification
  859. return globalNotificationService.notifyPageLike(page, req.user);
  860. })
  861. .catch(function(err) {
  862. debug('Like failed', err);
  863. return res.json(ApiResponse.error({}));
  864. });
  865. };
  866. /**
  867. * @api {post} /likes.remove Unlike page
  868. * @apiName UnlikePage
  869. * @apiGroup Page
  870. *
  871. * @apiParam {String} page_id Page Id.
  872. */
  873. api.unlike = function(req, res) {
  874. const id = req.body.page_id;
  875. Page.findPageByIdAndGrantedUser(id, req.user)
  876. .then(function(pageData) {
  877. return pageData.unlike(req.user);
  878. }).then(function(data) {
  879. const result = {page: data};
  880. return res.json(ApiResponse.success(result));
  881. }).catch(function(err) {
  882. debug('Unlike failed', err);
  883. return res.json(ApiResponse.error({}));
  884. });
  885. };
  886. /**
  887. * @api {get} /pages.updatePost
  888. * @apiName Get UpdatePost setting list
  889. * @apiGroup Page
  890. *
  891. * @apiParam {String} path
  892. */
  893. api.getUpdatePost = function(req, res) {
  894. const path = req.query.path;
  895. const UpdatePost = crowi.model('UpdatePost');
  896. if (!path) {
  897. return res.json(ApiResponse.error({}));
  898. }
  899. UpdatePost.findSettingsByPath(path)
  900. .then(function(data) {
  901. data = data.map(function(e) {
  902. return e.channel;
  903. });
  904. debug('Found updatePost data', data);
  905. const result = {updatePost: data};
  906. return res.json(ApiResponse.success(result));
  907. }).catch(function(err) {
  908. debug('Error occured while get setting', err);
  909. return res.json(ApiResponse.error({}));
  910. });
  911. };
  912. /**
  913. * @api {post} /pages.remove Remove page
  914. * @apiName RemovePage
  915. * @apiGroup Page
  916. *
  917. * @apiParam {String} page_id Page Id.
  918. * @apiParam {String} revision_id
  919. */
  920. api.remove = function(req, res) {
  921. const pageId = req.body.page_id;
  922. const previousRevision = req.body.revision_id || null;
  923. const socketClientId = req.body.socketClientId || undefined;
  924. // get completely flag
  925. const isCompletely = (req.body.completely != null);
  926. // get recursively flag
  927. const isRecursively = (req.body.recursively != null);
  928. const options = {socketClientId};
  929. Page.findPageByIdAndGrantedUser(pageId, req.user)
  930. .then(function(pageData) {
  931. debug('Delete page', pageData._id, pageData.path);
  932. if (isCompletely) {
  933. if (isRecursively) {
  934. return Page.completelyDeletePageRecursively(pageData, req.user, options);
  935. }
  936. else {
  937. return Page.completelyDeletePage(pageData, req.user, options);
  938. }
  939. }
  940. // else
  941. if (!pageData.isUpdatable(previousRevision)) {
  942. throw new Error('Someone could update this page, so couldn\'t delete.');
  943. }
  944. if (isRecursively) {
  945. return Page.deletePageRecursively(pageData, req.user, options);
  946. }
  947. else {
  948. return Page.deletePage(pageData, req.user, options);
  949. }
  950. })
  951. .then(function(data) {
  952. debug('Page deleted', data.path);
  953. const result = {};
  954. result.page = data; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  955. res.json(ApiResponse.success(result));
  956. return data;
  957. })
  958. .then((page) => {
  959. // global notification
  960. return globalNotificationService.notifyPageDelete(page);
  961. })
  962. .catch(function(err) {
  963. logger.error('Error occured while get setting', err, err.stack);
  964. return res.json(ApiResponse.error('Failed to delete page.'));
  965. });
  966. };
  967. /**
  968. * @api {post} /pages.revertRemove Revert removed page
  969. * @apiName RevertRemovePage
  970. * @apiGroup Page
  971. *
  972. * @apiParam {String} page_id Page Id.
  973. */
  974. api.revertRemove = function(req, res, options) {
  975. const pageId = req.body.page_id;
  976. const socketClientId = req.body.socketClientId || undefined;
  977. // get recursively flag
  978. const isRecursively = (req.body.recursively !== undefined);
  979. Page.findPageByIdAndGrantedUser(pageId, req.user)
  980. .then(function(pageData) {
  981. if (isRecursively) {
  982. return Page.revertDeletedPageRecursively(pageData, req.user, {socketClientId});
  983. }
  984. else {
  985. return Page.revertDeletedPage(pageData, req.user, {socketClientId});
  986. }
  987. }).then(function(data) {
  988. const result = {};
  989. result.page = data; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  990. return res.json(ApiResponse.success(result));
  991. }).catch(function(err) {
  992. logger.error('Error occured while get setting', err, err.stack);
  993. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  994. });
  995. };
  996. /**
  997. * @api {post} /pages.rename Rename page
  998. * @apiName RenamePage
  999. * @apiGroup Page
  1000. *
  1001. * @apiParam {String} page_id Page Id.
  1002. * @apiParam {String} path
  1003. * @apiParam {String} revision_id
  1004. * @apiParam {String} new_path
  1005. * @apiParam {Bool} create_redirect
  1006. */
  1007. api.rename = function(req, res) {
  1008. const pageId = req.body.page_id;
  1009. const previousRevision = req.body.revision_id || null;
  1010. const newPagePath = Page.normalizePath(req.body.new_path);
  1011. const options = {
  1012. createRedirectPage: req.body.create_redirect || 0,
  1013. moveUnderTrees: req.body.move_trees || 0,
  1014. socketClientId: +req.body.socketClientId || undefined,
  1015. };
  1016. const isRecursiveMove = req.body.move_recursively || 0;
  1017. if (!Page.isCreatableName(newPagePath)) {
  1018. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})`));
  1019. }
  1020. Page.findPageByPath(newPagePath)
  1021. .then(function(page) {
  1022. if (page != null) {
  1023. // if page found, cannot cannot rename to that path
  1024. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`));
  1025. }
  1026. Page.findPageById(pageId)
  1027. .then(function(pageData) {
  1028. page = pageData;
  1029. if (!pageData.isUpdatable(previousRevision)) {
  1030. throw new Error('Someone could update this page, so couldn\'t delete.');
  1031. }
  1032. if (isRecursiveMove) {
  1033. return Page.renameRecursively(pageData, newPagePath, req.user, options);
  1034. }
  1035. else {
  1036. return Page.rename(pageData, newPagePath, req.user, options);
  1037. }
  1038. })
  1039. .then(function() {
  1040. const result = {};
  1041. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1042. return res.json(ApiResponse.success(result));
  1043. })
  1044. .then(() => {
  1045. // global notification
  1046. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  1047. })
  1048. .catch(function(err) {
  1049. return res.json(ApiResponse.error('Failed to update page.'));
  1050. });
  1051. });
  1052. };
  1053. /**
  1054. * @api {post} /pages.duplicate Duplicate page
  1055. * @apiName DuplicatePage
  1056. * @apiGroup Page
  1057. *
  1058. * @apiParam {String} page_id Page Id.
  1059. * @apiParam {String} new_path
  1060. */
  1061. api.duplicate = function(req, res) {
  1062. const pageId = req.body.page_id;
  1063. const newPagePath = Page.normalizePath(req.body.new_path);
  1064. Page.findPageById(pageId)
  1065. .then(function(pageData) {
  1066. req.body.path = newPagePath;
  1067. req.body.body = pageData.revision.body;
  1068. req.body.grant = pageData.grant;
  1069. return api.create(req, res);
  1070. });
  1071. };
  1072. /**
  1073. * @api {post} /pages.unlink Remove the redirecting page
  1074. * @apiName UnlinkPage
  1075. * @apiGroup Page
  1076. *
  1077. * @apiParam {String} page_id Page Id.
  1078. * @apiParam {String} revision_id
  1079. */
  1080. api.unlink = function(req, res) {
  1081. const pageId = req.body.page_id;
  1082. Page.findPageByIdAndGrantedUser(pageId, req.user)
  1083. .then(function(pageData) {
  1084. debug('Unlink page', pageData._id, pageData.path);
  1085. return Page.removeRedirectOriginPageByPath(pageData.path)
  1086. .then(() => pageData);
  1087. }).then(function(data) {
  1088. debug('Redirect Page deleted', data.path);
  1089. const result = {};
  1090. result.page = data; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1091. return res.json(ApiResponse.success(result));
  1092. }).catch(function(err) {
  1093. debug('Error occured while get setting', err, err.stack);
  1094. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1095. });
  1096. };
  1097. return actions;
  1098. };