page.js 34 KB

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