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