page.js 35 KB

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