page.js 35 KB

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