page.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. , Config = crowi.model('Config')
  7. , config = crowi.getConfig()
  8. , Revision = crowi.model('Revision')
  9. , Bookmark = crowi.model('Bookmark')
  10. , UserGroupRelation = crowi.model('UserGroupRelation')
  11. , ApiResponse = require('../util/apiResponse')
  12. , interceptorManager = crowi.getInterceptorManager()
  13. , actions = {};
  14. // register page events
  15. var pageEvent = crowi.event('page');
  16. pageEvent.on('update', function(page, user) {
  17. crowi.getIo().sockets.emit('page edited', {page, user});
  18. });
  19. function getPathFromRequest(req) {
  20. var path = '/' + (req.params[0] || '');
  21. return path.replace(/\.md$/, '');
  22. }
  23. function isUserPage(path) {
  24. if (path.match(/^\/user\/[^\/]+\/?$/)) {
  25. return true;
  26. }
  27. return false;
  28. }
  29. // TODO: total とかでちゃんと計算する
  30. function generatePager(options) {
  31. var next = null,
  32. prev = null,
  33. offset = parseInt(options.offset, 10),
  34. limit = parseInt(options.limit, 10),
  35. length = options.length || 0;
  36. if (offset > 0) {
  37. prev = offset - limit;
  38. if (prev < 0) {
  39. prev = 0;
  40. }
  41. }
  42. if (length < limit) {
  43. next = null;
  44. } else {
  45. next = offset + limit;
  46. }
  47. return {
  48. prev: prev,
  49. next: next,
  50. offset: offset,
  51. };
  52. }
  53. /**
  54. * switch action by behaviorType
  55. */
  56. actions.pageListShowWrapper = function(req, res) {
  57. const behaviorType = Config.behaviorType(config);
  58. if (!behaviorType || 'crowi' === behaviorType) {
  59. return actions.pageListShow(req, res);
  60. }
  61. else {
  62. return actions.pageListShowForCrowiPlus(req, res);
  63. }
  64. }
  65. /**
  66. * switch action by behaviorType
  67. */
  68. actions.pageShowWrapper = function(req, res) {
  69. const behaviorType = Config.behaviorType(config);
  70. if (!behaviorType || 'crowi' === behaviorType) {
  71. return actions.pageShow(req, res);
  72. }
  73. else {
  74. return actions.pageShowForCrowiPlus(req, res);
  75. }
  76. }
  77. /**
  78. * switch action by behaviorType
  79. */
  80. actions.trashPageListShowWrapper = function(req, res) {
  81. const behaviorType = Config.behaviorType(config);
  82. if (!behaviorType || 'crowi' === behaviorType) {
  83. // Crowi behavior for '/trash/*'
  84. return actions.deletedPageListShow(req, res);
  85. }
  86. else {
  87. // redirect to '/trash'
  88. return res.redirect('/trash');
  89. }
  90. }
  91. /**
  92. * switch action by behaviorType
  93. */
  94. actions.trashPageShowWrapper = function(req, res) {
  95. const behaviorType = Config.behaviorType(config);
  96. if (!behaviorType || 'crowi' === behaviorType) {
  97. // redirect to '/trash/'
  98. return res.redirect('/trash/');
  99. }
  100. else {
  101. // Crowi behavior for '/trash/*'
  102. return actions.deletedPageListShow(req, res);
  103. }
  104. }
  105. /**
  106. * switch action by behaviorType
  107. */
  108. actions.deletedPageListShowWrapper = function(req, res) {
  109. const behaviorType = Config.behaviorType(config);
  110. if (!behaviorType || 'crowi' === behaviorType) {
  111. // Crowi behavior for '/trash/*'
  112. return actions.deletedPageListShow(req, res);
  113. }
  114. else {
  115. const path = '/trash' + getPathFromRequest(req);
  116. return res.redirect(path);
  117. }
  118. }
  119. actions.pageListShow = function(req, res) {
  120. var path = getPathFromRequest(req);
  121. var limit = 50;
  122. var offset = parseInt(req.query.offset) || 0;
  123. var SEENER_THRESHOLD = 10;
  124. // add slash if root
  125. path = path + (path == '/' ? '' : '/');
  126. debug('Page list show', path);
  127. // index page
  128. var pagerOptions = {
  129. offset: offset,
  130. limit : limit
  131. };
  132. var queryOptions = {
  133. offset: offset,
  134. limit : limit + 1,
  135. isPopulateRevisionBody: Config.isEnabledTimeline(config),
  136. };
  137. var renderVars = {
  138. page: null,
  139. path: path,
  140. isPortal: false,
  141. pages: [],
  142. tree: [],
  143. };
  144. Page.hasPortalPage(path, req.user, req.query.revision)
  145. .then(function(portalPage) {
  146. renderVars.page = portalPage;
  147. renderVars.isPortal = (portalPage != null);
  148. if (portalPage) {
  149. renderVars.revision = portalPage.revision;
  150. return Revision.findRevisionList(portalPage.path, {});
  151. } else {
  152. return Promise.resolve([]);
  153. }
  154. }).then(function(tree) {
  155. renderVars.tree = tree;
  156. return Page.findListByStartWith(path, req.user, queryOptions);
  157. }).then(function(pageList) {
  158. if (pageList.length > limit) {
  159. pageList.pop();
  160. }
  161. pagerOptions.length = pageList.length;
  162. renderVars.viewConfig = {
  163. seener_threshold: SEENER_THRESHOLD,
  164. };
  165. renderVars.pager = generatePager(pagerOptions);
  166. renderVars.pages = pageList;
  167. res.render('customlayout-selector/page_list', renderVars);
  168. }).catch(function(err) {
  169. debug('Error on rendering pageListShow', err);
  170. });
  171. };
  172. actions.pageListShowForCrowiPlus = function(req, res) {
  173. var path = getPathFromRequest(req);
  174. // omit the slash of the last
  175. path = path.replace((/\/$/), '');
  176. // redirect
  177. return res.redirect(path);
  178. }
  179. actions.pageShowForCrowiPlus = function(req, res) {
  180. var path = getPathFromRequest(req);
  181. var limit = 50;
  182. var offset = parseInt(req.query.offset) || 0;
  183. var SEENER_THRESHOLD = 10;
  184. // index page
  185. var pagerOptions = {
  186. offset: offset,
  187. limit : limit
  188. };
  189. var queryOptions = {
  190. offset: offset,
  191. limit : limit + 1,
  192. isPopulateRevisionBody: Config.isEnabledTimeline(config),
  193. includeDeletedPage: path.startsWith('/trash/'),
  194. };
  195. var renderVars = {
  196. path: path,
  197. page: null,
  198. revision: {},
  199. author: false,
  200. pages: [],
  201. tree: [],
  202. userRelatedGroups: [],
  203. };
  204. var pageTeamplate = 'customlayout-selector/page';
  205. var isRedirect = false;
  206. Page.findPage(path, req.user, req.query.revision)
  207. .then(function(page) {
  208. debug('Page found', page._id, page.path);
  209. // redirect
  210. if (page.redirectTo) {
  211. debug(`Redirect to '${page.redirectTo}'`);
  212. isRedirect = true;
  213. return res.redirect(encodeURI(page.redirectTo + '?redirectFrom=' + page.path));
  214. }
  215. renderVars.page = page;
  216. if (page) {
  217. renderVars.path = page.path;
  218. renderVars.revision = page.revision;
  219. renderVars.author = page.revision.author;
  220. return Revision.findRevisionList(page.path, {})
  221. .then(function(tree) {
  222. renderVars.tree = tree;
  223. return Promise.resolve();
  224. }).then(function() {
  225. var userPage = isUserPage(page.path);
  226. var userData = null;
  227. if (userPage) {
  228. // change template
  229. pageTeamplate = 'customlayout-selector/user_page';
  230. return User.findUserByUsername(User.getUsernameByPath(page.path))
  231. .then(function(data) {
  232. if (data === null) {
  233. throw new Error('The user not found.');
  234. }
  235. userData = data;
  236. renderVars.pageUser = userData;
  237. return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
  238. }).then(function(bookmarkList) {
  239. renderVars.bookmarkList = bookmarkList;
  240. return Page.findListByCreator(userData, {limit: 10}, req.user);
  241. }).then(function(createdList) {
  242. renderVars.createdList = createdList;
  243. return Promise.resolve();
  244. }).catch(function(err) {
  245. debug('Error on finding user related entities', err);
  246. // pass
  247. });
  248. }
  249. else {
  250. return Promise.resolve();
  251. }
  252. });
  253. } else {
  254. return Promise.resolve();
  255. }
  256. })
  257. // page not exists
  258. .catch(function(err) {
  259. debug('Page not found', path);
  260. // change template
  261. pageTeamplate = 'customlayout-selector/not_found';
  262. })
  263. // get list pages
  264. .then(function() {
  265. if (!isRedirect) {
  266. Page.findListWithDescendants(path, req.user, queryOptions)
  267. .then(function(pageList) {
  268. if (pageList.length > limit) {
  269. pageList.pop();
  270. }
  271. pagerOptions.length = pageList.length;
  272. renderVars.viewConfig = {
  273. seener_threshold: SEENER_THRESHOLD,
  274. };
  275. renderVars.pager = generatePager(pagerOptions);
  276. renderVars.pages = pageList;
  277. return Promise.resolve();
  278. })
  279. .then(function() {
  280. return interceptorManager.process('beforeRenderPage', req, res, renderVars);
  281. })
  282. .then(function() {
  283. res.render(req.query.presentation ? 'page_presentation' : pageTeamplate, renderVars);
  284. })
  285. .catch(function(err) {
  286. console.log(err);
  287. debug('Error on rendering pageListShowForCrowiPlus', err);
  288. });
  289. }
  290. })
  291. .then(function() {
  292. return UserGroupRelation.findAllRelationForUser(req.user);
  293. }).then(function (groupRelations) {
  294. debug('findPage : relatedGroups ', groupRelations);
  295. renderVars.userRelatedGroups = groupRelations.map(relation => relation.relatedGroup);
  296. debug('findPage : groups ', renderVars.userRelatedGroups);
  297. return Promise.resolve();
  298. });
  299. }
  300. actions.deletedPageListShow = function(req, res) {
  301. var path = '/trash' + getPathFromRequest(req);
  302. var limit = 50;
  303. var offset = parseInt(req.query.offset) || 0;
  304. // index page
  305. var pagerOptions = {
  306. offset: offset,
  307. limit : limit
  308. };
  309. var queryOptions = {
  310. offset: offset,
  311. limit : limit + 1,
  312. includeDeletedPage: true,
  313. };
  314. var renderVars = {
  315. page: null,
  316. path: path,
  317. pages: [],
  318. };
  319. Page.findListWithDescendants(path, req.user, queryOptions)
  320. .then(function(pageList) {
  321. if (pageList.length > limit) {
  322. pageList.pop();
  323. }
  324. pagerOptions.length = pageList.length;
  325. renderVars.pager = generatePager(pagerOptions);
  326. renderVars.pages = pageList;
  327. res.render('customlayout-selector/page_list', renderVars);
  328. }).catch(function(err) {
  329. debug('Error on rendering deletedPageListShow', err);
  330. });
  331. };
  332. actions.search = function(req, res) {
  333. // spec: ?q=query&sort=sort_order&author=author_filter
  334. var query = req.query.q;
  335. var search = require('../util/search')(crowi);
  336. search.searchPageByKeyword(query)
  337. .then(function(pages) {
  338. debug('pages', pages);
  339. if (pages.hits.total <= 0) {
  340. return Promise.resolve([]);
  341. }
  342. var ids = pages.hits.hits.map(function(page) {
  343. return page._id;
  344. });
  345. return Page.findListByPageIds(ids);
  346. }).then(function(pages) {
  347. res.render('customlayout-selector/page_list', {
  348. path: '/',
  349. pages: pages,
  350. pager: generatePager({offset: 0, limit: 50})
  351. });
  352. }).catch(function(err) {
  353. debug('search error', err);
  354. });
  355. };
  356. function renderPage(pageData, req, res) {
  357. // create page
  358. if (!pageData) {
  359. return res.render('customlayout-selector/not_found', {
  360. author: {},
  361. page: false,
  362. });
  363. }
  364. if (pageData.redirectTo) {
  365. return res.redirect(encodeURI(pageData.redirectTo + '?redirectFrom=' + pageData.path));
  366. }
  367. var renderVars = {
  368. path: pageData.path,
  369. page: pageData,
  370. revision: pageData.revision || {},
  371. author: pageData.revision.author || false,
  372. };
  373. var userPage = isUserPage(pageData.path);
  374. var userData = null;
  375. Revision.findRevisionList(pageData.path, {})
  376. .then(function(tree) {
  377. renderVars.tree = tree;
  378. return Promise.resolve();
  379. }).then(function() {
  380. if (userPage) {
  381. return User.findUserByUsername(User.getUsernameByPath(pageData.path))
  382. .then(function(data) {
  383. if (data === null) {
  384. throw new Error('The user not found.');
  385. }
  386. userData = data;
  387. renderVars.pageUser = userData;
  388. return Bookmark.findByUser(userData, {limit: 10, populatePage: true, requestUser: req.user});
  389. }).then(function(bookmarkList) {
  390. renderVars.bookmarkList = bookmarkList;
  391. return Page.findListByCreator(userData, {limit: 10}, req.user);
  392. }).then(function(createdList) {
  393. renderVars.createdList = createdList;
  394. return Promise.resolve();
  395. }).catch(function(err) {
  396. debug('Error on finding user related entities', err);
  397. // pass
  398. });
  399. } else {
  400. return Promise.resolve();
  401. }
  402. }).then(function() {
  403. return interceptorManager.process('beforeRenderPage', req, res, renderVars);
  404. }).then(function() {
  405. var defaultPageTeamplate = 'customlayout-selector/page';
  406. if (userData) {
  407. defaultPageTeamplate = 'customlayout-selector/user_page';
  408. }
  409. res.render(req.query.presentation ? 'page_presentation' : defaultPageTeamplate, renderVars);
  410. }).catch(function(err) {
  411. debug('Error: renderPage()', err);
  412. if (err) {
  413. res.redirect('/');
  414. }
  415. });
  416. }
  417. actions.pageShow = function(req, res) {
  418. var path = path || getPathFromRequest(req);
  419. var options = {};
  420. // FIXME: せっかく getPathFromRequest になってるのにここが生 params[0] だとダサイ
  421. var isMarkdown = req.params[0].match(/.+\.md$/) || false;
  422. res.locals.path = path;
  423. Page.findPage(path, req.user, req.query.revision)
  424. .then(function(page) {
  425. debug('Page found', page._id, page.path);
  426. if (isMarkdown) {
  427. res.set('Content-Type', 'text/plain');
  428. return res.send(page.revision.body);
  429. }
  430. return renderPage(page, req, res);
  431. }).catch(function(err) {
  432. const normalizedPath = Page.normalizePath(path);
  433. if (normalizedPath !== path) {
  434. return res.redirect(normalizedPath);
  435. }
  436. // pageShow は /* にマッチしてる最後の砦なので、creatableName でない routing は
  437. // これ以前に定義されているはずなので、こうしてしまって問題ない。
  438. if (!Page.isCreatableName(path)) {
  439. // 削除済みページの場合 /trash 以下に移動しているので creatableName になっていないので、表示を許可
  440. debug('Page is not creatable name.', path);
  441. res.redirect('/');
  442. return ;
  443. }
  444. if (req.query.revision) {
  445. return res.redirect(encodeURI(path));
  446. }
  447. if (isMarkdown) {
  448. return res.redirect('/');
  449. }
  450. Page.hasPortalPage(path + '/', req.user)
  451. .then(function(page) {
  452. if (page) {
  453. return res.redirect(encodeURI(path) + '/');
  454. } else {
  455. var fixed = Page.fixToCreatableName(path)
  456. if (fixed !== path) {
  457. debug('fixed page name', fixed)
  458. res.redirect(encodeURI(fixed));
  459. return ;
  460. }
  461. // if guest user
  462. if (!req.user) {
  463. res.redirect('/');
  464. }
  465. // render editor
  466. debug('Catch pageShow', err);
  467. return renderPage(null, req, res);
  468. }
  469. }).catch(function(err) {
  470. debug('Error on rendering pageShow (redirect to portal)', err);
  471. });
  472. });
  473. };
  474. actions.pageEdit = function(req, res) {
  475. var pageForm = req.body.pageForm;
  476. var body = pageForm.body;
  477. var currentRevision = pageForm.currentRevision;
  478. var grant = pageForm.grant;
  479. var path = pageForm.path;
  480. var grantUserGroupId = pageForm.grantUserGroupId
  481. // TODO: make it pluggable
  482. var notify = pageForm.notify || {};
  483. debug('notify: ', notify);
  484. var redirectPath = encodeURI(path);
  485. var pageData = {};
  486. var updateOrCreate;
  487. var previousRevision = false;
  488. // set to render
  489. res.locals.pageForm = pageForm;
  490. // 削除済みページはここで編集不可判定される
  491. if (!Page.isCreatableName(path)) {
  492. res.redirect(redirectPath);
  493. return ;
  494. }
  495. var ignoreNotFound = true;
  496. Page.findPage(path, req.user, null, ignoreNotFound)
  497. .then(function(data) {
  498. pageData = data;
  499. if (!req.form.isValid) {
  500. debug('Form data not valid');
  501. throw new Error('Form data not valid.');
  502. }
  503. if (data && !data.isUpdatable(currentRevision)) {
  504. debug('Conflict occured');
  505. req.form.errors.push('page_edit.notice.conflict');
  506. throw new Error('Conflict.');
  507. }
  508. if (data) {
  509. previousRevision = data.revision;
  510. return Page.updatePage(data, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
  511. } else {
  512. // new page
  513. updateOrCreate = 'create';
  514. return Page.create(path, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
  515. }
  516. }).then(function(data) {
  517. // data is a saved page data.
  518. pageData = data;
  519. if (!data) {
  520. throw new Error('Data not found');
  521. }
  522. // TODO: move to events
  523. if (notify.slack) {
  524. if (notify.slack.on && notify.slack.channel) {
  525. data.updateSlackChannel(notify.slack.channel).then(function(){}).catch(function(){});
  526. if (crowi.slack) {
  527. notify.slack.channel.split(',').map(function(chan) {
  528. var message = crowi.slack.prepareSlackMessage(pageData, req.user, chan, updateOrCreate, previousRevision);
  529. crowi.slack.post(message.channel, message.text, message).then(function(){}).catch(function(){});
  530. });
  531. }
  532. }
  533. }
  534. return res.redirect(redirectPath);
  535. }).catch(function(err) {
  536. debug('Page create or edit error.', err);
  537. if (pageData && !req.form.isValid) {
  538. return renderPage(pageData, req, res);
  539. }
  540. return res.redirect(redirectPath);
  541. });
  542. };
  543. var api = actions.api = {};
  544. /**
  545. * redirector
  546. */
  547. api.redirector = function(req, res){
  548. var id = req.params.id;
  549. Page.findPageById(id)
  550. .then(function(pageData) {
  551. if (pageData.grant == Page.GRANT_RESTRICTED && !pageData.isGrantedFor(req.user)) {
  552. return Page.pushToGrantedUsers(pageData, req.user);
  553. }
  554. return Promise.resolve(pageData);
  555. }).then(function(page) {
  556. return res.redirect(encodeURI(page.path));
  557. }).catch(function(err) {
  558. return res.redirect('/');
  559. });
  560. };
  561. /**
  562. * @api {get} /pages.list List pages by user
  563. * @apiName ListPage
  564. * @apiGroup Page
  565. *
  566. * @apiParam {String} path
  567. * @apiParam {String} user
  568. */
  569. api.list = function(req, res) {
  570. var username = req.query.user || null;
  571. var path = req.query.path || null;
  572. var limit = 50;
  573. var offset = parseInt(req.query.offset) || 0;
  574. var pagerOptions = { offset: offset, limit : limit };
  575. var queryOptions = { offset: offset, limit : limit + 1};
  576. // Accepts only one of these
  577. if (username === null && path === null) {
  578. return res.json(ApiResponse.error('Parameter user or path is required.'));
  579. }
  580. if (username !== null && path !== null) {
  581. return res.json(ApiResponse.error('Parameter user or path is required.'));
  582. }
  583. var pageFetcher;
  584. if (path === null) {
  585. pageFetcher = User.findUserByUsername(username)
  586. .then(function(user) {
  587. if (user === null) {
  588. throw new Error('The user not found.');
  589. }
  590. return Page.findListByCreator(user, queryOptions, req.user);
  591. });
  592. } else {
  593. pageFetcher = Page.findListByStartWith(path, req.user, queryOptions);
  594. }
  595. pageFetcher
  596. .then(function(pages) {
  597. if (pages.length > limit) {
  598. pages.pop();
  599. }
  600. pagerOptions.length = pages.length;
  601. var result = {};
  602. result.pages = pages;
  603. return res.json(ApiResponse.success(result));
  604. }).catch(function(err) {
  605. return res.json(ApiResponse.error(err));
  606. });
  607. };
  608. /**
  609. * @api {post} /pages.create Create new page
  610. * @apiName CreatePage
  611. * @apiGroup Page
  612. *
  613. * @apiParam {String} body
  614. * @apiParam {String} path
  615. * @apiParam {String} grant
  616. */
  617. api.create = function(req, res){
  618. var body = req.body.body || null;
  619. var pagePath = req.body.path || null;
  620. var grant = req.body.grant || null;
  621. var grantUserGroupId = req.body.grantUserGroupId || null;
  622. if (body === null || pagePath === null) {
  623. return res.json(ApiResponse.error('Parameters body and path are required.'));
  624. }
  625. var ignoreNotFound = true;
  626. Page.findPage(pagePath, req.user, null, ignoreNotFound)
  627. .then(function(data) {
  628. if (data !== null) {
  629. throw new Error('Page exists');
  630. }
  631. return Page.create(pagePath, body, req.user, { grant: grant, grantUserGroupId: grantUserGroupId});
  632. }).then(function(data) {
  633. if (!data) {
  634. throw new Error('Failed to create page.');
  635. }
  636. var result = { page: data.toObject() };
  637. result.page.lastUpdateUser = User.filterToPublicFields(data.lastUpdateUser);
  638. result.page.creator = User.filterToPublicFields(data.creator);
  639. return res.json(ApiResponse.success(result));
  640. }).catch(function(err) {
  641. return res.json(ApiResponse.error(err));
  642. });;
  643. };
  644. /**
  645. * @api {post} /pages.update Update page
  646. * @apiName UpdatePage
  647. * @apiGroup Page
  648. *
  649. * @apiParam {String} body
  650. * @apiParam {String} page_id
  651. * @apiParam {String} revision_id
  652. * @apiParam {String} grant
  653. *
  654. * In the case of the page exists:
  655. * - If revision_id is specified => update the page,
  656. * - If revision_id is not specified => force update by the new contents.
  657. */
  658. api.update = function(req, res){
  659. var pageBody = req.body.body || null;
  660. var pageId = req.body.page_id || null;
  661. var revisionId = req.body.revision_id || null;
  662. var grant = req.body.grant || null;
  663. var grantUserGroupId = req.body.grantUserGroupId || null;
  664. if (pageId === null || pageBody === null) {
  665. return res.json(ApiResponse.error('page_id and body are required.'));
  666. }
  667. Page.findPageByIdAndGrantedUser(pageId, req.user)
  668. .then(function(pageData) {
  669. if (pageData && revisionId !== null && !pageData.isUpdatable(revisionId)) {
  670. throw new Error('Revision error.');
  671. };
  672. var grantOption = {grant: pageData.grant};
  673. if (grant !== null) {
  674. grantOption.grant = grant;
  675. }
  676. if (grantUserGroupId != null) {
  677. grantOption.grantUserGroupId = grantUserGroupId;
  678. }
  679. return Page.updatePage(pageData, pageBody, req.user, grantOption);
  680. }).then(function(pageData) {
  681. var result = {
  682. page: pageData.toObject(),
  683. };
  684. result.page.lastUpdateUser = User.filterToPublicFields(result.page.lastUpdateUser);
  685. return res.json(ApiResponse.success(result));
  686. }).catch(function(err) {
  687. debug('error on _api/pages.update', err);
  688. return res.json(ApiResponse.error(err));
  689. });
  690. };
  691. /**
  692. * @api {get} /pages.get Get page data
  693. * @apiName GetPage
  694. * @apiGroup Page
  695. *
  696. * @apiParam {String} page_id
  697. * @apiParam {String} path
  698. * @apiParam {String} revision_id
  699. */
  700. api.get = function(req, res){
  701. const pagePath = req.query.path || null;
  702. const pageId = req.query.page_id || null; // TODO: handling
  703. const revisionId = req.query.revision_id || null;
  704. if (!pageId && !pagePath) {
  705. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  706. }
  707. let pageFinder;
  708. if (pageId) { // prioritized
  709. pageFinder = Page.findPageByIdAndGrantedUser(pageId, req.user);
  710. } else if (pagePath) {
  711. pageFinder = Page.findPage(pagePath, req.user, revisionId);
  712. }
  713. pageFinder.then(function(pageData) {
  714. var result = {};
  715. result.page = pageData;
  716. return res.json(ApiResponse.success(result));
  717. }).catch(function(err) {
  718. return res.json(ApiResponse.error(err));
  719. });
  720. };
  721. /**
  722. * @api {post} /pages.seen Mark as seen user
  723. * @apiName SeenPage
  724. * @apiGroup Page
  725. *
  726. * @apiParam {String} page_id Page Id.
  727. */
  728. api.seen = function(req, res){
  729. var pageId = req.body.page_id;
  730. if (!pageId) {
  731. return res.json(ApiResponse.error('page_id required'));
  732. }
  733. Page.findPageByIdAndGrantedUser(pageId, req.user)
  734. .then(function(page) {
  735. return page.seen(req.user);
  736. }).then(function(user) {
  737. var result = {};
  738. result.seenUser = user;
  739. return res.json(ApiResponse.success(result));
  740. }).catch(function(err) {
  741. debug('Seen user update error', err);
  742. return res.json(ApiResponse.error(err));
  743. });
  744. };
  745. /**
  746. * @api {post} /likes.add Like page
  747. * @apiName LikePage
  748. * @apiGroup Page
  749. *
  750. * @apiParam {String} page_id Page Id.
  751. */
  752. api.like = function(req, res){
  753. var id = req.body.page_id;
  754. Page.findPageByIdAndGrantedUser(id, req.user)
  755. .then(function(pageData) {
  756. return pageData.like(req.user);
  757. }).then(function(data) {
  758. var result = {page: data};
  759. return res.json(ApiResponse.success(result));
  760. }).catch(function(err) {
  761. debug('Like failed', err);
  762. return res.json(ApiResponse.error({}));
  763. });
  764. };
  765. /**
  766. * @api {post} /likes.remove Unlike page
  767. * @apiName UnlikePage
  768. * @apiGroup Page
  769. *
  770. * @apiParam {String} page_id Page Id.
  771. */
  772. api.unlike = function(req, res){
  773. var id = req.body.page_id;
  774. Page.findPageByIdAndGrantedUser(id, req.user)
  775. .then(function(pageData) {
  776. return pageData.unlike(req.user);
  777. }).then(function(data) {
  778. var result = {page: data};
  779. return res.json(ApiResponse.success(result));
  780. }).catch(function(err) {
  781. debug('Unlike failed', err);
  782. return res.json(ApiResponse.error({}));
  783. });
  784. };
  785. /**
  786. * @api {get} /pages.updatePost
  787. * @apiName Get UpdatePost setting list
  788. * @apiGroup Page
  789. *
  790. * @apiParam {String} path
  791. */
  792. api.getUpdatePost = function(req, res) {
  793. var path = req.query.path;
  794. var UpdatePost = crowi.model('UpdatePost');
  795. if (!path) {
  796. return res.json(ApiResponse.error({}));
  797. }
  798. UpdatePost.findSettingsByPath(path)
  799. .then(function(data) {
  800. data = data.map(function(e) {
  801. return e.channel;
  802. });
  803. debug('Found updatePost data', data);
  804. var result = {updatePost: data};
  805. return res.json(ApiResponse.success(result));
  806. }).catch(function(err) {
  807. debug('Error occured while get setting', err);
  808. return res.json(ApiResponse.error({}));
  809. });
  810. };
  811. /**
  812. * @api {post} /pages.remove Remove page
  813. * @apiName RemovePage
  814. * @apiGroup Page
  815. *
  816. * @apiParam {String} page_id Page Id.
  817. * @apiParam {String} revision_id
  818. */
  819. api.remove = function(req, res){
  820. var pageId = req.body.page_id;
  821. var previousRevision = req.body.revision_id || null;
  822. // get completely flag
  823. const isCompletely = (req.body.completely !== undefined);
  824. // get recursively flag
  825. const isRecursively = (req.body.recursively !== undefined);
  826. Page.findPageByIdAndGrantedUser(pageId, req.user)
  827. .then(function(pageData) {
  828. debug('Delete page', pageData._id, pageData.path);
  829. if (isCompletely) {
  830. if (isRecursively) {
  831. return Page.completelyDeletePageRecursively(pageData, req.user);
  832. }
  833. else {
  834. return Page.completelyDeletePage(pageData, req.user);
  835. }
  836. }
  837. // else
  838. if (!pageData.isUpdatable(previousRevision)) {
  839. throw new Error('Someone could update this page, so couldn\'t delete.');
  840. }
  841. if (isRecursively) {
  842. return Page.deletePageRecursively(pageData, req.user);
  843. }
  844. else {
  845. return Page.deletePage(pageData, req.user);
  846. }
  847. }).then(function(data) {
  848. debug('Page deleted', data.path);
  849. var result = {};
  850. result.page = data;
  851. return res.json(ApiResponse.success(result));
  852. }).catch(function(err) {
  853. debug('Error occured while get setting', err, err.stack);
  854. return res.json(ApiResponse.error('Failed to delete page.'));
  855. });
  856. };
  857. /**
  858. * @api {post} /pages.revertRemove Revert removed page
  859. * @apiName RevertRemovePage
  860. * @apiGroup Page
  861. *
  862. * @apiParam {String} page_id Page Id.
  863. */
  864. api.revertRemove = function(req, res){
  865. var pageId = req.body.page_id;
  866. // get recursively flag
  867. const isRecursively = (req.body.recursively !== undefined);
  868. Page.findPageByIdAndGrantedUser(pageId, req.user)
  869. .then(function(pageData) {
  870. if (isRecursively) {
  871. return Page.revertDeletedPageRecursively(pageData, req.user);
  872. }
  873. else {
  874. return Page.revertDeletedPage(pageData, req.user);
  875. }
  876. }).then(function(data) {
  877. debug('Complete to revert deleted page', data.path);
  878. var result = {};
  879. result.page = data;
  880. return res.json(ApiResponse.success(result));
  881. }).catch(function(err) {
  882. debug('Error occured while get setting', err, err.stack);
  883. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  884. });
  885. };
  886. /**
  887. * @api {post} /pages.rename Rename page
  888. * @apiName RenamePage
  889. * @apiGroup Page
  890. *
  891. * @apiParam {String} page_id Page Id.
  892. * @apiParam {String} path
  893. * @apiParam {String} revision_id
  894. * @apiParam {String} new_path
  895. * @apiParam {Bool} create_redirect
  896. */
  897. api.rename = function(req, res){
  898. var pageId = req.body.page_id;
  899. var previousRevision = req.body.revision_id || null;
  900. var newPagePath = Page.normalizePath(req.body.new_path);
  901. var options = {
  902. createRedirectPage: req.body.create_redirect || 0,
  903. moveUnderTrees: req.body.move_trees || 0,
  904. };
  905. var isRecursiveMove = req.body.move_recursively || 0;
  906. var page = {};
  907. if (!Page.isCreatableName(newPagePath)) {
  908. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})`));
  909. }
  910. Page.findPageByPath(newPagePath)
  911. .then(function(page) {
  912. // if page found, cannot cannot rename to that path
  913. return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`));
  914. }).catch(function(err) {
  915. Page.findPageById(pageId)
  916. .then(function(pageData) {
  917. page = pageData;
  918. if (!pageData.isUpdatable(previousRevision)) {
  919. throw new Error('Someone could update this page, so couldn\'t delete.');
  920. }
  921. if (isRecursiveMove) {
  922. return Page.renameRecursively(pageData, newPagePath, req.user, options);
  923. }
  924. else {
  925. return Page.rename(pageData, newPagePath, req.user, options);
  926. }
  927. }).then(function() {
  928. var result = {};
  929. result.page = page;
  930. return res.json(ApiResponse.success(result));
  931. }).catch(function(err) {
  932. return res.json(ApiResponse.error('Failed to update page.'));
  933. });
  934. });
  935. };
  936. /**
  937. * @api {post} /pages.duplicate Duplicate page
  938. * @apiName DuplicatePage
  939. * @apiGroup Page
  940. *
  941. * @apiParam {String} page_id Page Id.
  942. * @apiParam {String} new_path
  943. */
  944. api.duplicate = function (req, res) {
  945. var pageId = req.body.page_id;
  946. var newPagePath = Page.normalizePath(req.body.new_path);
  947. var page = {};
  948. Page.findPageById(pageId)
  949. .then(function (pageData) {
  950. req.body.path = newPagePath;
  951. req.body.body = pageData.revision.body;
  952. req.body.grant = pageData.grant;
  953. return api.create(req, res);
  954. });
  955. };
  956. /**
  957. * @api {post} /pages.unlink Remove the redirecting page
  958. * @apiName UnlinkPage
  959. * @apiGroup Page
  960. *
  961. * @apiParam {String} page_id Page Id.
  962. * @apiParam {String} revision_id
  963. */
  964. api.unlink = function(req, res){
  965. var pageId = req.body.page_id;
  966. Page.findPageByIdAndGrantedUser(pageId, req.user)
  967. .then(function(pageData) {
  968. debug('Unlink page', pageData._id, pageData.path);
  969. return Page.removeRedirectOriginPageByPath(pageData.path)
  970. .then(() => pageData);
  971. }).then(function(data) {
  972. debug('Redirect Page deleted', data.path);
  973. var result = {};
  974. result.page = data;
  975. return res.json(ApiResponse.success(result));
  976. }).catch(function(err) {
  977. debug('Error occured while get setting', err, err.stack);
  978. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  979. });
  980. };
  981. return actions;
  982. };