page.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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. /**
  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. let path = getPathFromRequest(req);
  128. const limit = 50;
  129. const offset = parseInt(req.query.offset) || 0;
  130. const SEENER_THRESHOLD = 10;
  131. // add slash if root
  132. path = path + (path == '/' ? '' : '/');
  133. debug('Page list show', path);
  134. // index page
  135. const pagerOptions = {
  136. offset: offset,
  137. limit: limit
  138. };
  139. const queryOptions = {
  140. offset: offset,
  141. limit: limit + 1,
  142. isPopulateRevisionBody: Config.isEnabledTimeline(config),
  143. };
  144. const 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. const path = '/trash' + getPathFromRequest(req);
  367. const limit = 50;
  368. const offset = parseInt(req.query.offset) || 0;
  369. // index page
  370. const pagerOptions = {
  371. offset: offset,
  372. limit: limit
  373. };
  374. const queryOptions = {
  375. offset: offset,
  376. limit: limit + 1,
  377. includeDeletedPage: true,
  378. };
  379. const 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. const query = req.query.q;
  400. const 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. const 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. const path = getPathFromRequest(req);
  513. // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ
  514. const 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. const pageForm = req.form.pageForm;
  580. const path = pageForm.path;
  581. const body = pageForm.body;
  582. const currentRevision = pageForm.currentRevision;
  583. const grant = pageForm.grant;
  584. const grantUserGroupId = pageForm.grantUserGroupId;
  585. // TODO: make it pluggable
  586. const notify = pageForm.notify || {};
  587. debug('notify: ', notify);
  588. const redirectPath = pagePathUtil.encodePagePath(path);
  589. let pageData = {};
  590. let previousRevision = false;
  591. let updateOrCreate;
  592. // set to render
  593. res.locals.pageForm = pageForm;
  594. // 削除済みページはここで編集不可判定される
  595. if (!Page.isCreatableName(path)) {
  596. res.redirect(redirectPath);
  597. return ;
  598. }
  599. const 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. const api = actions.api = {};
  655. /**
  656. * redirector
  657. */
  658. api.redirector = function(req, res) {
  659. const 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. const username = req.query.user || null;
  682. const path = req.query.path || null;
  683. const limit = 50;
  684. const offset = parseInt(req.query.offset) || 0;
  685. const pagerOptions = { offset: offset, limit: limit };
  686. const 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. let 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. const 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. const body = req.body.body || null;
  731. const pagePath = req.body.path || null;
  732. const grant = req.body.grant || null;
  733. const 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. const 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. const 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. const pageBody = req.body.body || null;
  772. const pageId = req.body.page_id || null;
  773. const revisionId = req.body.revision_id || null;
  774. const grant = req.body.grant || null;
  775. const 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. const 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. const 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. const 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. const 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. const 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. const 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. const 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. const 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. const 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. const path = req.query.path;
  914. const 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. const 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. const pageId = req.body.page_id;
  941. const 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. const 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. const 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. const 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. const pageId = req.body.page_id;
  1026. const previousRevision = req.body.revision_id || null;
  1027. const newPagePath = Page.normalizePath(req.body.new_path);
  1028. const options = {
  1029. createRedirectPage: req.body.create_redirect || 0,
  1030. moveUnderTrees: req.body.move_trees || 0,
  1031. };
  1032. const isRecursiveMove = req.body.move_recursively || 0;
  1033. if (!Page.isCreatableName(newPagePath)) {
  1034. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})`));
  1035. }
  1036. Page.findPageByPath(newPagePath)
  1037. .then(function(page) {
  1038. if (page != null) {
  1039. // if page found, cannot cannot rename to that path
  1040. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`));
  1041. }
  1042. Page.findPageById(pageId)
  1043. .then(function(pageData) {
  1044. page = pageData;
  1045. if (!pageData.isUpdatable(previousRevision)) {
  1046. throw new Error('Someone could update this page, so couldn\'t delete.');
  1047. }
  1048. if (isRecursiveMove) {
  1049. return Page.renameRecursively(pageData, newPagePath, req.user, options);
  1050. }
  1051. else {
  1052. return Page.rename(pageData, newPagePath, req.user, options);
  1053. }
  1054. })
  1055. .then(function() {
  1056. const result = {};
  1057. result.page = page;
  1058. return res.json(ApiResponse.success(result));
  1059. })
  1060. .then(() => {
  1061. // global notification
  1062. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  1063. })
  1064. .catch(function(err) {
  1065. return res.json(ApiResponse.error('Failed to update page.'));
  1066. });
  1067. });
  1068. };
  1069. /**
  1070. * @api {post} /pages.duplicate Duplicate page
  1071. * @apiName DuplicatePage
  1072. * @apiGroup Page
  1073. *
  1074. * @apiParam {String} page_id Page Id.
  1075. * @apiParam {String} new_path
  1076. */
  1077. api.duplicate = function(req, res) {
  1078. const pageId = req.body.page_id;
  1079. const newPagePath = Page.normalizePath(req.body.new_path);
  1080. Page.findPageById(pageId)
  1081. .then(function(pageData) {
  1082. req.body.path = newPagePath;
  1083. req.body.body = pageData.revision.body;
  1084. req.body.grant = pageData.grant;
  1085. return api.create(req, res);
  1086. });
  1087. };
  1088. /**
  1089. * @api {post} /pages.unlink Remove the redirecting page
  1090. * @apiName UnlinkPage
  1091. * @apiGroup Page
  1092. *
  1093. * @apiParam {String} page_id Page Id.
  1094. * @apiParam {String} revision_id
  1095. */
  1096. api.unlink = function(req, res) {
  1097. const pageId = req.body.page_id;
  1098. Page.findPageByIdAndGrantedUser(pageId, req.user)
  1099. .then(function(pageData) {
  1100. debug('Unlink page', pageData._id, pageData.path);
  1101. return Page.removeRedirectOriginPageByPath(pageData.path)
  1102. .then(() => pageData);
  1103. }).then(function(data) {
  1104. debug('Redirect Page deleted', data.path);
  1105. const result = {};
  1106. result.page = data;
  1107. return res.json(ApiResponse.success(result));
  1108. }).catch(function(err) {
  1109. debug('Error occured while get setting', err, err.stack);
  1110. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1111. });
  1112. };
  1113. return actions;
  1114. };