page.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. , Revision = crowi.model('Revision')
  7. , Bookmark = crowi.model('Bookmark')
  8. , ApiResponse = require('../util/apiResponse')
  9. , sprintf = require('sprintf')
  10. , actions = {};
  11. function getPathFromRequest(req) {
  12. var path = '/' + (req.params[0] || '');
  13. return path.replace(/\.md$/, '');
  14. }
  15. function isUserPage(path) {
  16. if (path.match(/^\/user\/[^\/]+\/?$/)) {
  17. return true;
  18. }
  19. return false;
  20. }
  21. // TODO: total とかでちゃんと計算する
  22. function generatePager(options) {
  23. var next = null,
  24. prev = null,
  25. offset = parseInt(options.offset, 10),
  26. limit = parseInt(options.limit, 10),
  27. length = options.length || 0;
  28. if (offset > 0) {
  29. prev = offset - limit;
  30. if (prev < 0) {
  31. prev = 0;
  32. }
  33. }
  34. if (length < limit) {
  35. next = null;
  36. } else {
  37. next = offset + limit;
  38. }
  39. return {
  40. prev: prev,
  41. next: next,
  42. offset: offset,
  43. };
  44. }
  45. // routing
  46. actions.pageListShow = function(req, res) {
  47. var path = getPathFromRequest(req);
  48. var limit = 50;
  49. var offset = parseInt(req.query.offset) || 0;
  50. var SEENER_THRESHOLD = 10;
  51. path = path + (path == '/' ? '' : '/');
  52. // index page
  53. var pagerOptions = {
  54. offset: offset,
  55. limit : limit
  56. };
  57. var queryOptions = {
  58. offset: offset,
  59. limit : limit + 1
  60. };
  61. var renderVars = {
  62. page: null,
  63. path: path,
  64. pages: [],
  65. };
  66. Page.hasPortalPage(path, req.user)
  67. .then(function(portalPage) {
  68. renderVars.page = portalPage;
  69. return Page.findListByStartWith(path, req.user, queryOptions);
  70. }).then(function(pageList) {
  71. if (pageList.length > limit) {
  72. pageList.pop();
  73. }
  74. pagerOptions.length = pageList.length;
  75. renderVars.config = {
  76. seener_threshold: SEENER_THRESHOLD
  77. };
  78. renderVars.pager = generatePager(pagerOptions);
  79. renderVars.pages = pageList;
  80. res.render('page_list', renderVars);
  81. }).catch(function(err) {
  82. debug('Error on rendering pageListShow', err);
  83. });
  84. };
  85. actions.search = function(req, res) {
  86. // spec: ?q=query&sort=sort_order&author=author_filter
  87. var query = req.query.q;
  88. var search = require('../util/search')(crowi);
  89. search.searchPageByKeyword(query)
  90. .then(function(pages) {
  91. debug('pages', pages);
  92. if (pages.hits.total <= 0) {
  93. return Promise.resolve([]);
  94. }
  95. var ids = pages.hits.hits.map(function(page) {
  96. return page._id;
  97. });
  98. return Page.findListByPageIds(ids);
  99. }).then(function(pages) {
  100. res.render('page_list', {
  101. path: '/',
  102. pages: pages,
  103. pager: generatePager({offset: 0, limit: 50})
  104. });
  105. }).catch(function(err) {
  106. debug('search error', err);
  107. });
  108. };
  109. actions.search = function(req, res) {
  110. // spec: ?q=query&sort=sort_order&author=author_filter
  111. var query = req.query.q;
  112. var search = require('../util/search')(crowi);
  113. search.searchPageByKeyword(query)
  114. .then(function(pages) {
  115. debug('pages', pages);
  116. if (pages.hits.total <= 0) {
  117. return Promise.resolve([]);
  118. }
  119. var ids = pages.hits.hits.map(function(page) {
  120. return page._id;
  121. });
  122. return Page.findListByPageIds(ids);
  123. }).then(function(pages) {
  124. res.render('page_list', {
  125. path: '/',
  126. pages: pages,
  127. pager: generatePager({offset: 0, limit: 50})
  128. });
  129. }).catch(function(err) {
  130. debug('search error', err);
  131. });
  132. };
  133. function renderPage(pageData, req, res) {
  134. // create page
  135. if (!pageData) {
  136. return res.render('page', {
  137. author: {},
  138. page: false,
  139. });
  140. }
  141. if (pageData.redirectTo) {
  142. return res.redirect(encodeURI(pageData.redirectTo + '?renamed=' + pageData.path));
  143. }
  144. var renderVars = {
  145. path: pageData.path,
  146. page: pageData,
  147. revision: pageData.revision || {},
  148. author: pageData.revision.author || false,
  149. };
  150. var userPage = isUserPage(pageData.path);
  151. var userData = null;
  152. Revision.findRevisionList(pageData.path, {})
  153. .then(function(tree) {
  154. renderVars.tree = tree;
  155. return Promise.resolve();
  156. }).then(function() {
  157. if (userPage) {
  158. return User.findUserByUsername(User.getUsernameByPath(pageData.path))
  159. .then(function(data) {
  160. if (data === null) {
  161. throw new Error('The user not found.');
  162. }
  163. userData = data;
  164. renderVars.pageUser = userData;
  165. return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
  166. }).then(function(bookmarkList) {
  167. renderVars.bookmarkList = bookmarkList;
  168. return Page.findListByCreator(userData, {limit: 10});
  169. }).then(function(createdList) {
  170. renderVars.createdList = createdList;
  171. return Promise.resolve();
  172. }).catch(function(err) {
  173. debug('Error on finding user related entities', err);
  174. // pass
  175. });
  176. } else {
  177. return Promise.resolve();
  178. }
  179. }).then(function() {
  180. var defaultPageTeamplate = 'page';
  181. if (userData) {
  182. defaultPageTeamplate = 'user_page';
  183. }
  184. res.render(req.query.presentation ? 'page_presentation' : defaultPageTeamplate, renderVars);
  185. }).catch(function(err) {
  186. debug('Error: renderPage()', err);
  187. if (err) {
  188. res.redirect('/');
  189. }
  190. });
  191. }
  192. actions.pageShow = function(req, res) {
  193. var path = path || getPathFromRequest(req);
  194. var options = {};
  195. // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ
  196. var isMarkdown = req.params[0].match(/.+\.md$/) || false;
  197. res.locals.path = path;
  198. // pageShow は /* にマッチしてる最後の砦なので、creatableName でない routing は
  199. // これ以前に定義されているはずなので、こうしてしまって問題ない。
  200. if (!Page.isCreatableName(path)) {
  201. debug('Page is not creatable name.', path);
  202. res.redirect('/');
  203. return ;
  204. }
  205. Page.findPage(path, req.user, req.query.revision)
  206. .then(function(page) {
  207. debug('Page found', page._id, page.path);
  208. if (isMarkdown) {
  209. res.set('Content-Type', 'text/plain');
  210. return res.send(page.revision.body);
  211. }
  212. return renderPage(page, req, res);
  213. }).catch(function(err) {
  214. if (req.query.revision) {
  215. return res.redirect(encodeURI(path));
  216. }
  217. if (isMarkdown) {
  218. return res.redirect('/');
  219. }
  220. Page.hasPortalPage(path + '/', req.user)
  221. .then(function(page) {
  222. if (page) {
  223. return res.redirect(encodeURI(path) + '/');
  224. } else {
  225. debug('Catch pageShow', err);
  226. return renderPage(null, req, res);
  227. }
  228. }).catch(function(err) {
  229. debug('Error on rendering pageShow (redirect to portal)', err);
  230. });
  231. });
  232. };
  233. actions.pageEdit = function(req, res) {
  234. var pageForm = req.body.pageForm;
  235. var body = pageForm.body;
  236. var currentRevision = pageForm.currentRevision;
  237. var grant = pageForm.grant;
  238. var path = pageForm.path;
  239. // TODO: make it pluggable
  240. var notify = pageForm.notify || {};
  241. debug('notify: ', notify);
  242. var redirectPath = encodeURI(path);
  243. var pageData = {};
  244. var updateOrCreate;
  245. var previousRevision = false;
  246. // set to render
  247. res.locals.pageForm = pageForm;
  248. if (!Page.isCreatableName(path)) {
  249. res.redirect(redirectPath);
  250. return ;
  251. }
  252. var ignoreNotFound = true;
  253. Page.findPage(path, req.user, null, ignoreNotFound)
  254. .then(function(data) {
  255. pageData = data;
  256. if (!req.form.isValid) {
  257. debug('Form data not valid');
  258. throw new Error('Form data not valid.');
  259. }
  260. if (data && !data.isUpdatable(currentRevision)) {
  261. debug('Conflict occured');
  262. req.form.errors.push('すでに他の人がこのページを編集していたため保存できませんでした。ページを再読み込み後、自分の編集箇所のみ再度編集してください。');
  263. throw new Error('Conflict.');
  264. }
  265. if (data) {
  266. previousRevision = data.revision;
  267. return Page.updatePage(data, body, req.user, {grant: grant});
  268. } else {
  269. // new page
  270. updateOrCreate = 'create';
  271. return Page.create(path, body, req.user, {grant: grant});
  272. }
  273. }).then(function(data) {
  274. // data is a saved page data.
  275. pageData = data;
  276. if (!data) {
  277. throw new Error('Data not found');
  278. }
  279. // TODO: move to events
  280. crowi.getIo().sockets.emit('page edited', {page: data, user: req.user});
  281. if (notify.slack) {
  282. if (notify.slack.on && notify.slack.channel) {
  283. data.updateSlackChannel(notify.slack.channel).then(function(){}).catch(function(){});
  284. if (crowi.slack) {
  285. notify.slack.channel.split(',').map(function(chan) {
  286. var message = crowi.slack.prepareSlackMessage(pageData, req.user, chan, updateOrCreate, previousRevision);
  287. crowi.slack.post(message).then(function(){}).catch(function(){});
  288. });
  289. }
  290. }
  291. }
  292. return res.redirect(redirectPath);
  293. }).catch(function(err) {
  294. debug('Page create or edit error.', err);
  295. if (pageData && !req.form.isValid) {
  296. return renderPage(pageData, req, res);
  297. }
  298. return res.redirect(redirectPath);
  299. });
  300. };
  301. // app.get( '/users/:username([^/]+)/bookmarks' , loginRequired(crowi, app) , page.userBookmarkList);
  302. actions.userBookmarkList = function(req, res) {
  303. var username = req.params.username;
  304. var limit = 50;
  305. var offset = parseInt(req.query.offset) || 0;
  306. var user;
  307. var renderVars = {};
  308. var pagerOptions = { offset: offset, limit : limit };
  309. var queryOptions = { offset: offset, limit : limit + 1, populatePage: true, requestUser: req.user};
  310. User.findUserByUsername(username)
  311. .then(function(user) {
  312. if (user === null) {
  313. throw new Error('The user not found.');
  314. }
  315. renderVars.user = user;
  316. return Bookmark.findByUser(user, queryOptions);
  317. }).then(function(bookmarks) {
  318. if (bookmarks.length > limit) {
  319. bookmarks.pop();
  320. }
  321. pagerOptions.length = bookmarks.length;
  322. renderVars.pager = generatePager(pagerOptions);
  323. renderVars.bookmarks = bookmarks;
  324. return res.render('user/bookmarks', renderVars);
  325. }).catch(function(err) {
  326. debug('Error on rendereing bookmark', err);
  327. res.redirect('/');
  328. });
  329. };
  330. // app.get( '/users/:username([^/]+)/recent-create' , loginRequired(crowi, app) , page.userRecentCreatedList);
  331. actions.userRecentCreatedList = function(req, res) {
  332. var username = req.params.username;
  333. var limit = 50;
  334. var offset = parseInt(req.query.offset) || 0;
  335. var user;
  336. var renderVars = {};
  337. var pagerOptions = { offset: offset, limit : limit };
  338. var queryOptions = { offset: offset, limit : limit + 1};
  339. User.findUserByUsername(username)
  340. .then(function(user) {
  341. if (user === null) {
  342. throw new Error('The user not found.');
  343. }
  344. renderVars.user = user;
  345. return Page.findListByCreator(user, queryOptions);
  346. }).then(function(pages) {
  347. if (pages.length > limit) {
  348. pages.pop();
  349. }
  350. pagerOptions.length = pages.length;
  351. renderVars.pager = generatePager(pagerOptions);
  352. renderVars.pages = pages;
  353. return res.render('user/recent-create', renderVars);
  354. }).catch(function(err) {
  355. debug('Error on rendereing recent-created', err);
  356. res.redirect('/');
  357. });
  358. };
  359. var api = actions.api = {};
  360. /**
  361. * redirector
  362. */
  363. api.redirector = function(req, res){
  364. var id = req.params.id;
  365. Page.findPageById(id)
  366. .then(function(pageData) {
  367. if (pageData.grant == Page.GRANT_RESTRICTED && !pageData.isGrantedFor(req.user)) {
  368. return Page.pushToGrantedUsers(pageData, req.user);
  369. }
  370. return Promise.resolve(pageData);
  371. }).then(function(page) {
  372. return res.redirect(encodeURI(page.path));
  373. }).catch(function(err) {
  374. return res.redirect('/');
  375. });
  376. };
  377. /**
  378. * @api {get} /pages.get Get page data
  379. * @apiName GetPage
  380. * @apiGroup Page
  381. *
  382. * @apiParam {String} page_id
  383. * @apiParam {String} path
  384. * @apiParam {String} revision_id
  385. */
  386. api.get = function(req, res){
  387. var pagePath = req.query.path || null;
  388. var pageId = req.query.page_id || null; // TODO: handling
  389. var revisionId = req.query.revision_id || null;
  390. Page.findPage(pagePath, req.user, revisionId)
  391. .then(function(pageData) {
  392. var result = {};
  393. result.page = pageData;
  394. return res.json(ApiResponse.success(result));
  395. }).catch(function(err) {
  396. return res.json(ApiResponse.error(err));
  397. });
  398. };
  399. /**
  400. * @api {post} /pages.seen Mark as seen user
  401. * @apiName SeenPage
  402. * @apiGroup Page
  403. *
  404. * @apiParam {String} page_id Page Id.
  405. */
  406. api.seen = function(req, res){
  407. var pageId = req.body.page_id;
  408. if (!pageId) {
  409. return res.json(ApiResponse.error('page_id required'));
  410. }
  411. Page.findPageByIdAndGrantedUser(pageId, req.user)
  412. .then(function(page) {
  413. return page.seen(req.user);
  414. }).then(function(user) {
  415. var result = {};
  416. result.seenUser = user;
  417. return res.json(ApiResponse.success(result));
  418. }).catch(function(err) {
  419. debug('Seen user update error', err);
  420. return res.json(ApiResponse.error(err));
  421. });
  422. };
  423. /**
  424. * @api {post} /likes.add Like page
  425. * @apiName LikePage
  426. * @apiGroup Page
  427. *
  428. * @apiParam {String} page_id Page Id.
  429. */
  430. api.like = function(req, res){
  431. var id = req.body.page_id;
  432. Page.findPageByIdAndGrantedUser(id, req.user)
  433. .then(function(pageData) {
  434. return pageData.like(req.user);
  435. }).then(function(data) {
  436. var result = {page: data};
  437. return res.json(ApiResponse.success(result));
  438. }).catch(function(err) {
  439. debug('Like failed', err);
  440. return res.json(ApiResponse.error({}));
  441. });
  442. };
  443. /**
  444. * @api {post} /likes.remove Unlike page
  445. * @apiName UnlikePage
  446. * @apiGroup Page
  447. *
  448. * @apiParam {String} page_id Page Id.
  449. */
  450. api.unlike = function(req, res){
  451. var id = req.body.page_id;
  452. Page.findPageByIdAndGrantedUser(id, req.user)
  453. .then(function(pageData) {
  454. return pageData.unlike(req.user);
  455. }).then(function(data) {
  456. var result = {page: data};
  457. return res.json(ApiResponse.success(result));
  458. }).catch(function(err) {
  459. debug('Unlike failed', err);
  460. return res.json(ApiResponse.error({}));
  461. });
  462. };
  463. /**
  464. * @api {get} /pages.updatePost
  465. * @apiName Get UpdatePost setting list
  466. * @apiGroup Page
  467. *
  468. * @apiParam {String} path
  469. */
  470. api.getUpdatePost = function(req, res) {
  471. var path = req.query.path;
  472. var UpdatePost = crowi.model('UpdatePost');
  473. if (!path) {
  474. return res.json(ApiResponse.error({}));
  475. }
  476. UpdatePost.findSettingsByPath(path)
  477. .then(function(data) {
  478. data = data.map(function(e) {
  479. return e.channel;
  480. });
  481. debug('Found updatePost data', data);
  482. var result = {updatePost: data};
  483. return res.json(ApiResponse.success(result));
  484. }).catch(function(err) {
  485. debug('Error occured while get setting', err);
  486. return res.json(ApiResponse.error({}));
  487. });
  488. };
  489. /**
  490. * @api {post} /pages.remove Remove page
  491. * @apiName RemovePage
  492. * @apiGroup Page
  493. *
  494. * @apiParam {String} page_id Page Id.
  495. * @apiParam {String} revision_id
  496. */
  497. api.remove = function(req, res){
  498. var pageId = req.body.page_id;
  499. var previousRevision = req.body.revision_id || null;
  500. Page.findPageByIdAndGrantedUser(id, req.user)
  501. .then(function(pageData) {
  502. return Page.removePage(pageData);
  503. }).then(function(data) {
  504. });
  505. };
  506. /**
  507. * @api {post} /pages.rename Rename page
  508. * @apiName RenamePage
  509. * @apiGroup Page
  510. *
  511. * @apiParam {String} page_id Page Id.
  512. * @apiParam {String} path
  513. * @apiParam {String} revision_id
  514. * @apiParam {String} new_path
  515. * @apiParam {Bool} create_redirect
  516. */
  517. api.rename = function(req, res){
  518. var pageId = req.body.page_id;
  519. var previousRevision = req.body.revision_id || null;
  520. var newPagePath = Page.normalizePath(req.body.new_path);
  521. var options = {
  522. createRedirectPage: req.body.create_redirect || 0,
  523. moveUnderTrees: req.body.move_trees || 0,
  524. };
  525. var page = {};
  526. if (!Page.isCreatableName(newPagePath)) {
  527. return res.json(ApiResponse.error(sprintf('このページ名は作成できません (%s)', newPagePath)));
  528. }
  529. Page.findPageByPath(newPagePath)
  530. .then(function(page) {
  531. // if page found, cannot cannot rename to that path
  532. return res.json(ApiResponse.error(sprintf('このページ名は作成できません (%s)。ページが存在します。', newPagePath)));
  533. }).catch(function(err) {
  534. Page.findPageById(pageId)
  535. .then(function(pageData) {
  536. page = pageData;
  537. if (!pageData.isUpdatable(previousRevision)) {
  538. return res.json(ApiResponse.error('誰かが更新している可能性があります。ページを更新できません。'));
  539. }
  540. return Page.rename(pageData, newPagePath, req.user, options);
  541. }).then(function() {
  542. var result = {};
  543. result.page = page;
  544. return res.json(ApiResponse.success(result));
  545. }).catch(function(err) {
  546. return res.json(ApiResponse.error('エラーが発生しました。ページを更新できません。'));
  547. });
  548. });
  549. };
  550. return actions;
  551. };