page.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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. 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. };