page.js 36 KB

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