page.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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. const api = actions.api = {};
  592. /**
  593. * redirector
  594. */
  595. api.redirector = function(req, res) {
  596. const id = req.params.id;
  597. Page.findPageById(id)
  598. .then(function(pageData) {
  599. if (pageData.grant == Page.GRANT_RESTRICTED && !pageData.isGrantedFor(req.user)) {
  600. return Page.pushToGrantedUsers(pageData, req.user);
  601. }
  602. return Promise.resolve(pageData);
  603. }).then(function(page) {
  604. return res.redirect(pagePathUtil.encodePagePath(page.path));
  605. }).catch(function(err) {
  606. return res.redirect('/');
  607. });
  608. };
  609. /**
  610. * @api {get} /pages.list List pages by user
  611. * @apiName ListPage
  612. * @apiGroup Page
  613. *
  614. * @apiParam {String} path
  615. * @apiParam {String} user
  616. */
  617. api.list = function(req, res) {
  618. const username = req.query.user || null;
  619. const path = req.query.path || null;
  620. const limit = 50;
  621. const offset = parseInt(req.query.offset) || 0;
  622. const pagerOptions = { offset: offset, limit: limit };
  623. const queryOptions = { offset: offset, limit: limit + 1};
  624. // Accepts only one of these
  625. if (username === null && path === null) {
  626. return res.json(ApiResponse.error('Parameter user or path is required.'));
  627. }
  628. if (username !== null && path !== null) {
  629. return res.json(ApiResponse.error('Parameter user or path is required.'));
  630. }
  631. let pageFetcher;
  632. if (path === null) {
  633. pageFetcher = User.findUserByUsername(username)
  634. .then(function(user) {
  635. if (user === null) {
  636. throw new Error('The user not found.');
  637. }
  638. return Page.findListByCreator(user, queryOptions, req.user);
  639. });
  640. }
  641. else {
  642. pageFetcher = Page.findListByStartWith(path, req.user, queryOptions);
  643. }
  644. pageFetcher
  645. .then(function(pages) {
  646. if (pages.length > limit) {
  647. pages.pop();
  648. }
  649. pagerOptions.length = pages.length;
  650. const result = {};
  651. result.pages = pagePathUtil.encodePagesPath(pages);
  652. return res.json(ApiResponse.success(result));
  653. }).catch(function(err) {
  654. return res.json(ApiResponse.error(err));
  655. });
  656. };
  657. /**
  658. * @api {post} /pages.create Create new page
  659. * @apiName CreatePage
  660. * @apiGroup Page
  661. *
  662. * @apiParam {String} body
  663. * @apiParam {String} path
  664. * @apiParam {String} grant
  665. */
  666. api.create = async function(req, res) {
  667. const body = req.body.body || null;
  668. const pagePath = req.body.path || null;
  669. const grant = req.body.grant || null;
  670. const grantUserGroupId = req.body.grantUserGroupId || null;
  671. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  672. const slackChannels = req.body.slackChannels || null;
  673. if (body === null || pagePath === null) {
  674. return res.json(ApiResponse.error('Parameters body and path are required.'));
  675. }
  676. const ignoreNotFound = true;
  677. const createdPage = await Page.findPage(pagePath, req.user, null, ignoreNotFound)
  678. .then(function(data) {
  679. if (data !== null) {
  680. throw new Error('Page exists');
  681. }
  682. return Page.create(pagePath, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
  683. })
  684. .catch(function(err) {
  685. return res.json(ApiResponse.error(err));
  686. });
  687. const result = { page: createdPage.toObject() };
  688. result.page.lastUpdateUser = User.filterToPublicFields(createdPage.lastUpdateUser);
  689. result.page.creator = User.filterToPublicFields(createdPage.creator);
  690. res.json(ApiResponse.success(result));
  691. // global notification
  692. try {
  693. await globalNotificationService.notifyPageCreate(createdPage);
  694. }
  695. catch (err) {
  696. logger.error(err);
  697. }
  698. // user notification
  699. if (isSlackEnabled && slackChannels != null) {
  700. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  701. }
  702. };
  703. /**
  704. * @api {post} /pages.update Update page
  705. * @apiName UpdatePage
  706. * @apiGroup Page
  707. *
  708. * @apiParam {String} body
  709. * @apiParam {String} page_id
  710. * @apiParam {String} revision_id
  711. * @apiParam {String} grant
  712. *
  713. * In the case of the page exists:
  714. * - If revision_id is specified => update the page,
  715. * - If revision_id is not specified => force update by the new contents.
  716. */
  717. api.update = async function(req, res) {
  718. const pageBody = req.body.body || null;
  719. const pageId = req.body.page_id || null;
  720. const revisionId = req.body.revision_id || null;
  721. const grant = req.body.grant || null;
  722. const grantUserGroupId = req.body.grantUserGroupId || null;
  723. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  724. const slackChannels = req.body.slackChannels || null;
  725. if (pageId === null || pageBody === null) {
  726. return res.json(ApiResponse.error('page_id and body are required.'));
  727. }
  728. let previousRevision = undefined;
  729. let updatedPage = await Page.findPageByIdAndGrantedUser(pageId, req.user)
  730. .then(function(pageData) {
  731. if (pageData && revisionId !== null && !pageData.isUpdatable(revisionId)) {
  732. throw new Error('Revision error.');
  733. }
  734. const grantOption = {};
  735. if (grant != null) {
  736. grantOption.grant = grant;
  737. }
  738. if (grantUserGroupId != null) {
  739. grantOption.grantUserGroupId = grantUserGroupId;
  740. }
  741. // store previous revision
  742. previousRevision = pageData.revision;
  743. return Page.updatePage(pageData, pageBody, req.user, grantOption);
  744. })
  745. .catch(function(err) {
  746. debug('error on _api/pages.update', err);
  747. res.json(ApiResponse.error(err));
  748. });
  749. const result = { page: updatedPage.toObject() };
  750. result.page.lastUpdateUser = User.filterToPublicFields(updatedPage.lastUpdateUser);
  751. res.json(ApiResponse.success(result));
  752. // global notification
  753. try {
  754. await globalNotificationService.notifyPageEdit(updatedPage);
  755. }
  756. catch (err) {
  757. logger.error(err);
  758. }
  759. // user notification
  760. if (isSlackEnabled && slackChannels != null) {
  761. await notifyToSlackByUser(updatedPage, req.user, slackChannels, 'update', previousRevision);
  762. }
  763. };
  764. /**
  765. * @api {get} /pages.get Get page data
  766. * @apiName GetPage
  767. * @apiGroup Page
  768. *
  769. * @apiParam {String} page_id
  770. * @apiParam {String} path
  771. * @apiParam {String} revision_id
  772. */
  773. api.get = function(req, res) {
  774. const pagePath = req.query.path || null;
  775. const pageId = req.query.page_id || null; // TODO: handling
  776. const revisionId = req.query.revision_id || null;
  777. if (!pageId && !pagePath) {
  778. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  779. }
  780. let pageFinder;
  781. if (pageId) { // prioritized
  782. pageFinder = Page.findPageByIdAndGrantedUser(pageId, req.user);
  783. }
  784. else if (pagePath) {
  785. pageFinder = Page.findPage(pagePath, req.user, revisionId);
  786. }
  787. pageFinder.then(function(pageData) {
  788. const result = {};
  789. result.page = pageData;
  790. return res.json(ApiResponse.success(result));
  791. }).catch(function(err) {
  792. return res.json(ApiResponse.error(err));
  793. });
  794. };
  795. /**
  796. * @api {post} /pages.seen Mark as seen user
  797. * @apiName SeenPage
  798. * @apiGroup Page
  799. *
  800. * @apiParam {String} page_id Page Id.
  801. */
  802. api.seen = function(req, res) {
  803. const pageId = req.body.page_id;
  804. if (!pageId) {
  805. return res.json(ApiResponse.error('page_id required'));
  806. }
  807. Page.findPageByIdAndGrantedUser(pageId, req.user)
  808. .then(function(page) {
  809. return page.seen(req.user);
  810. }).then(function(user) {
  811. const result = {};
  812. result.seenUser = user;
  813. return res.json(ApiResponse.success(result));
  814. }).catch(function(err) {
  815. debug('Seen user update error', err);
  816. return res.json(ApiResponse.error(err));
  817. });
  818. };
  819. /**
  820. * @api {post} /likes.add Like page
  821. * @apiName LikePage
  822. * @apiGroup Page
  823. *
  824. * @apiParam {String} page_id Page Id.
  825. */
  826. api.like = function(req, res) {
  827. const id = req.body.page_id;
  828. Page.findPageByIdAndGrantedUser(id, req.user)
  829. .then(function(pageData) {
  830. return pageData.like(req.user);
  831. })
  832. .then(function(page) {
  833. const result = {page: page};
  834. res.json(ApiResponse.success(result));
  835. return page;
  836. })
  837. .then((page) => {
  838. // global notification
  839. return globalNotificationService.notifyPageLike(page, req.user);
  840. })
  841. .catch(function(err) {
  842. debug('Like failed', err);
  843. return res.json(ApiResponse.error({}));
  844. });
  845. };
  846. /**
  847. * @api {post} /likes.remove Unlike page
  848. * @apiName UnlikePage
  849. * @apiGroup Page
  850. *
  851. * @apiParam {String} page_id Page Id.
  852. */
  853. api.unlike = function(req, res) {
  854. const id = req.body.page_id;
  855. Page.findPageByIdAndGrantedUser(id, req.user)
  856. .then(function(pageData) {
  857. return pageData.unlike(req.user);
  858. }).then(function(data) {
  859. const result = {page: data};
  860. return res.json(ApiResponse.success(result));
  861. }).catch(function(err) {
  862. debug('Unlike failed', err);
  863. return res.json(ApiResponse.error({}));
  864. });
  865. };
  866. /**
  867. * @api {get} /pages.updatePost
  868. * @apiName Get UpdatePost setting list
  869. * @apiGroup Page
  870. *
  871. * @apiParam {String} path
  872. */
  873. api.getUpdatePost = function(req, res) {
  874. const path = req.query.path;
  875. const UpdatePost = crowi.model('UpdatePost');
  876. if (!path) {
  877. return res.json(ApiResponse.error({}));
  878. }
  879. UpdatePost.findSettingsByPath(path)
  880. .then(function(data) {
  881. data = data.map(function(e) {
  882. return e.channel;
  883. });
  884. debug('Found updatePost data', data);
  885. const result = {updatePost: data};
  886. return res.json(ApiResponse.success(result));
  887. }).catch(function(err) {
  888. debug('Error occured while get setting', err);
  889. return res.json(ApiResponse.error({}));
  890. });
  891. };
  892. /**
  893. * @api {post} /pages.remove Remove page
  894. * @apiName RemovePage
  895. * @apiGroup Page
  896. *
  897. * @apiParam {String} page_id Page Id.
  898. * @apiParam {String} revision_id
  899. */
  900. api.remove = function(req, res) {
  901. const pageId = req.body.page_id;
  902. const previousRevision = req.body.revision_id || null;
  903. // get completely flag
  904. const isCompletely = (req.body.completely != null);
  905. // get recursively flag
  906. const isRecursively = (req.body.recursively != null);
  907. Page.findPageByIdAndGrantedUser(pageId, req.user)
  908. .then(function(pageData) {
  909. debug('Delete page', pageData._id, pageData.path);
  910. if (isCompletely) {
  911. if (isRecursively) {
  912. return Page.completelyDeletePageRecursively(pageData, req.user);
  913. }
  914. else {
  915. return Page.completelyDeletePage(pageData, req.user);
  916. }
  917. }
  918. // else
  919. if (!pageData.isUpdatable(previousRevision)) {
  920. throw new Error('Someone could update this page, so couldn\'t delete.');
  921. }
  922. if (isRecursively) {
  923. return Page.deletePageRecursively(pageData, req.user);
  924. }
  925. else {
  926. return Page.deletePage(pageData, req.user);
  927. }
  928. })
  929. .then(function(data) {
  930. debug('Page deleted', data.path);
  931. const result = {};
  932. result.page = data;
  933. res.json(ApiResponse.success(result));
  934. return data;
  935. })
  936. .then((page) => {
  937. // global notification
  938. return globalNotificationService.notifyPageDelete(page);
  939. })
  940. .catch(function(err) {
  941. debug('Error occured while get setting', err, err.stack);
  942. return res.json(ApiResponse.error('Failed to delete page.'));
  943. });
  944. };
  945. /**
  946. * @api {post} /pages.revertRemove Revert removed page
  947. * @apiName RevertRemovePage
  948. * @apiGroup Page
  949. *
  950. * @apiParam {String} page_id Page Id.
  951. */
  952. api.revertRemove = function(req, res) {
  953. const pageId = req.body.page_id;
  954. // get recursively flag
  955. const isRecursively = (req.body.recursively !== undefined);
  956. Page.findPageByIdAndGrantedUser(pageId, req.user)
  957. .then(function(pageData) {
  958. if (isRecursively) {
  959. return Page.revertDeletedPageRecursively(pageData, req.user);
  960. }
  961. else {
  962. return Page.revertDeletedPage(pageData, req.user);
  963. }
  964. }).then(function(data) {
  965. debug('Complete to revert deleted page', data.path);
  966. const result = {};
  967. result.page = data;
  968. return res.json(ApiResponse.success(result));
  969. }).catch(function(err) {
  970. debug('Error occured while get setting', err, err.stack);
  971. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  972. });
  973. };
  974. /**
  975. * @api {post} /pages.rename Rename page
  976. * @apiName RenamePage
  977. * @apiGroup Page
  978. *
  979. * @apiParam {String} page_id Page Id.
  980. * @apiParam {String} path
  981. * @apiParam {String} revision_id
  982. * @apiParam {String} new_path
  983. * @apiParam {Bool} create_redirect
  984. */
  985. api.rename = function(req, res) {
  986. const pageId = req.body.page_id;
  987. const previousRevision = req.body.revision_id || null;
  988. const newPagePath = Page.normalizePath(req.body.new_path);
  989. const options = {
  990. createRedirectPage: req.body.create_redirect || 0,
  991. moveUnderTrees: req.body.move_trees || 0,
  992. };
  993. const isRecursiveMove = req.body.move_recursively || 0;
  994. if (!Page.isCreatableName(newPagePath)) {
  995. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})`));
  996. }
  997. Page.findPageByPath(newPagePath)
  998. .then(function(page) {
  999. if (page != null) {
  1000. // if page found, cannot cannot rename to that path
  1001. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`));
  1002. }
  1003. Page.findPageById(pageId)
  1004. .then(function(pageData) {
  1005. page = pageData;
  1006. if (!pageData.isUpdatable(previousRevision)) {
  1007. throw new Error('Someone could update this page, so couldn\'t delete.');
  1008. }
  1009. if (isRecursiveMove) {
  1010. return Page.renameRecursively(pageData, newPagePath, req.user, options);
  1011. }
  1012. else {
  1013. return Page.rename(pageData, newPagePath, req.user, options);
  1014. }
  1015. })
  1016. .then(function() {
  1017. const result = {};
  1018. result.page = page;
  1019. return res.json(ApiResponse.success(result));
  1020. })
  1021. .then(() => {
  1022. // global notification
  1023. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  1024. })
  1025. .catch(function(err) {
  1026. return res.json(ApiResponse.error('Failed to update page.'));
  1027. });
  1028. });
  1029. };
  1030. /**
  1031. * @api {post} /pages.duplicate Duplicate page
  1032. * @apiName DuplicatePage
  1033. * @apiGroup Page
  1034. *
  1035. * @apiParam {String} page_id Page Id.
  1036. * @apiParam {String} new_path
  1037. */
  1038. api.duplicate = function(req, res) {
  1039. const pageId = req.body.page_id;
  1040. const newPagePath = Page.normalizePath(req.body.new_path);
  1041. Page.findPageById(pageId)
  1042. .then(function(pageData) {
  1043. req.body.path = newPagePath;
  1044. req.body.body = pageData.revision.body;
  1045. req.body.grant = pageData.grant;
  1046. return api.create(req, res);
  1047. });
  1048. };
  1049. /**
  1050. * @api {post} /pages.unlink Remove the redirecting page
  1051. * @apiName UnlinkPage
  1052. * @apiGroup Page
  1053. *
  1054. * @apiParam {String} page_id Page Id.
  1055. * @apiParam {String} revision_id
  1056. */
  1057. api.unlink = function(req, res) {
  1058. const pageId = req.body.page_id;
  1059. Page.findPageByIdAndGrantedUser(pageId, req.user)
  1060. .then(function(pageData) {
  1061. debug('Unlink page', pageData._id, pageData.path);
  1062. return Page.removeRedirectOriginPageByPath(pageData.path)
  1063. .then(() => pageData);
  1064. }).then(function(data) {
  1065. debug('Redirect Page deleted', data.path);
  1066. const result = {};
  1067. result.page = data;
  1068. return res.json(ApiResponse.success(result));
  1069. }).catch(function(err) {
  1070. debug('Error occured while get setting', err, err.stack);
  1071. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1072. });
  1073. };
  1074. return actions;
  1075. };