page.js 35 KB

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