page.js 37 KB

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