page.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. path = path + (path == '/' ? '' : '/');
  51. // index page
  52. var pagerOptions = {
  53. offset: offset,
  54. limit : limit
  55. };
  56. var queryOptions = {
  57. offset: offset,
  58. limit : limit + 1
  59. };
  60. var renderVars = {
  61. page: null,
  62. path: path,
  63. pages: [],
  64. };
  65. Page.hasPortalPage(path, req.user)
  66. .then(function(portalPage) {
  67. renderVars.page = portalPage;
  68. return Page.findListByStartWith(path, req.user, queryOptions);
  69. }).then(function(pageList) {
  70. if (pageList.length > limit) {
  71. pageList.pop();
  72. }
  73. pagerOptions.length = pageList.length;
  74. renderVars.pager = generatePager(pagerOptions);
  75. renderVars.pages = pageList;
  76. res.render('page_list', renderVars);
  77. });
  78. };
  79. function renderPage(pageData, req, res) {
  80. // create page
  81. if (!pageData) {
  82. return res.render('page', {
  83. author: {},
  84. page: false,
  85. });
  86. }
  87. if (pageData.redirectTo) {
  88. return res.redirect(encodeURI(pageData.redirectTo + '?renamed=' + pageData.path));
  89. }
  90. var renderVars = {
  91. path: pageData.path,
  92. page: pageData,
  93. revision: pageData.revision || {},
  94. author: pageData.revision.author || false,
  95. };
  96. var userPage = isUserPage(pageData.path);
  97. var userData = null;
  98. Revision.findRevisionList(pageData.path, {})
  99. .then(function(tree) {
  100. renderVars.tree = tree;
  101. return Promise.resolve();
  102. }).then(function() {
  103. if (userPage) {
  104. return User.findUserByUsername(User.getUsernameByPath(pageData.path))
  105. .then(function(data) {
  106. if (data === null) {
  107. throw new Error('The user not found.');
  108. }
  109. userData = data;
  110. renderVars.pageUser = userData;
  111. return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
  112. }).then(function(bookmarkList) {
  113. debug(bookmarkList);
  114. renderVars.bookmarkList = bookmarkList;
  115. return Page.findListByCreator(userData, {limit: 10});
  116. }).then(function(createdList) {
  117. renderVars.createdList = createdList;
  118. return Promise.resolve();
  119. }).catch(function(err) {
  120. debug('Error on finding user related entities', err);
  121. // pass
  122. });
  123. } else {
  124. return Promise.resolve();
  125. }
  126. }).then(function() {
  127. var defaultPageTeamplate = 'page';
  128. if (userData) {
  129. defaultPageTeamplate = 'user_page';
  130. }
  131. res.render(req.query.presentation ? 'page_presentation' : defaultPageTeamplate, renderVars);
  132. }).catch(function(err) {
  133. debug('Error: renderPage()', err);
  134. if (err) {
  135. res.redirect('/');
  136. }
  137. });
  138. }
  139. actions.pageShow = function(req, res) {
  140. var path = path || getPathFromRequest(req);
  141. var options = {};
  142. // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ
  143. var isMarkdown = req.params[0].match(/.+\.md$/) || false;
  144. res.locals.path = path;
  145. // pageShow は /* にマッチしてる最後の砦なので、creatableName でない routing は
  146. // これ以前に定義されているはずなので、こうしてしまって問題ない。
  147. if (!Page.isCreatableName(path)) {
  148. debug('Page is not creatable name.', path);
  149. res.redirect('/');
  150. return ;
  151. }
  152. Page.findPage(path, req.user, req.query.revision)
  153. .then(function(page) {
  154. debug('Page found', page._id, page.path);
  155. if (isMarkdown) {
  156. res.set('Content-Type', 'text/plain');
  157. return res.send(page.revision.body);
  158. }
  159. return renderPage(page, req, res);
  160. }).catch(function(err) {
  161. if (req.query.revision) {
  162. return res.redirect(encodeURI(path));
  163. }
  164. if (isMarkdown) {
  165. return res.redirect('/');
  166. }
  167. Page.hasPortalPage(path + '/', req.user)
  168. .then(function(page) {
  169. if (page) {
  170. return res.redirect(path + '/');
  171. } else {
  172. debug('Catch pageShow', err);
  173. return renderPage(null, req, res);
  174. }
  175. });
  176. });
  177. };
  178. actions.pageEdit = function(req, res) {
  179. var pageForm = req.body.pageForm;
  180. var body = pageForm.body;
  181. var currentRevision = pageForm.currentRevision;
  182. var grant = pageForm.grant;
  183. var path = pageForm.path;
  184. var redirectPath = encodeURI(path);
  185. // set to render
  186. res.locals.pageForm = pageForm;
  187. if (!Page.isCreatableName(path)) {
  188. res.redirect(redirectPath);
  189. return ;
  190. }
  191. var ignoreNotFound = true;
  192. Page.findPage(path, req.user, null, ignoreNotFound)
  193. .then(function(pageData) {
  194. if (!req.form.isValid) {
  195. return renderPage(pageData, req, res);
  196. }
  197. if (pageData && !pageData.isUpdatable(currentRevision)) {
  198. req.form.errors.push('すでに他の人がこのページを編集していたため保存できませんでした。ページを再読み込み後、自分の編集箇所のみ再度編集してください。');
  199. return renderPage(pageData, req, res);
  200. }
  201. if (pageData) {
  202. // update existing page
  203. var newRevision = Revision.prepareRevision(pageData, body, req.user);
  204. return Page.pushRevision(pageData, newRevision, req.user);
  205. } else {
  206. // new page
  207. return Page.create(path, body, req.user, {grant: grant});
  208. }
  209. }).then(function(data) {
  210. crowi.getIo().sockets.emit('page edited', {page: data, user: req.user});
  211. if (grant != data.grant) {
  212. return Page.updateGrant(data, grant, req.user).then(function(data) {
  213. return res.redirect(redirectPath);
  214. });
  215. } else {
  216. return res.redirect(redirectPath);
  217. }
  218. }).catch(function(err) {
  219. debug('Create or edit page error', err);
  220. return res.redirect(redirectPath);
  221. });
  222. };
  223. // app.get( '/users/:username([^/]+)/bookmarks' , loginRequired(crowi, app) , page.userBookmarkList);
  224. actions.userBookmarkList = function(req, res) {
  225. var username = req.params.username;
  226. var limit = 50;
  227. var offset = parseInt(req.query.offset) || 0;
  228. var user;
  229. var renderVars = {};
  230. var pagerOptions = { offset: offset, limit : limit };
  231. var queryOptions = { offset: offset, limit : limit + 1, populatePage: true, requestUser: req.user};
  232. User.findUserByUsername(username)
  233. .then(function(user) {
  234. if (user === null) {
  235. throw new Error('The user not found.');
  236. }
  237. renderVars.user = user;
  238. return Bookmark.findByUser(user, queryOptions);
  239. }).then(function(bookmarks) {
  240. if (bookmarks.length > limit) {
  241. bookmarks.pop();
  242. }
  243. pagerOptions.length = bookmarks.length;
  244. renderVars.pager = generatePager(pagerOptions);
  245. renderVars.bookmarks = bookmarks;
  246. return res.render('user/bookmarks', renderVars);
  247. }).catch(function(err) {
  248. debug('Error on rendereing bookmark', err);
  249. res.redirect('/');
  250. });
  251. };
  252. // app.get( '/users/:username([^/]+)/recent-create' , loginRequired(crowi, app) , page.userRecentCreatedList);
  253. actions.userRecentCreatedList = function(req, res) {
  254. var username = req.params.username;
  255. var limit = 50;
  256. var offset = parseInt(req.query.offset) || 0;
  257. var user;
  258. var renderVars = {};
  259. var pagerOptions = { offset: offset, limit : limit };
  260. var queryOptions = { offset: offset, limit : limit + 1};
  261. User.findUserByUsername(username)
  262. .then(function(user) {
  263. if (user === null) {
  264. throw new Error('The user not found.');
  265. }
  266. renderVars.user = user;
  267. return Page.findListByCreator(user, queryOptions);
  268. }).then(function(pages) {
  269. if (pages.length > limit) {
  270. pages.pop();
  271. }
  272. pagerOptions.length = pages.length;
  273. renderVars.pager = generatePager(pagerOptions);
  274. renderVars.pages = pages;
  275. return res.render('user/recent-create', renderVars);
  276. }).catch(function(err) {
  277. debug('Error on rendereing recent-created', err);
  278. res.redirect('/');
  279. });
  280. };
  281. var api = actions.api = {};
  282. /**
  283. * redirector
  284. */
  285. api.redirector = function(req, res){
  286. var id = req.params.id;
  287. Page.findPageById(id)
  288. .then(function(pageData) {
  289. if (pageData.grant == Page.GRANT_RESTRICTED && !pageData.isGrantedFor(req.user)) {
  290. return Page.pushToGrantedUsers(pageData, req.user);
  291. }
  292. return Promise.resolve(pageData);
  293. }).then(function(page) {
  294. return res.redirect(encodeURI(page.path));
  295. }).catch(function(err) {
  296. return res.redirect('/');
  297. });
  298. };
  299. /**
  300. * @api {get} /pages.get Get page data
  301. * @apiName GetPage
  302. * @apiGroup Page
  303. *
  304. * @apiParam {String} page_id
  305. * @apiParam {String} path
  306. * @apiParam {String} revision_id
  307. */
  308. api.get = function(req, res){
  309. var pagePath = req.query.path || null;
  310. var pageId = req.query.page_id || null; // TODO: handling
  311. var revisionId = req.query.revision_id || null;
  312. Page.findPage(pagePath, req.user, revisionId)
  313. .then(function(pageData) {
  314. var result = {};
  315. result.page = pageData;
  316. return res.json(ApiResponse.success(result));
  317. }).catch(function(err) {
  318. return res.json(ApiResponse.error(err));
  319. });
  320. };
  321. /**
  322. * @api {post} /pages.seen Mark as seen user
  323. * @apiName SeenPage
  324. * @apiGroup Page
  325. *
  326. * @apiParam {String} page_id Page Id.
  327. */
  328. api.seen = function(req, res){
  329. var pageId = req.body.page_id;
  330. if (!pageId) {
  331. return res.json(ApiResponse.error('page_id required'));
  332. }
  333. Page.findPageByIdAndGrantedUser(pageId, req.user)
  334. .then(function(page) {
  335. return page.seen(req.user);
  336. }).then(function(user) {
  337. var result = {};
  338. result.seenUser = user;
  339. return res.json(ApiResponse.success(result));
  340. }).catch(function(err) {
  341. debug('Seen user update error', err);
  342. return res.json(ApiResponse.error(err));
  343. });
  344. };
  345. /**
  346. * @api {post} /likes.add Like page
  347. * @apiName LikePage
  348. * @apiGroup Page
  349. *
  350. * @apiParam {String} page_id Page Id.
  351. */
  352. api.like = function(req, res){
  353. var id = req.body.page_id;
  354. Page.findPageByIdAndGrantedUser(id, req.user)
  355. .then(function(pageData) {
  356. return pageData.like(req.user);
  357. }).then(function(data) {
  358. var result = {page: data};
  359. return res.json(ApiResponse.success(result));
  360. }).catch(function(err) {
  361. debug('Like failed', err);
  362. return res.json(ApiResponse.error({}));
  363. });
  364. };
  365. /**
  366. * @api {post} /likes.remove Unlike page
  367. * @apiName UnlikePage
  368. * @apiGroup Page
  369. *
  370. * @apiParam {String} page_id Page Id.
  371. */
  372. api.unlike = function(req, res){
  373. var id = req.body.page_id;
  374. Page.findPageByIdAndGrantedUser(id, req.user)
  375. .then(function(pageData) {
  376. return pageData.unlike(req.user);
  377. }).then(function(data) {
  378. var result = {page: data};
  379. return res.json(ApiResponse.success(result));
  380. }).catch(function(err) {
  381. debug('Unlike failed', err);
  382. return res.json(ApiResponse.error({}));
  383. });
  384. };
  385. /**
  386. * @api {post} /pages.rename Rename page
  387. * @apiName SeenPage
  388. * @apiGroup Page
  389. *
  390. * @apiParam {String} page_id Page Id.
  391. * @apiParam {String} path
  392. * @apiParam {String} revision_id
  393. * @apiParam {String} new_path
  394. * @apiParam {Bool} create_redirect
  395. */
  396. api.rename = function(req, res){
  397. var pageId = req.body.page_id;
  398. var previousRevision = req.body.revision_id || null;
  399. var newPagePath = Page.normalizePath(req.body.new_path);
  400. var options = {
  401. createRedirectPage: req.body.create_redirect || 0,
  402. moveUnderTrees: req.body.move_trees || 0,
  403. };
  404. var page = {};
  405. if (!Page.isCreatableName(newPagePath)) {
  406. return res.json(ApiResponse.error(sprintf('このページ名は作成できません (%s)', newPagePath)));
  407. }
  408. Page.findPageByPath(newPagePath)
  409. .then(function(page) {
  410. // if page found, cannot cannot rename to that path
  411. return res.json(ApiResponse.error(sprintf('このページ名は作成できません (%s)。ページが存在します。', newPagePath)));
  412. }).catch(function(err) {
  413. Page.findPageById(pageId)
  414. .then(function(pageData) {
  415. page = pageData;
  416. if (!pageData.isUpdatable(previousRevision)) {
  417. return res.json(ApiResponse.error('誰かが更新している可能性があります。ページを更新できません。'));
  418. }
  419. return Page.rename(pageData, newPagePath, req.user, options);
  420. }).then(function() {
  421. var result = {};
  422. result.page = page;
  423. return res.json(ApiResponse.success(result));
  424. }).catch(function(err) {
  425. return res.json(ApiResponse.error('エラーが発生しました。ページを更新できません。'));
  426. });
  427. });
  428. };
  429. return actions;
  430. };