page.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. /**
  2. * @swagger
  3. * tags:
  4. * name: Pages
  5. */
  6. /**
  7. * @swagger
  8. *
  9. * components:
  10. * schemas:
  11. * Page:
  12. * description: Page
  13. * type: object
  14. * properties:
  15. * _id:
  16. * type: string
  17. * description: page ID
  18. * example: 5e07345972560e001761fa63
  19. * __v:
  20. * type: number
  21. * description: DB record version
  22. * example: 0
  23. * commentCount:
  24. * type: number
  25. * description: count of comments
  26. * example: 3
  27. * createdAt:
  28. * type: string
  29. * description: date created at
  30. * example: 2010-01-01T00:00:00.000Z
  31. * creator:
  32. * $ref: '#/components/schemas/User'
  33. * extended:
  34. * type: object
  35. * description: extend data
  36. * example: {}
  37. * grant:
  38. * type: number
  39. * description: grant
  40. * example: 1
  41. * grantedUsers:
  42. * type: array
  43. * description: granted users
  44. * items:
  45. * type: string
  46. * description: user ID
  47. * example: ["5ae5fccfc5577b0004dbd8ab"]
  48. * lastUpdateUser:
  49. * $ref: '#/components/schemas/User'
  50. * liker:
  51. * type: array
  52. * description: granted users
  53. * items:
  54. * type: string
  55. * description: user ID
  56. * example: []
  57. * path:
  58. * type: string
  59. * description: page path
  60. * example: /
  61. * redirectTo:
  62. * type: string
  63. * description: redirect path
  64. * example: ""
  65. * revision:
  66. * $ref: '#/components/schemas/Revision'
  67. * seenUsers:
  68. * type: array
  69. * description: granted users
  70. * items:
  71. * type: string
  72. * description: user ID
  73. * example: ["5ae5fccfc5577b0004dbd8ab"]
  74. * status:
  75. * type: string
  76. * description: status
  77. * enum:
  78. * - 'wip'
  79. * - 'published'
  80. * - 'deleted'
  81. * - 'deprecated'
  82. * example: published
  83. * updatedAt:
  84. * type: string
  85. * description: date updated at
  86. * example: 2010-01-01T00:00:00.000Z
  87. *
  88. * UpdatePost:
  89. * description: UpdatePost
  90. * type: object
  91. * properties:
  92. * _id:
  93. * type: string
  94. * description: update post ID
  95. * example: 5e0734e472560e001761fa68
  96. * __v:
  97. * type: number
  98. * description: DB record version
  99. * example: 0
  100. * pathPattern:
  101. * type: string
  102. * description: path pattern
  103. * example: /test
  104. * patternPrefix:
  105. * type: string
  106. * description: patternPrefix prefix
  107. * example: /
  108. * patternPrefix2:
  109. * type: string
  110. * description: path
  111. * example: test
  112. * channel:
  113. * type: string
  114. * description: channel
  115. * example: general
  116. * provider:
  117. * type: string
  118. * description: provider
  119. * enum:
  120. * - slack
  121. * example: slack
  122. * creator:
  123. * $ref: '#/components/schemas/User'
  124. * createdAt:
  125. * type: string
  126. * description: date created at
  127. * example: 2010-01-01T00:00:00.000Z
  128. */
  129. /* eslint-disable no-use-before-define */
  130. module.exports = function(crowi, app) {
  131. const debug = require('debug')('growi:routes:page');
  132. const logger = require('@alias/logger')('growi:routes:page');
  133. const swig = require('swig-templates');
  134. const pathUtils = require('growi-commons').pathUtils;
  135. const Page = crowi.model('Page');
  136. const User = crowi.model('User');
  137. const Bookmark = crowi.model('Bookmark');
  138. const PageTagRelation = crowi.model('PageTagRelation');
  139. const UpdatePost = crowi.model('UpdatePost');
  140. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  141. const ShareLink = crowi.model('ShareLink');
  142. const ApiResponse = require('../util/apiResponse');
  143. const getToday = require('../util/getToday');
  144. const { slackNotificationService, configManager } = crowi;
  145. const interceptorManager = crowi.getInterceptorManager();
  146. const globalNotificationService = crowi.getGlobalNotificationService();
  147. const actions = {};
  148. // register page events
  149. const pageEvent = crowi.event('page');
  150. pageEvent.on('create', (page, user, socketClientId) => {
  151. page = serializeToObj(page); // eslint-disable-line no-param-reassign
  152. crowi.getIo().sockets.emit('page:create', { page, user, socketClientId });
  153. });
  154. pageEvent.on('update', (page, user, socketClientId) => {
  155. page = serializeToObj(page); // eslint-disable-line no-param-reassign
  156. crowi.getIo().sockets.emit('page:update', { page, user, socketClientId });
  157. });
  158. pageEvent.on('delete', (page, user, socketClientId) => {
  159. page = serializeToObj(page); // eslint-disable-line no-param-reassign
  160. crowi.getIo().sockets.emit('page:delete', { page, user, socketClientId });
  161. });
  162. function serializeToObj(page) {
  163. const returnObj = page.toObject();
  164. if (page.revisionHackmdSynced != null && page.revisionHackmdSynced._id != null) {
  165. returnObj.revisionHackmdSynced = page.revisionHackmdSynced._id;
  166. }
  167. if (page.lastUpdateUser != null && page.lastUpdateUser instanceof User) {
  168. returnObj.lastUpdateUser = page.lastUpdateUser.toObject();
  169. }
  170. if (page.creator != null && page.creator instanceof User) {
  171. returnObj.creator = page.creator.toObject();
  172. }
  173. return returnObj;
  174. }
  175. function getPathFromRequest(req) {
  176. return pathUtils.normalizePath(req.params[0] || '');
  177. }
  178. function isUserPage(path) {
  179. if (path.match(/^\/user\/[^/]+\/?$/)) {
  180. return true;
  181. }
  182. return false;
  183. }
  184. function generatePager(offset, limit, totalCount) {
  185. let prev = null;
  186. if (offset > 0) {
  187. prev = offset - limit;
  188. if (prev < 0) {
  189. prev = 0;
  190. }
  191. }
  192. let next = offset + limit;
  193. if (totalCount < next) {
  194. next = null;
  195. }
  196. return {
  197. prev,
  198. next,
  199. offset,
  200. };
  201. }
  202. // user notification
  203. // TODO create '/service/user-notification' module
  204. /**
  205. *
  206. * @param {Page} page
  207. * @param {User} user
  208. * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
  209. * @param {boolean} updateOrCreate
  210. * @param {string} previousRevision
  211. */
  212. async function notifyToSlackByUser(page, user, slackChannelsStr, updateOrCreate, previousRevision) {
  213. await page.updateSlackChannel(slackChannelsStr)
  214. .catch((err) => {
  215. logger.error('Error occured in updating slack channels: ', err);
  216. });
  217. if (slackNotificationService.hasSlackConfig()) {
  218. const slackChannels = slackChannelsStr != null ? slackChannelsStr.split(',') : [null];
  219. const promises = slackChannels.map((chan) => {
  220. return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
  221. });
  222. Promise.all(promises)
  223. .catch((err) => {
  224. logger.error('Error occured in sending slack notification: ', err);
  225. });
  226. }
  227. }
  228. function addRendarVarsForPage(renderVars, page) {
  229. renderVars.page = page;
  230. renderVars.revision = page.revision;
  231. renderVars.author = page.revision.author;
  232. renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
  233. renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
  234. renderVars.hasDraftOnHackmd = page.hasDraftOnHackmd;
  235. }
  236. async function addRenderVarsForUserPage(renderVars, page, requestUser) {
  237. const userData = await User.findUserByUsername(User.getUsernameByPath(page.path));
  238. if (userData != null) {
  239. renderVars.pageUser = userData;
  240. renderVars.bookmarkList = await Bookmark.findByUser(userData, { limit: 10, populatePage: true, requestUser });
  241. }
  242. }
  243. function addRendarVarsForScope(renderVars, page) {
  244. renderVars.grant = page.grant;
  245. renderVars.grantedGroupId = page.grantedGroup ? page.grantedGroup.id : null;
  246. renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
  247. }
  248. async function addRenderVarsForSlack(renderVars, page) {
  249. renderVars.slack = await getSlackChannels(page);
  250. }
  251. async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
  252. const SEENER_THRESHOLD = 10;
  253. const queryOptions = {
  254. offset,
  255. limit,
  256. includeTrashed: path.startsWith('/trash/'),
  257. isRegExpEscapedFromPath,
  258. };
  259. const result = await Page.findListWithDescendants(path, requestUser, queryOptions);
  260. if (result.pages.length > limit) {
  261. result.pages.pop();
  262. }
  263. renderVars.viewConfig = {
  264. seener_threshold: SEENER_THRESHOLD,
  265. };
  266. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  267. renderVars.pages = result.pages;
  268. }
  269. function replacePlaceholdersOfTemplate(template, req) {
  270. if (req.user == null) {
  271. return '';
  272. }
  273. const definitions = {
  274. pagepath: getPathFromRequest(req),
  275. username: req.user.name,
  276. today: getToday(),
  277. };
  278. const compiledTemplate = swig.compile(template);
  279. return compiledTemplate(definitions);
  280. }
  281. async function showPageForPresentation(req, res, next) {
  282. const path = getPathFromRequest(req);
  283. const revisionId = req.query.revision;
  284. let page = await Page.findByPathAndViewer(path, req.user);
  285. if (page == null) {
  286. next();
  287. }
  288. const renderVars = {};
  289. // populate
  290. page = await page.populateDataToMakePresentation(revisionId);
  291. addRendarVarsForPage(renderVars, page);
  292. return res.render('page_presentation', renderVars);
  293. }
  294. async function showTopPage(req, res, next) {
  295. const portalPath = req.path;
  296. const revisionId = req.query.revision;
  297. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  298. const view = `layout-${layoutName}/page_list`;
  299. const renderVars = { path: portalPath };
  300. let portalPage = await Page.findByPathAndViewer(portalPath, req.user);
  301. portalPage.initLatestRevisionField(revisionId);
  302. // populate
  303. portalPage = await portalPage.populateDataToShowRevision();
  304. addRendarVarsForPage(renderVars, portalPage);
  305. await addRenderVarsForSlack(renderVars, portalPage);
  306. const limit = 50;
  307. const offset = parseInt(req.query.offset) || 0;
  308. await addRenderVarsForDescendants(renderVars, portalPath, req.user, offset, limit);
  309. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  310. return res.render(view, renderVars);
  311. }
  312. async function showPageForGrowiBehavior(req, res, next) {
  313. const path = getPathFromRequest(req);
  314. const revisionId = req.query.revision;
  315. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  316. let page = await Page.findByPathAndViewer(path, req.user);
  317. if (page == null) {
  318. // check the page is forbidden or just does not exist.
  319. req.isForbidden = await Page.count({ path }) > 0;
  320. return next();
  321. }
  322. if (page.redirectTo) {
  323. debug(`Redirect to '${page.redirectTo}'`);
  324. return res.redirect(`${encodeURI(page.redirectTo)}?redirectFrom=${encodeURIComponent(path)}`);
  325. }
  326. logger.debug('Page is found when processing pageShowForGrowiBehavior', page._id, page.path);
  327. const limit = 50;
  328. const offset = parseInt(req.query.offset) || 0;
  329. const renderVars = {};
  330. let view = `layout-${layoutName}/page`;
  331. page.initLatestRevisionField(revisionId);
  332. // populate
  333. page = await page.populateDataToShowRevision();
  334. addRendarVarsForPage(renderVars, page);
  335. addRendarVarsForScope(renderVars, page);
  336. await addRenderVarsForSlack(renderVars, page);
  337. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  338. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
  339. renderVars.sharelinksNumber = sharelinksNumber;
  340. if (isUserPage(page.path)) {
  341. // change template
  342. view = `layout-${layoutName}/user_page`;
  343. await addRenderVarsForUserPage(renderVars, page, req.user);
  344. }
  345. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  346. return res.render(view, renderVars);
  347. }
  348. const getSlackChannels = async(page) => {
  349. if (page.extended.slack) {
  350. return page.extended.slack;
  351. }
  352. const data = await UpdatePost.findSettingsByPath(page.path);
  353. const channels = data.map((e) => { return e.channel }).join(', ');
  354. return channels;
  355. };
  356. actions.showTopPage = function(req, res) {
  357. return showTopPage(req, res);
  358. };
  359. /**
  360. * Redirect to the page without trailing slash
  361. */
  362. actions.showPageWithEndOfSlash = function(req, res, next) {
  363. return res.redirect(pathUtils.removeTrailingSlash(req.path));
  364. };
  365. /**
  366. * switch action
  367. * - presentation mode
  368. * - by behaviorType
  369. */
  370. actions.showPage = async function(req, res, next) {
  371. // presentation mode
  372. if (req.query.presentation) {
  373. return showPageForPresentation(req, res, next);
  374. }
  375. // delegate to showPageForGrowiBehavior
  376. return showPageForGrowiBehavior(req, res, next);
  377. };
  378. actions.showSharedPage = async function(req, res, next) {
  379. const { linkId } = req.params;
  380. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  381. const view = `layout-${layoutName}/shared_page`;
  382. const shareLink = await ShareLink.findOne({ _id: linkId }).populate('relatedPage');
  383. if (shareLink == null || shareLink.relatedPage == null) {
  384. // page or sharelink are not found
  385. return res.render(`layout-${layoutName}/not_found_shared_page`);
  386. }
  387. let page = shareLink.relatedPage;
  388. // check if share link is expired
  389. if (shareLink.isExpired()) {
  390. // page is not found
  391. return res.render(`layout-${layoutName}/expired_shared_page`);
  392. }
  393. const renderVars = {};
  394. renderVars.sharelink = shareLink;
  395. // populate
  396. page = await page.populateDataToShowRevision();
  397. addRendarVarsForPage(renderVars, page);
  398. addRendarVarsForScope(renderVars, page);
  399. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  400. return res.render(view, renderVars);
  401. };
  402. /**
  403. * switch action by behaviorType
  404. */
  405. /* eslint-disable no-else-return */
  406. actions.trashPageListShowWrapper = function(req, res) {
  407. // redirect to '/trash'
  408. return res.redirect('/trash');
  409. };
  410. /* eslint-enable no-else-return */
  411. /**
  412. * switch action by behaviorType
  413. */
  414. /* eslint-disable no-else-return */
  415. actions.trashPageShowWrapper = function(req, res) {
  416. // Crowi behavior for '/trash/*'
  417. return actions.deletedPageListShow(req, res);
  418. };
  419. /* eslint-enable no-else-return */
  420. /**
  421. * switch action by behaviorType
  422. */
  423. /* eslint-disable no-else-return */
  424. actions.deletedPageListShowWrapper = function(req, res) {
  425. const path = `/trash${getPathFromRequest(req)}`;
  426. return res.redirect(path);
  427. };
  428. /* eslint-enable no-else-return */
  429. actions.notFound = async function(req, res) {
  430. const path = getPathFromRequest(req);
  431. const isCreatable = Page.isCreatableName(path);
  432. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  433. let view;
  434. const renderVars = { path };
  435. if (!isCreatable) {
  436. view = `layout-${layoutName}/not_creatable`;
  437. }
  438. else if (req.isForbidden) {
  439. view = `layout-${layoutName}/forbidden`;
  440. }
  441. else {
  442. view = `layout-${layoutName}/not_found`;
  443. // retrieve templates
  444. if (req.user != null) {
  445. const template = await Page.findTemplate(path);
  446. if (template.templateBody) {
  447. const body = replacePlaceholdersOfTemplate(template.templateBody, req);
  448. const tags = template.templateTags;
  449. renderVars.template = body;
  450. renderVars.templateTags = tags;
  451. }
  452. }
  453. // add scope variables by ancestor page
  454. const ancestor = await Page.findAncestorByPathAndViewer(path, req.user);
  455. if (ancestor != null) {
  456. await ancestor.populate('grantedGroup').execPopulate();
  457. addRendarVarsForScope(renderVars, ancestor);
  458. }
  459. }
  460. const limit = 50;
  461. const offset = parseInt(req.query.offset) || 0;
  462. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  463. return res.render(view, renderVars);
  464. };
  465. actions.deletedPageListShow = async function(req, res) {
  466. // normalizePath makes '/trash/' -> '/trash'
  467. const path = pathUtils.normalizePath(`/trash${getPathFromRequest(req)}`);
  468. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  469. const limit = 50;
  470. const offset = parseInt(req.query.offset) || 0;
  471. const queryOptions = {
  472. offset,
  473. limit,
  474. includeTrashed: true,
  475. };
  476. const renderVars = {
  477. page: null,
  478. path,
  479. pages: [],
  480. };
  481. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  482. if (result.pages.length > limit) {
  483. result.pages.pop();
  484. }
  485. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  486. renderVars.pages = result.pages;
  487. res.render(`layout-${layoutName}/page_list`, renderVars);
  488. };
  489. /**
  490. * redirector
  491. */
  492. actions.redirector = async function(req, res) {
  493. const id = req.params.id;
  494. const page = await Page.findByIdAndViewer(id, req.user);
  495. if (page != null) {
  496. return res.redirect(encodeURI(page.path));
  497. }
  498. return res.redirect('/');
  499. };
  500. const api = {};
  501. actions.api = api;
  502. /**
  503. * @swagger
  504. *
  505. * /pages.list:
  506. * get:
  507. * tags: [Pages, CrowiCompatibles]
  508. * operationId: listPages
  509. * summary: /pages.list
  510. * description: Get list of pages
  511. * parameters:
  512. * - in: query
  513. * name: path
  514. * schema:
  515. * $ref: '#/components/schemas/Page/properties/path'
  516. * - in: query
  517. * name: user
  518. * schema:
  519. * $ref: '#/components/schemas/User/properties/username'
  520. * - in: query
  521. * name: limit
  522. * schema:
  523. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  524. * - in: query
  525. * name: offset
  526. * schema:
  527. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  528. * responses:
  529. * 200:
  530. * description: Succeeded to get list of pages.
  531. * content:
  532. * application/json:
  533. * schema:
  534. * properties:
  535. * ok:
  536. * $ref: '#/components/schemas/V1Response/properties/ok'
  537. * pages:
  538. * type: array
  539. * items:
  540. * $ref: '#/components/schemas/Page'
  541. * description: page list
  542. * 403:
  543. * $ref: '#/components/responses/403'
  544. * 500:
  545. * $ref: '#/components/responses/500'
  546. */
  547. /**
  548. * @api {get} /pages.list List pages by user
  549. * @apiName ListPage
  550. * @apiGroup Page
  551. *
  552. * @apiParam {String} path
  553. * @apiParam {String} user
  554. */
  555. api.list = async function(req, res) {
  556. const username = req.query.user || null;
  557. const path = req.query.path || null;
  558. const limit = +req.query.limit || 50;
  559. const offset = parseInt(req.query.offset) || 0;
  560. const queryOptions = { offset, limit: limit + 1 };
  561. // Accepts only one of these
  562. if (username === null && path === null) {
  563. return res.json(ApiResponse.error('Parameter user or path is required.'));
  564. }
  565. if (username !== null && path !== null) {
  566. return res.json(ApiResponse.error('Parameter user or path is required.'));
  567. }
  568. try {
  569. let result = null;
  570. if (path == null) {
  571. const user = await User.findUserByUsername(username);
  572. if (user === null) {
  573. throw new Error('The user not found.');
  574. }
  575. result = await Page.findListByCreator(user, req.user, queryOptions);
  576. }
  577. else {
  578. result = await Page.findListByStartWith(path, req.user, queryOptions);
  579. }
  580. if (result.pages.length > limit) {
  581. result.pages.pop();
  582. }
  583. return res.json(ApiResponse.success(result));
  584. }
  585. catch (err) {
  586. return res.json(ApiResponse.error(err));
  587. }
  588. };
  589. /**
  590. * @swagger
  591. *
  592. * /pages.create:
  593. * post:
  594. * tags: [Pages, CrowiCompatibles]
  595. * operationId: createPage
  596. * summary: /pages.create
  597. * description: Create page
  598. * requestBody:
  599. * content:
  600. * application/json:
  601. * schema:
  602. * properties:
  603. * body:
  604. * $ref: '#/components/schemas/Revision/properties/body'
  605. * path:
  606. * $ref: '#/components/schemas/Page/properties/path'
  607. * grant:
  608. * $ref: '#/components/schemas/Page/properties/grant'
  609. * required:
  610. * - body
  611. * - path
  612. * responses:
  613. * 200:
  614. * description: Succeeded to create page.
  615. * content:
  616. * application/json:
  617. * schema:
  618. * properties:
  619. * ok:
  620. * $ref: '#/components/schemas/V1Response/properties/ok'
  621. * page:
  622. * $ref: '#/components/schemas/Page'
  623. * 403:
  624. * $ref: '#/components/responses/403'
  625. * 500:
  626. * $ref: '#/components/responses/500'
  627. */
  628. /**
  629. * @api {post} /pages.create Create new page
  630. * @apiName CreatePage
  631. * @apiGroup Page
  632. *
  633. * @apiParam {String} body
  634. * @apiParam {String} path
  635. * @apiParam {String} grant
  636. * @apiParam {Array} pageTags
  637. */
  638. api.create = async function(req, res) {
  639. const body = req.body.body || null;
  640. let pagePath = req.body.path || null;
  641. const grant = req.body.grant || null;
  642. const grantUserGroupId = req.body.grantUserGroupId || null;
  643. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  644. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  645. const slackChannels = req.body.slackChannels || null;
  646. const socketClientId = req.body.socketClientId || undefined;
  647. const pageTags = req.body.pageTags || undefined;
  648. if (body === null || pagePath === null) {
  649. return res.json(ApiResponse.error('Parameters body and path are required.'));
  650. }
  651. // check whether path starts slash
  652. pagePath = pathUtils.addHeadingSlash(pagePath);
  653. // check page existence
  654. const isExist = await Page.count({ path: pagePath }) > 0;
  655. if (isExist) {
  656. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  657. }
  658. const options = { socketClientId };
  659. if (grant != null) {
  660. options.grant = grant;
  661. options.grantUserGroupId = grantUserGroupId;
  662. }
  663. const createdPage = await Page.create(pagePath, body, req.user, options);
  664. let savedTags;
  665. if (pageTags != null) {
  666. await PageTagRelation.updatePageTags(createdPage.id, pageTags);
  667. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  668. }
  669. const result = { page: serializeToObj(createdPage), tags: savedTags };
  670. res.json(ApiResponse.success(result));
  671. // update scopes for descendants
  672. if (overwriteScopesOfDescendants) {
  673. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  674. }
  675. // global notification
  676. try {
  677. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage, req.user);
  678. }
  679. catch (err) {
  680. logger.error('Create notification failed', err);
  681. }
  682. // user notification
  683. if (isSlackEnabled) {
  684. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  685. }
  686. };
  687. /**
  688. * @swagger
  689. *
  690. * /pages.update:
  691. * post:
  692. * tags: [Pages, CrowiCompatibles]
  693. * operationId: updatePage
  694. * summary: /pages.update
  695. * description: Update page
  696. * requestBody:
  697. * content:
  698. * application/json:
  699. * schema:
  700. * properties:
  701. * body:
  702. * $ref: '#/components/schemas/Revision/properties/body'
  703. * page_id:
  704. * $ref: '#/components/schemas/Page/properties/_id'
  705. * revision_id:
  706. * $ref: '#/components/schemas/Revision/properties/_id'
  707. * grant:
  708. * $ref: '#/components/schemas/Page/properties/grant'
  709. * required:
  710. * - body
  711. * - page_id
  712. * - revision_id
  713. * responses:
  714. * 200:
  715. * description: Succeeded to update page.
  716. * content:
  717. * application/json:
  718. * schema:
  719. * properties:
  720. * ok:
  721. * $ref: '#/components/schemas/V1Response/properties/ok'
  722. * page:
  723. * $ref: '#/components/schemas/Page'
  724. * 403:
  725. * $ref: '#/components/responses/403'
  726. * 500:
  727. * $ref: '#/components/responses/500'
  728. */
  729. /**
  730. * @api {post} /pages.update Update page
  731. * @apiName UpdatePage
  732. * @apiGroup Page
  733. *
  734. * @apiParam {String} body
  735. * @apiParam {String} page_id
  736. * @apiParam {String} revision_id
  737. * @apiParam {String} grant
  738. *
  739. * In the case of the page exists:
  740. * - If revision_id is specified => update the page,
  741. * - If revision_id is not specified => force update by the new contents.
  742. */
  743. api.update = async function(req, res) {
  744. const pageBody = req.body.body || null;
  745. const pageId = req.body.page_id || null;
  746. const revisionId = req.body.revision_id || null;
  747. const grant = req.body.grant || null;
  748. const grantUserGroupId = req.body.grantUserGroupId || null;
  749. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  750. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  751. const slackChannels = req.body.slackChannels || null;
  752. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  753. const socketClientId = req.body.socketClientId || undefined;
  754. const pageTags = req.body.pageTags || undefined;
  755. if (pageId === null || pageBody === null || revisionId === null) {
  756. return res.json(ApiResponse.error('page_id, body and revision_id are required.'));
  757. }
  758. // check page existence
  759. const isExist = await Page.count({ _id: pageId }) > 0;
  760. if (!isExist) {
  761. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  762. }
  763. // check revision
  764. let page = await Page.findByIdAndViewer(pageId, req.user);
  765. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  766. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  767. }
  768. const options = { isSyncRevisionToHackmd, socketClientId };
  769. if (grant != null) {
  770. options.grant = grant;
  771. options.grantUserGroupId = grantUserGroupId;
  772. }
  773. const Revision = crowi.model('Revision');
  774. const previousRevision = await Revision.findById(revisionId);
  775. try {
  776. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  777. }
  778. catch (err) {
  779. logger.error('error on _api/pages.update', err);
  780. return res.json(ApiResponse.error(err));
  781. }
  782. let savedTags;
  783. if (pageTags != null) {
  784. await PageTagRelation.updatePageTags(pageId, pageTags);
  785. savedTags = await PageTagRelation.listTagNamesByPage(pageId);
  786. }
  787. const result = { page: serializeToObj(page), tags: savedTags };
  788. res.json(ApiResponse.success(result));
  789. // update scopes for descendants
  790. if (overwriteScopesOfDescendants) {
  791. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  792. }
  793. // global notification
  794. try {
  795. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_EDIT, page, req.user);
  796. }
  797. catch (err) {
  798. logger.error('Edit notification failed', err);
  799. }
  800. // user notification
  801. if (isSlackEnabled) {
  802. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  803. }
  804. };
  805. /**
  806. * @swagger
  807. *
  808. * /pages.get:
  809. * get:
  810. * tags: [Pages, CrowiCompatibles]
  811. * operationId: getPage
  812. * summary: /pages.get
  813. * description: Get page data
  814. * parameters:
  815. * - in: query
  816. * name: page_id
  817. * schema:
  818. * $ref: '#/components/schemas/Page/properties/_id'
  819. * - in: query
  820. * name: path
  821. * schema:
  822. * $ref: '#/components/schemas/Page/properties/path'
  823. * - in: query
  824. * name: revision_id
  825. * schema:
  826. * $ref: '#/components/schemas/Revision/properties/_id'
  827. * responses:
  828. * 200:
  829. * description: Succeeded to get page data.
  830. * content:
  831. * application/json:
  832. * schema:
  833. * properties:
  834. * ok:
  835. * $ref: '#/components/schemas/V1Response/properties/ok'
  836. * page:
  837. * $ref: '#/components/schemas/Page'
  838. * 403:
  839. * $ref: '#/components/responses/403'
  840. * 500:
  841. * $ref: '#/components/responses/500'
  842. */
  843. /**
  844. * @api {get} /pages.get Get page data
  845. * @apiName GetPage
  846. * @apiGroup Page
  847. *
  848. * @apiParam {String} page_id
  849. * @apiParam {String} path
  850. * @apiParam {String} revision_id
  851. */
  852. api.get = async function(req, res) {
  853. const pagePath = req.query.path || null;
  854. const pageId = req.query.page_id || null; // TODO: handling
  855. if (!pageId && !pagePath) {
  856. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  857. }
  858. let page;
  859. try {
  860. if (pageId) { // prioritized
  861. page = await Page.findByIdAndViewer(pageId, req.user);
  862. }
  863. else if (pagePath) {
  864. page = await Page.findByPathAndViewer(pagePath, req.user);
  865. }
  866. if (page == null) {
  867. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  868. }
  869. page.initLatestRevisionField();
  870. // populate
  871. page = await page.populateDataToShowRevision();
  872. }
  873. catch (err) {
  874. return res.json(ApiResponse.error(err));
  875. }
  876. const result = {};
  877. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  878. return res.json(ApiResponse.success(result));
  879. };
  880. /**
  881. * @swagger
  882. *
  883. * /pages.exist:
  884. * get:
  885. * tags: [Pages]
  886. * operationId: getPageExistence
  887. * summary: /pages.exist
  888. * description: Get page existence
  889. * parameters:
  890. * - in: query
  891. * name: pagePaths
  892. * schema:
  893. * type: string
  894. * description: Page path list in JSON Array format
  895. * example: '["/", "/user/unknown"]'
  896. * responses:
  897. * 200:
  898. * description: Succeeded to get page existence.
  899. * content:
  900. * application/json:
  901. * schema:
  902. * properties:
  903. * ok:
  904. * $ref: '#/components/schemas/V1Response/properties/ok'
  905. * pages:
  906. * type: string
  907. * description: Properties of page path and existence
  908. * example: '{"/": true, "/user/unknown": false}'
  909. * 403:
  910. * $ref: '#/components/responses/403'
  911. * 500:
  912. * $ref: '#/components/responses/500'
  913. */
  914. /**
  915. * @api {get} /pages.exist Get if page exists
  916. * @apiName GetPage
  917. * @apiGroup Page
  918. *
  919. * @apiParam {String} pages (stringified JSON)
  920. */
  921. api.exist = async function(req, res) {
  922. const pagePaths = JSON.parse(req.query.pagePaths || '[]');
  923. const pages = {};
  924. await Promise.all(pagePaths.map(async(path) => {
  925. // check page existence
  926. const isExist = await Page.count({ path }) > 0;
  927. pages[path] = isExist;
  928. return;
  929. }));
  930. const result = { pages };
  931. return res.json(ApiResponse.success(result));
  932. };
  933. /**
  934. * @swagger
  935. *
  936. * /pages.getPageTag:
  937. * get:
  938. * tags: [Pages]
  939. * operationId: getPageTag
  940. * summary: /pages.getPageTag
  941. * description: Get page tag
  942. * parameters:
  943. * - in: query
  944. * name: pageId
  945. * schema:
  946. * $ref: '#/components/schemas/Page/properties/_id'
  947. * responses:
  948. * 200:
  949. * description: Succeeded to get page tags.
  950. * content:
  951. * application/json:
  952. * schema:
  953. * properties:
  954. * ok:
  955. * $ref: '#/components/schemas/V1Response/properties/ok'
  956. * tags:
  957. * $ref: '#/components/schemas/Tags'
  958. * 403:
  959. * $ref: '#/components/responses/403'
  960. * 500:
  961. * $ref: '#/components/responses/500'
  962. */
  963. /**
  964. * @api {get} /pages.getPageTag get page tags
  965. * @apiName GetPageTag
  966. * @apiGroup Page
  967. *
  968. * @apiParam {String} pageId
  969. */
  970. api.getPageTag = async function(req, res) {
  971. const result = {};
  972. try {
  973. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  974. }
  975. catch (err) {
  976. return res.json(ApiResponse.error(err));
  977. }
  978. return res.json(ApiResponse.success(result));
  979. };
  980. /**
  981. * @swagger
  982. *
  983. * /pages.seen:
  984. * post:
  985. * tags: [Pages, CrowiCompatibles]
  986. * operationId: seenPage
  987. * summary: /pages.seen
  988. * description: Mark as seen user
  989. * requestBody:
  990. * content:
  991. * application/json:
  992. * schema:
  993. * properties:
  994. * page_id:
  995. * $ref: '#/components/schemas/Page/properties/_id'
  996. * required:
  997. * - page_id
  998. * responses:
  999. * 200:
  1000. * description: Succeeded to be page seen.
  1001. * content:
  1002. * application/json:
  1003. * schema:
  1004. * properties:
  1005. * ok:
  1006. * $ref: '#/components/schemas/V1Response/properties/ok'
  1007. * seenUser:
  1008. * $ref: '#/components/schemas/Page/properties/seenUsers'
  1009. * 403:
  1010. * $ref: '#/components/responses/403'
  1011. * 500:
  1012. * $ref: '#/components/responses/500'
  1013. */
  1014. /**
  1015. * @api {post} /pages.seen Mark as seen user
  1016. * @apiName SeenPage
  1017. * @apiGroup Page
  1018. *
  1019. * @apiParam {String} page_id Page Id.
  1020. */
  1021. api.seen = async function(req, res) {
  1022. const user = req.user;
  1023. const pageId = req.body.page_id;
  1024. if (!pageId) {
  1025. return res.json(ApiResponse.error('page_id required'));
  1026. }
  1027. if (!req.user) {
  1028. return res.json(ApiResponse.error('user required'));
  1029. }
  1030. let page;
  1031. try {
  1032. page = await Page.findByIdAndViewer(pageId, user);
  1033. if (user != null) {
  1034. page = await page.seen(user);
  1035. }
  1036. }
  1037. catch (err) {
  1038. debug('Seen user update error', err);
  1039. return res.json(ApiResponse.error(err));
  1040. }
  1041. const result = {};
  1042. result.seenUser = page.seenUsers;
  1043. return res.json(ApiResponse.success(result));
  1044. };
  1045. /**
  1046. * @swagger
  1047. *
  1048. * /pages.updatePost:
  1049. * get:
  1050. * tags: [Pages, CrowiCompatibles]
  1051. * operationId: getUpdatePostPage
  1052. * summary: /pages.updatePost
  1053. * description: Get UpdatePost setting list
  1054. * parameters:
  1055. * - in: query
  1056. * name: path
  1057. * schema:
  1058. * $ref: '#/components/schemas/Page/properties/path'
  1059. * responses:
  1060. * 200:
  1061. * description: Succeeded to get UpdatePost setting list.
  1062. * content:
  1063. * application/json:
  1064. * schema:
  1065. * properties:
  1066. * ok:
  1067. * $ref: '#/components/schemas/V1Response/properties/ok'
  1068. * updatePost:
  1069. * $ref: '#/components/schemas/UpdatePost'
  1070. * 403:
  1071. * $ref: '#/components/responses/403'
  1072. * 500:
  1073. * $ref: '#/components/responses/500'
  1074. */
  1075. /**
  1076. * @api {get} /pages.updatePost
  1077. * @apiName Get UpdatePost setting list
  1078. * @apiGroup Page
  1079. *
  1080. * @apiParam {String} path
  1081. */
  1082. api.getUpdatePost = function(req, res) {
  1083. const path = req.query.path;
  1084. const UpdatePost = crowi.model('UpdatePost');
  1085. if (!path) {
  1086. return res.json(ApiResponse.error({}));
  1087. }
  1088. UpdatePost.findSettingsByPath(path)
  1089. .then((data) => {
  1090. // eslint-disable-next-line no-param-reassign
  1091. data = data.map((e) => {
  1092. return e.channel;
  1093. });
  1094. debug('Found updatePost data', data);
  1095. const result = { updatePost: data };
  1096. return res.json(ApiResponse.success(result));
  1097. })
  1098. .catch((err) => {
  1099. debug('Error occured while get setting', err);
  1100. return res.json(ApiResponse.error({}));
  1101. });
  1102. };
  1103. /**
  1104. * @api {post} /pages.remove Remove page
  1105. * @apiName RemovePage
  1106. * @apiGroup Page
  1107. *
  1108. * @apiParam {String} page_id Page Id.
  1109. * @apiParam {String} revision_id
  1110. */
  1111. api.remove = async function(req, res) {
  1112. const pageId = req.body.page_id;
  1113. const previousRevision = req.body.revision_id || null;
  1114. const socketClientId = req.body.socketClientId || undefined;
  1115. // get completely flag
  1116. const isCompletely = (req.body.completely != null);
  1117. // get recursively flag
  1118. const isRecursively = (req.body.recursively != null);
  1119. const options = { socketClientId };
  1120. let page = await Page.findByIdAndViewer(pageId, req.user);
  1121. if (page == null) {
  1122. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1123. }
  1124. debug('Delete page', page._id, page.path);
  1125. try {
  1126. if (isCompletely) {
  1127. if (!req.user.canDeleteCompletely(page.creator)) {
  1128. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  1129. }
  1130. if (isRecursively) {
  1131. await Page.completelyDeletePageRecursively(page.path, req.user, options);
  1132. }
  1133. else {
  1134. page = await Page.completelyDeletePage(page, req.user, options);
  1135. }
  1136. }
  1137. else {
  1138. if (!page.isUpdatable(previousRevision)) {
  1139. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1140. }
  1141. if (isRecursively) {
  1142. page = await Page.deletePageRecursively(page, req.user, options);
  1143. }
  1144. else {
  1145. page = await Page.deletePage(page, req.user, options);
  1146. }
  1147. }
  1148. }
  1149. catch (err) {
  1150. logger.error('Error occured while get setting', err);
  1151. return res.json(ApiResponse.error('Failed to delete page.', 'unknown'));
  1152. }
  1153. debug('Page deleted', page.path);
  1154. const result = {};
  1155. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1156. res.json(ApiResponse.success(result));
  1157. try {
  1158. // global notification
  1159. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page, req.user);
  1160. }
  1161. catch (err) {
  1162. logger.error('Delete notification failed', err);
  1163. }
  1164. };
  1165. /**
  1166. * @api {post} /pages.revertRemove Revert removed page
  1167. * @apiName RevertRemovePage
  1168. * @apiGroup Page
  1169. *
  1170. * @apiParam {String} page_id Page Id.
  1171. */
  1172. api.revertRemove = async function(req, res, options) {
  1173. const pageId = req.body.page_id;
  1174. const socketClientId = req.body.socketClientId || undefined;
  1175. // get recursively flag
  1176. const isRecursively = (req.body.recursively != null);
  1177. let page;
  1178. try {
  1179. page = await Page.findByIdAndViewer(pageId, req.user);
  1180. if (page == null) {
  1181. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  1182. }
  1183. if (isRecursively) {
  1184. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  1185. }
  1186. else {
  1187. page = await Page.revertDeletedPage(page, req.user, { socketClientId });
  1188. }
  1189. }
  1190. catch (err) {
  1191. logger.error('Error occured while get setting', err);
  1192. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  1193. }
  1194. const result = {};
  1195. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1196. return res.json(ApiResponse.success(result));
  1197. };
  1198. /**
  1199. * @swagger
  1200. *
  1201. * /pages.rename:
  1202. * post:
  1203. * tags: [Pages, CrowiCompatibles]
  1204. * operationId: renamePage
  1205. * summary: /pages.rename
  1206. * description: Rename page
  1207. * requestBody:
  1208. * content:
  1209. * application/json:
  1210. * schema:
  1211. * properties:
  1212. * page_id:
  1213. * $ref: '#/components/schemas/Page/properties/_id'
  1214. * path:
  1215. * $ref: '#/components/schemas/Page/properties/path'
  1216. * revision_id:
  1217. * $ref: '#/components/schemas/Revision/properties/_id'
  1218. * new_path:
  1219. * type: string
  1220. * description: new path
  1221. * example: /user/alice/new_test
  1222. * create_redirect:
  1223. * type: boolean
  1224. * description: whether redirect page
  1225. * required:
  1226. * - page_id
  1227. * responses:
  1228. * 200:
  1229. * description: Succeeded to rename page.
  1230. * content:
  1231. * application/json:
  1232. * schema:
  1233. * properties:
  1234. * ok:
  1235. * $ref: '#/components/schemas/V1Response/properties/ok'
  1236. * page:
  1237. * $ref: '#/components/schemas/Page'
  1238. * 403:
  1239. * $ref: '#/components/responses/403'
  1240. * 500:
  1241. * $ref: '#/components/responses/500'
  1242. */
  1243. /**
  1244. * @api {post} /pages.rename Rename page
  1245. * @apiName RenamePage
  1246. * @apiGroup Page
  1247. *
  1248. * @apiParam {String} page_id Page Id.
  1249. * @apiParam {String} path
  1250. * @apiParam {String} revision_id
  1251. * @apiParam {String} new_path New path name.
  1252. * @apiParam {Bool} create_redirect
  1253. */
  1254. api.rename = async function(req, res) {
  1255. const pageId = req.body.page_id;
  1256. const previousRevision = req.body.revision_id || null;
  1257. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1258. const options = {
  1259. createRedirectPage: (req.body.create_redirect != null),
  1260. updateMetadata: (req.body.remain_metadata == null),
  1261. socketClientId: +req.body.socketClientId || undefined,
  1262. };
  1263. const isRecursively = (req.body.recursively != null);
  1264. if (!Page.isCreatableName(newPagePath)) {
  1265. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  1266. }
  1267. // check whether path starts slash
  1268. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1269. const isExist = await Page.count({ path: newPagePath }) > 0;
  1270. if (isExist) {
  1271. // if page found, cannot cannot rename to that path
  1272. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  1273. }
  1274. let page;
  1275. try {
  1276. page = await Page.findByIdAndViewer(pageId, req.user);
  1277. if (page == null) {
  1278. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1279. }
  1280. if (!page.isUpdatable(previousRevision)) {
  1281. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1282. }
  1283. if (isRecursively) {
  1284. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  1285. }
  1286. else {
  1287. page = await Page.rename(page, newPagePath, req.user, options);
  1288. }
  1289. }
  1290. catch (err) {
  1291. logger.error(err);
  1292. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  1293. }
  1294. const result = {};
  1295. result.page = page; // TODO consider to use serializeToObj method -- 2018.08.06 Yuki Takei
  1296. res.json(ApiResponse.success(result));
  1297. try {
  1298. // global notification
  1299. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_MOVE, page, req.user, {
  1300. oldPath: req.body.path,
  1301. });
  1302. }
  1303. catch (err) {
  1304. logger.error('Move notification failed', err);
  1305. }
  1306. return page;
  1307. };
  1308. /**
  1309. * @swagger
  1310. *
  1311. * /pages.duplicate:
  1312. * post:
  1313. * tags: [Pages]
  1314. * operationId: duplicatePage
  1315. * summary: /pages.duplicate
  1316. * description: Duplicate page
  1317. * requestBody:
  1318. * content:
  1319. * application/json:
  1320. * schema:
  1321. * properties:
  1322. * page_id:
  1323. * $ref: '#/components/schemas/Page/properties/_id'
  1324. * new_path:
  1325. * $ref: '#/components/schemas/Page/properties/path'
  1326. * required:
  1327. * - page_id
  1328. * responses:
  1329. * 200:
  1330. * description: Succeeded to duplicate page.
  1331. * content:
  1332. * application/json:
  1333. * schema:
  1334. * properties:
  1335. * ok:
  1336. * $ref: '#/components/schemas/V1Response/properties/ok'
  1337. * page:
  1338. * $ref: '#/components/schemas/Page'
  1339. * tags:
  1340. * $ref: '#/components/schemas/Tags'
  1341. * 403:
  1342. * $ref: '#/components/responses/403'
  1343. * 500:
  1344. * $ref: '#/components/responses/500'
  1345. */
  1346. /**
  1347. * @api {post} /pages.duplicate Duplicate page
  1348. * @apiName DuplicatePage
  1349. * @apiGroup Page
  1350. *
  1351. * @apiParam {String} page_id Page Id.
  1352. * @apiParam {String} new_path New path name.
  1353. */
  1354. api.duplicate = async function(req, res) {
  1355. const pageId = req.body.page_id;
  1356. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1357. const page = await Page.findByIdAndViewer(pageId, req.user);
  1358. if (page == null) {
  1359. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1360. }
  1361. // check whether path starts slash
  1362. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1363. await page.populateDataToShowRevision();
  1364. const originTags = await page.findRelatedTagsById();
  1365. req.body.path = newPagePath;
  1366. req.body.body = page.revision.body;
  1367. req.body.grant = page.grant;
  1368. req.body.grantedUsers = page.grantedUsers;
  1369. req.body.grantUserGroupId = page.grantedGroup;
  1370. req.body.pageTags = originTags;
  1371. return api.create(req, res);
  1372. };
  1373. /**
  1374. * @api {post} /pages.unlink Remove the redirecting page
  1375. * @apiName UnlinkPage
  1376. * @apiGroup Page
  1377. *
  1378. * @apiParam {String} page_id Page Id.
  1379. * @apiParam {String} revision_id
  1380. */
  1381. api.unlink = async function(req, res) {
  1382. const path = req.body.path;
  1383. try {
  1384. await Page.removeRedirectOriginPageByPath(path);
  1385. logger.debug('Redirect Page deleted', path);
  1386. }
  1387. catch (err) {
  1388. logger.error('Error occured while get setting', err);
  1389. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1390. }
  1391. const result = { path };
  1392. return res.json(ApiResponse.success(result));
  1393. };
  1394. /**
  1395. * @swagger
  1396. *
  1397. * /pages.recentCreated:
  1398. * get:
  1399. * tags: [Pages]
  1400. * operationId: getRecentCreatedPages
  1401. * summary: /pages.recentCreated
  1402. * description: Get recent created page list
  1403. * parameters:
  1404. * - in: query
  1405. * name: page_id
  1406. * required: true
  1407. * schema:
  1408. * $ref: '#/components/schemas/Page/properties/_id'
  1409. * - in: query
  1410. * name: offset
  1411. * schema:
  1412. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  1413. * - in: query
  1414. * name: limit
  1415. * schema:
  1416. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  1417. * responses:
  1418. * 200:
  1419. * description: Succeeded to get recent created page list.
  1420. * content:
  1421. * application/json:
  1422. * schema:
  1423. * properties:
  1424. * ok:
  1425. * $ref: '#/components/schemas/V1Response/properties/ok'
  1426. * pages:
  1427. * type: array
  1428. * description: recent created page list
  1429. * items:
  1430. * $ref: '#/components/schemas/Page'
  1431. * totalCount:
  1432. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/total'
  1433. * offset:
  1434. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  1435. * limit:
  1436. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  1437. * 403:
  1438. * $ref: '#/components/responses/403'
  1439. * 500:
  1440. * $ref: '#/components/responses/500'
  1441. */
  1442. api.recentCreated = async function(req, res) {
  1443. const pageId = req.query.page_id;
  1444. if (pageId == null) {
  1445. return res.json(ApiResponse.error('param \'pageId\' must not be null'));
  1446. }
  1447. const page = await Page.findById(pageId);
  1448. if (page == null) {
  1449. return res.json(ApiResponse.error(`Page (id='${pageId}') does not exist`));
  1450. }
  1451. if (!isUserPage(page.path)) {
  1452. return res.json(ApiResponse.error(`Page (id='${pageId}') is not a user home`));
  1453. }
  1454. const limit = +req.query.limit || 50;
  1455. const offset = +req.query.offset || 0;
  1456. const queryOptions = { offset, limit };
  1457. try {
  1458. const result = await Page.findListByCreator(page.creator, req.user, queryOptions);
  1459. return res.json(ApiResponse.success(result));
  1460. }
  1461. catch (err) {
  1462. return res.json(ApiResponse.error(err));
  1463. }
  1464. };
  1465. return actions;
  1466. };