page.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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:update', {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. const isSyncRevisionToHackmd = !!req.body.slackChannels; // cast to boolean
  726. if (pageId === null || pageBody === null) {
  727. return res.json(ApiResponse.error('page_id and body are required.'));
  728. }
  729. let previousRevision = undefined;
  730. let updatedPage = await Page.findPageByIdAndGrantedUser(pageId, req.user)
  731. .then(function(pageData) {
  732. if (pageData && revisionId !== null && !pageData.isUpdatable(revisionId)) {
  733. throw new Error('Revision error.');
  734. }
  735. const options = {};
  736. if (grant != null) {
  737. options.grant = grant;
  738. }
  739. if (grantUserGroupId != null) {
  740. options.grantUserGroupId = grantUserGroupId;
  741. }
  742. if (isSyncRevisionToHackmd) {
  743. options.isSyncRevisionToHackmd = true;
  744. }
  745. // store previous revision
  746. previousRevision = pageData.revision;
  747. return Page.updatePage(pageData, pageBody, req.user, options);
  748. })
  749. .catch(function(err) {
  750. debug('error on _api/pages.update', err);
  751. res.json(ApiResponse.error(err));
  752. });
  753. const result = { page: updatedPage.toObject() };
  754. result.page.lastUpdateUser = User.filterToPublicFields(updatedPage.lastUpdateUser);
  755. res.json(ApiResponse.success(result));
  756. // global notification
  757. try {
  758. await globalNotificationService.notifyPageEdit(updatedPage);
  759. }
  760. catch (err) {
  761. logger.error(err);
  762. }
  763. // user notification
  764. if (isSlackEnabled && slackChannels != null) {
  765. await notifyToSlackByUser(updatedPage, req.user, slackChannels, 'update', previousRevision);
  766. }
  767. };
  768. /**
  769. * @api {get} /pages.get Get page data
  770. * @apiName GetPage
  771. * @apiGroup Page
  772. *
  773. * @apiParam {String} page_id
  774. * @apiParam {String} path
  775. * @apiParam {String} revision_id
  776. */
  777. api.get = function(req, res) {
  778. const pagePath = req.query.path || null;
  779. const pageId = req.query.page_id || null; // TODO: handling
  780. const revisionId = req.query.revision_id || null;
  781. if (!pageId && !pagePath) {
  782. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  783. }
  784. let pageFinder;
  785. if (pageId) { // prioritized
  786. pageFinder = Page.findPageByIdAndGrantedUser(pageId, req.user);
  787. }
  788. else if (pagePath) {
  789. pageFinder = Page.findPage(pagePath, req.user, revisionId);
  790. }
  791. pageFinder.then(function(pageData) {
  792. const result = {};
  793. result.page = pageData;
  794. return res.json(ApiResponse.success(result));
  795. }).catch(function(err) {
  796. return res.json(ApiResponse.error(err));
  797. });
  798. };
  799. /**
  800. * @api {post} /pages.seen Mark as seen user
  801. * @apiName SeenPage
  802. * @apiGroup Page
  803. *
  804. * @apiParam {String} page_id Page Id.
  805. */
  806. api.seen = function(req, res) {
  807. const pageId = req.body.page_id;
  808. if (!pageId) {
  809. return res.json(ApiResponse.error('page_id required'));
  810. }
  811. Page.findPageByIdAndGrantedUser(pageId, req.user)
  812. .then(function(page) {
  813. return page.seen(req.user);
  814. }).then(function(user) {
  815. const result = {};
  816. result.seenUser = user;
  817. return res.json(ApiResponse.success(result));
  818. }).catch(function(err) {
  819. debug('Seen user update error', err);
  820. return res.json(ApiResponse.error(err));
  821. });
  822. };
  823. /**
  824. * @api {post} /likes.add Like page
  825. * @apiName LikePage
  826. * @apiGroup Page
  827. *
  828. * @apiParam {String} page_id Page Id.
  829. */
  830. api.like = function(req, res) {
  831. const id = req.body.page_id;
  832. Page.findPageByIdAndGrantedUser(id, req.user)
  833. .then(function(pageData) {
  834. return pageData.like(req.user);
  835. })
  836. .then(function(page) {
  837. const result = {page: page};
  838. res.json(ApiResponse.success(result));
  839. return page;
  840. })
  841. .then((page) => {
  842. // global notification
  843. return globalNotificationService.notifyPageLike(page, req.user);
  844. })
  845. .catch(function(err) {
  846. debug('Like failed', err);
  847. return res.json(ApiResponse.error({}));
  848. });
  849. };
  850. /**
  851. * @api {post} /likes.remove Unlike page
  852. * @apiName UnlikePage
  853. * @apiGroup Page
  854. *
  855. * @apiParam {String} page_id Page Id.
  856. */
  857. api.unlike = function(req, res) {
  858. const id = req.body.page_id;
  859. Page.findPageByIdAndGrantedUser(id, req.user)
  860. .then(function(pageData) {
  861. return pageData.unlike(req.user);
  862. }).then(function(data) {
  863. const result = {page: data};
  864. return res.json(ApiResponse.success(result));
  865. }).catch(function(err) {
  866. debug('Unlike failed', err);
  867. return res.json(ApiResponse.error({}));
  868. });
  869. };
  870. /**
  871. * @api {get} /pages.updatePost
  872. * @apiName Get UpdatePost setting list
  873. * @apiGroup Page
  874. *
  875. * @apiParam {String} path
  876. */
  877. api.getUpdatePost = function(req, res) {
  878. const path = req.query.path;
  879. const UpdatePost = crowi.model('UpdatePost');
  880. if (!path) {
  881. return res.json(ApiResponse.error({}));
  882. }
  883. UpdatePost.findSettingsByPath(path)
  884. .then(function(data) {
  885. data = data.map(function(e) {
  886. return e.channel;
  887. });
  888. debug('Found updatePost data', data);
  889. const result = {updatePost: data};
  890. return res.json(ApiResponse.success(result));
  891. }).catch(function(err) {
  892. debug('Error occured while get setting', err);
  893. return res.json(ApiResponse.error({}));
  894. });
  895. };
  896. /**
  897. * @api {post} /pages.remove Remove page
  898. * @apiName RemovePage
  899. * @apiGroup Page
  900. *
  901. * @apiParam {String} page_id Page Id.
  902. * @apiParam {String} revision_id
  903. */
  904. api.remove = function(req, res) {
  905. const pageId = req.body.page_id;
  906. const previousRevision = req.body.revision_id || null;
  907. // get completely flag
  908. const isCompletely = (req.body.completely != null);
  909. // get recursively flag
  910. const isRecursively = (req.body.recursively != null);
  911. Page.findPageByIdAndGrantedUser(pageId, req.user)
  912. .then(function(pageData) {
  913. debug('Delete page', pageData._id, pageData.path);
  914. if (isCompletely) {
  915. if (isRecursively) {
  916. return Page.completelyDeletePageRecursively(pageData, req.user);
  917. }
  918. else {
  919. return Page.completelyDeletePage(pageData, req.user);
  920. }
  921. }
  922. // else
  923. if (!pageData.isUpdatable(previousRevision)) {
  924. throw new Error('Someone could update this page, so couldn\'t delete.');
  925. }
  926. if (isRecursively) {
  927. return Page.deletePageRecursively(pageData, req.user);
  928. }
  929. else {
  930. return Page.deletePage(pageData, req.user);
  931. }
  932. })
  933. .then(function(data) {
  934. debug('Page deleted', data.path);
  935. const result = {};
  936. result.page = data;
  937. res.json(ApiResponse.success(result));
  938. return data;
  939. })
  940. .then((page) => {
  941. // global notification
  942. return globalNotificationService.notifyPageDelete(page);
  943. })
  944. .catch(function(err) {
  945. debug('Error occured while get setting', err, err.stack);
  946. return res.json(ApiResponse.error('Failed to delete page.'));
  947. });
  948. };
  949. /**
  950. * @api {post} /pages.revertRemove Revert removed page
  951. * @apiName RevertRemovePage
  952. * @apiGroup Page
  953. *
  954. * @apiParam {String} page_id Page Id.
  955. */
  956. api.revertRemove = function(req, res) {
  957. const pageId = req.body.page_id;
  958. // get recursively flag
  959. const isRecursively = (req.body.recursively !== undefined);
  960. Page.findPageByIdAndGrantedUser(pageId, req.user)
  961. .then(function(pageData) {
  962. if (isRecursively) {
  963. return Page.revertDeletedPageRecursively(pageData, req.user);
  964. }
  965. else {
  966. return Page.revertDeletedPage(pageData, req.user);
  967. }
  968. }).then(function(data) {
  969. debug('Complete to revert deleted page', data.path);
  970. const result = {};
  971. result.page = data;
  972. return res.json(ApiResponse.success(result));
  973. }).catch(function(err) {
  974. debug('Error occured while get setting', err, err.stack);
  975. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  976. });
  977. };
  978. /**
  979. * @api {post} /pages.rename Rename page
  980. * @apiName RenamePage
  981. * @apiGroup Page
  982. *
  983. * @apiParam {String} page_id Page Id.
  984. * @apiParam {String} path
  985. * @apiParam {String} revision_id
  986. * @apiParam {String} new_path
  987. * @apiParam {Bool} create_redirect
  988. */
  989. api.rename = function(req, res) {
  990. const pageId = req.body.page_id;
  991. const previousRevision = req.body.revision_id || null;
  992. const newPagePath = Page.normalizePath(req.body.new_path);
  993. const options = {
  994. createRedirectPage: req.body.create_redirect || 0,
  995. moveUnderTrees: req.body.move_trees || 0,
  996. };
  997. const isRecursiveMove = req.body.move_recursively || 0;
  998. if (!Page.isCreatableName(newPagePath)) {
  999. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})`));
  1000. }
  1001. Page.findPageByPath(newPagePath)
  1002. .then(function(page) {
  1003. if (page != null) {
  1004. // if page found, cannot cannot rename to that path
  1005. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`));
  1006. }
  1007. Page.findPageById(pageId)
  1008. .then(function(pageData) {
  1009. page = pageData;
  1010. if (!pageData.isUpdatable(previousRevision)) {
  1011. throw new Error('Someone could update this page, so couldn\'t delete.');
  1012. }
  1013. if (isRecursiveMove) {
  1014. return Page.renameRecursively(pageData, newPagePath, req.user, options);
  1015. }
  1016. else {
  1017. return Page.rename(pageData, newPagePath, req.user, options);
  1018. }
  1019. })
  1020. .then(function() {
  1021. const result = {};
  1022. result.page = page;
  1023. return res.json(ApiResponse.success(result));
  1024. })
  1025. .then(() => {
  1026. // global notification
  1027. globalNotificationService.notifyPageMove(page, req.body.path, req.user);
  1028. })
  1029. .catch(function(err) {
  1030. return res.json(ApiResponse.error('Failed to update page.'));
  1031. });
  1032. });
  1033. };
  1034. /**
  1035. * @api {post} /pages.duplicate Duplicate page
  1036. * @apiName DuplicatePage
  1037. * @apiGroup Page
  1038. *
  1039. * @apiParam {String} page_id Page Id.
  1040. * @apiParam {String} new_path
  1041. */
  1042. api.duplicate = function(req, res) {
  1043. const pageId = req.body.page_id;
  1044. const newPagePath = Page.normalizePath(req.body.new_path);
  1045. Page.findPageById(pageId)
  1046. .then(function(pageData) {
  1047. req.body.path = newPagePath;
  1048. req.body.body = pageData.revision.body;
  1049. req.body.grant = pageData.grant;
  1050. return api.create(req, res);
  1051. });
  1052. };
  1053. /**
  1054. * @api {post} /pages.unlink Remove the redirecting page
  1055. * @apiName UnlinkPage
  1056. * @apiGroup Page
  1057. *
  1058. * @apiParam {String} page_id Page Id.
  1059. * @apiParam {String} revision_id
  1060. */
  1061. api.unlink = function(req, res) {
  1062. const pageId = req.body.page_id;
  1063. Page.findPageByIdAndGrantedUser(pageId, req.user)
  1064. .then(function(pageData) {
  1065. debug('Unlink page', pageData._id, pageData.path);
  1066. return Page.removeRedirectOriginPageByPath(pageData.path)
  1067. .then(() => pageData);
  1068. }).then(function(data) {
  1069. debug('Redirect Page deleted', data.path);
  1070. const result = {};
  1071. result.page = data;
  1072. return res.json(ApiResponse.success(result));
  1073. }).catch(function(err) {
  1074. debug('Error occured while get setting', err, err.stack);
  1075. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1076. });
  1077. };
  1078. return actions;
  1079. };