2
0

page.js 16 KB

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