page.js 56 KB

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