page.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. renderVars.bookmarkList = bookmarkList;
  114. return Page.findListByCreator(userData, {limit: 10});
  115. }).then(function(createdList) {
  116. renderVars.createdList = createdList;
  117. return Promise.resolve();
  118. }).catch(function(err) {
  119. debug('Error on finding user related entities', err);
  120. // pass
  121. });
  122. } else {
  123. return Promise.resolve();
  124. }
  125. }).then(function() {
  126. var defaultPageTeamplate = 'page';
  127. if (userData) {
  128. defaultPageTeamplate = 'user_page';
  129. }
  130. res.render(req.query.presentation ? 'page_presentation' : defaultPageTeamplate, renderVars);
  131. }).catch(function(err) {
  132. debug('Error: renderPage()', err);
  133. if (err) {
  134. res.redirect('/');
  135. }
  136. });
  137. }
  138. actions.pageShow = function(req, res) {
  139. var path = path || getPathFromRequest(req);
  140. var options = {};
  141. // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ
  142. var isMarkdown = req.params[0].match(/.+\.md$/) || false;
  143. res.locals.path = path;
  144. // pageShow は /* にマッチしてる最後の砦なので、creatableName でない routing は
  145. // これ以前に定義されているはずなので、こうしてしまって問題ない。
  146. if (!Page.isCreatableName(path)) {
  147. debug('Page is not creatable name.', path);
  148. res.redirect('/');
  149. return ;
  150. }
  151. Page.findPage(path, req.user, req.query.revision)
  152. .then(function(page) {
  153. debug('Page found', page._id, page.path);
  154. if (isMarkdown) {
  155. res.set('Content-Type', 'text/plain');
  156. return res.send(page.revision.body);
  157. }
  158. return renderPage(page, req, res);
  159. }).catch(function(err) {
  160. if (req.query.revision) {
  161. return res.redirect(encodeURI(path));
  162. }
  163. if (isMarkdown) {
  164. return res.redirect('/');
  165. }
  166. Page.hasPortalPage(path + '/', req.user)
  167. .then(function(page) {
  168. if (page) {
  169. return res.redirect(path + '/');
  170. } else {
  171. debug('Catch pageShow', err);
  172. return renderPage(null, req, res);
  173. }
  174. });
  175. });
  176. };
  177. actions.pageEdit = function(req, res) {
  178. var pageForm = req.body.pageForm;
  179. var body = pageForm.body;
  180. var currentRevision = pageForm.currentRevision;
  181. var grant = pageForm.grant;
  182. var path = pageForm.path;
  183. // TODO: make it pluggable
  184. var notify = pageForm.notify || {};
  185. debug('notify: ', notify);
  186. var redirectPath = encodeURI(path);
  187. var pageData = {};
  188. var updateOrCreate;
  189. // set to render
  190. res.locals.pageForm = pageForm;
  191. if (!Page.isCreatableName(path)) {
  192. res.redirect(redirectPath);
  193. return ;
  194. }
  195. var ignoreNotFound = true;
  196. Page.findPage(path, req.user, null, ignoreNotFound)
  197. .then(function(data) {
  198. pageData = data;
  199. if (!req.form.isValid) {
  200. debug('Form data not valid');
  201. throw new Error('Form data not valid.');
  202. }
  203. if (data && !data.isUpdatable(currentRevision)) {
  204. debug('Conflict occured');
  205. req.form.errors.push('すでに他の人がこのページを編集していたため保存できませんでした。ページを再読み込み後、自分の編集箇所のみ再度編集してください。');
  206. throw new Error('Conflict.');
  207. }
  208. if (data) {
  209. // update existing page
  210. var newRevision = Revision.prepareRevision(data, body, req.user);
  211. updateOrCreate = 'update';
  212. return Page.pushRevision(data, newRevision, req.user);
  213. } else {
  214. // new page
  215. updateOrCreate = 'create';
  216. return Page.create(path, body, req.user, {grant: grant});
  217. }
  218. }).then(function(data) {
  219. // data is a saved page data.
  220. pageData = data;
  221. if (!data) {
  222. throw new Error('Data not found');
  223. }
  224. // TODO: move to events
  225. crowi.getIo().sockets.emit('page edited', {page: data, user: req.user});
  226. if (notify.slack) {
  227. //if (notify.slack.channel && pageData.getSlackChannel()) {
  228. // // through
  229. // Page.updateNotify(data).then(function(){}).catch(function(){});
  230. //}
  231. if (notify.slack.on && notify.slack.channel) {
  232. if (crowi.slack) {
  233. notify.slack.channel.split(',').map(function(chan) {
  234. var message = crowi.slack.prepareSlackMessage(pageData, req.user, chan, updateOrCreate);
  235. crowi.slack.post(message).then(function(){}).catch(function(){});
  236. });
  237. }
  238. }
  239. }
  240. if (grant != data.grant) {
  241. return Page.updateGrant(data, grant, req.user).then(function(data) {
  242. return res.redirect(redirectPath);
  243. });
  244. } else {
  245. return res.redirect(redirectPath);
  246. }
  247. }).catch(function(err) {
  248. debug('Page create or edit error.', err);
  249. if (pageData && !req.form.isValid) {
  250. return renderPage(pageData, req, res);
  251. }
  252. return res.redirect(redirectPath);
  253. });
  254. };
  255. // app.get( '/users/:username([^/]+)/bookmarks' , loginRequired(crowi, app) , page.userBookmarkList);
  256. actions.userBookmarkList = function(req, res) {
  257. var username = req.params.username;
  258. var limit = 50;
  259. var offset = parseInt(req.query.offset) || 0;
  260. var user;
  261. var renderVars = {};
  262. var pagerOptions = { offset: offset, limit : limit };
  263. var queryOptions = { offset: offset, limit : limit + 1, populatePage: true, requestUser: req.user};
  264. User.findUserByUsername(username)
  265. .then(function(user) {
  266. if (user === null) {
  267. throw new Error('The user not found.');
  268. }
  269. renderVars.user = user;
  270. return Bookmark.findByUser(user, queryOptions);
  271. }).then(function(bookmarks) {
  272. if (bookmarks.length > limit) {
  273. bookmarks.pop();
  274. }
  275. pagerOptions.length = bookmarks.length;
  276. renderVars.pager = generatePager(pagerOptions);
  277. renderVars.bookmarks = bookmarks;
  278. return res.render('user/bookmarks', renderVars);
  279. }).catch(function(err) {
  280. debug('Error on rendereing bookmark', err);
  281. res.redirect('/');
  282. });
  283. };
  284. // app.get( '/users/:username([^/]+)/recent-create' , loginRequired(crowi, app) , page.userRecentCreatedList);
  285. actions.userRecentCreatedList = function(req, res) {
  286. var username = req.params.username;
  287. var limit = 50;
  288. var offset = parseInt(req.query.offset) || 0;
  289. var user;
  290. var renderVars = {};
  291. var pagerOptions = { offset: offset, limit : limit };
  292. var queryOptions = { offset: offset, limit : limit + 1};
  293. User.findUserByUsername(username)
  294. .then(function(user) {
  295. if (user === null) {
  296. throw new Error('The user not found.');
  297. }
  298. renderVars.user = user;
  299. return Page.findListByCreator(user, queryOptions);
  300. }).then(function(pages) {
  301. if (pages.length > limit) {
  302. pages.pop();
  303. }
  304. pagerOptions.length = pages.length;
  305. renderVars.pager = generatePager(pagerOptions);
  306. renderVars.pages = pages;
  307. return res.render('user/recent-create', renderVars);
  308. }).catch(function(err) {
  309. debug('Error on rendereing recent-created', err);
  310. res.redirect('/');
  311. });
  312. };
  313. var api = actions.api = {};
  314. /**
  315. * redirector
  316. */
  317. api.redirector = function(req, res){
  318. var id = req.params.id;
  319. Page.findPageById(id)
  320. .then(function(pageData) {
  321. if (pageData.grant == Page.GRANT_RESTRICTED && !pageData.isGrantedFor(req.user)) {
  322. return Page.pushToGrantedUsers(pageData, req.user);
  323. }
  324. return Promise.resolve(pageData);
  325. }).then(function(page) {
  326. return res.redirect(encodeURI(page.path));
  327. }).catch(function(err) {
  328. return res.redirect('/');
  329. });
  330. };
  331. /**
  332. * @api {get} /pages.get Get page data
  333. * @apiName GetPage
  334. * @apiGroup Page
  335. *
  336. * @apiParam {String} page_id
  337. * @apiParam {String} path
  338. * @apiParam {String} revision_id
  339. */
  340. api.get = function(req, res){
  341. var pagePath = req.query.path || null;
  342. var pageId = req.query.page_id || null; // TODO: handling
  343. var revisionId = req.query.revision_id || null;
  344. Page.findPage(pagePath, req.user, revisionId)
  345. .then(function(pageData) {
  346. var result = {};
  347. result.page = pageData;
  348. return res.json(ApiResponse.success(result));
  349. }).catch(function(err) {
  350. return res.json(ApiResponse.error(err));
  351. });
  352. };
  353. /**
  354. * @api {post} /pages.seen Mark as seen user
  355. * @apiName SeenPage
  356. * @apiGroup Page
  357. *
  358. * @apiParam {String} page_id Page Id.
  359. */
  360. api.seen = function(req, res){
  361. var pageId = req.body.page_id;
  362. if (!pageId) {
  363. return res.json(ApiResponse.error('page_id required'));
  364. }
  365. Page.findPageByIdAndGrantedUser(pageId, req.user)
  366. .then(function(page) {
  367. return page.seen(req.user);
  368. }).then(function(user) {
  369. var result = {};
  370. result.seenUser = user;
  371. return res.json(ApiResponse.success(result));
  372. }).catch(function(err) {
  373. debug('Seen user update error', err);
  374. return res.json(ApiResponse.error(err));
  375. });
  376. };
  377. /**
  378. * @api {post} /likes.add Like page
  379. * @apiName LikePage
  380. * @apiGroup Page
  381. *
  382. * @apiParam {String} page_id Page Id.
  383. */
  384. api.like = function(req, res){
  385. var id = req.body.page_id;
  386. Page.findPageByIdAndGrantedUser(id, req.user)
  387. .then(function(pageData) {
  388. return pageData.like(req.user);
  389. }).then(function(data) {
  390. var result = {page: data};
  391. return res.json(ApiResponse.success(result));
  392. }).catch(function(err) {
  393. debug('Like failed', err);
  394. return res.json(ApiResponse.error({}));
  395. });
  396. };
  397. /**
  398. * @api {post} /likes.remove Unlike page
  399. * @apiName UnlikePage
  400. * @apiGroup Page
  401. *
  402. * @apiParam {String} page_id Page Id.
  403. */
  404. api.unlike = function(req, res){
  405. var id = req.body.page_id;
  406. Page.findPageByIdAndGrantedUser(id, req.user)
  407. .then(function(pageData) {
  408. return pageData.unlike(req.user);
  409. }).then(function(data) {
  410. var result = {page: data};
  411. return res.json(ApiResponse.success(result));
  412. }).catch(function(err) {
  413. debug('Unlike failed', err);
  414. return res.json(ApiResponse.error({}));
  415. });
  416. };
  417. /**
  418. * @api {get} /pages.updatePost
  419. * @apiName Get UpdatePost setting list
  420. * @apiGroup Page
  421. *
  422. * @apiParam {String} path
  423. */
  424. api.getUpdatePost = function(req, res) {
  425. var path = req.query.path;
  426. var UpdatePost = crowi.model('UpdatePost');
  427. if (!path) {
  428. return res.json(ApiResponse.error({}));
  429. }
  430. UpdatePost.findSettingsByPath(path)
  431. .then(function(data) {
  432. data = data.map(function(e) {
  433. return e.channel;
  434. });
  435. debug('Found updatePost data', data);
  436. var result = {updatePost: data};
  437. return res.json(ApiResponse.success(result));
  438. }).catch(function(err) {
  439. debug('Error occured while get setting', err);
  440. return res.json(ApiResponse.error({}));
  441. });
  442. };
  443. /**
  444. * @api {post} /pages.rename Rename page
  445. * @apiName SeenPage
  446. * @apiGroup Page
  447. *
  448. * @apiParam {String} page_id Page Id.
  449. * @apiParam {String} path
  450. * @apiParam {String} revision_id
  451. * @apiParam {String} new_path
  452. * @apiParam {Bool} create_redirect
  453. */
  454. api.rename = function(req, res){
  455. var pageId = req.body.page_id;
  456. var previousRevision = req.body.revision_id || null;
  457. var newPagePath = Page.normalizePath(req.body.new_path);
  458. var options = {
  459. createRedirectPage: req.body.create_redirect || 0,
  460. moveUnderTrees: req.body.move_trees || 0,
  461. };
  462. var page = {};
  463. if (!Page.isCreatableName(newPagePath)) {
  464. return res.json(ApiResponse.error(sprintf('このページ名は作成できません (%s)', newPagePath)));
  465. }
  466. Page.findPageByPath(newPagePath)
  467. .then(function(page) {
  468. // if page found, cannot cannot rename to that path
  469. return res.json(ApiResponse.error(sprintf('このページ名は作成できません (%s)。ページが存在します。', newPagePath)));
  470. }).catch(function(err) {
  471. Page.findPageById(pageId)
  472. .then(function(pageData) {
  473. page = pageData;
  474. if (!pageData.isUpdatable(previousRevision)) {
  475. return res.json(ApiResponse.error('誰かが更新している可能性があります。ページを更新できません。'));
  476. }
  477. return Page.rename(pageData, newPagePath, req.user, options);
  478. }).then(function() {
  479. var result = {};
  480. result.page = page;
  481. return res.json(ApiResponse.success(result));
  482. }).catch(function(err) {
  483. return res.json(ApiResponse.error('エラーが発生しました。ページを更新できません。'));
  484. });
  485. });
  486. };
  487. return actions;
  488. };