page.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. import { pagePathUtils } from '@growi/core';
  2. import loggerFactory from '~/utils/logger';
  3. import { generateGrantCondition } from '~/server/models/page';
  4. const mongoose = require('mongoose');
  5. const escapeStringRegexp = require('escape-string-regexp');
  6. const streamToPromise = require('stream-to-promise');
  7. const pathlib = require('path');
  8. const logger = loggerFactory('growi:services:page');
  9. const debug = require('debug')('growi:services:page');
  10. const { Writable } = require('stream');
  11. const { createBatchStream } = require('~/server/util/batch-stream');
  12. const { isCreatablePage, isDeletablePage, isTrashPage } = pagePathUtils;
  13. const { serializePageSecurely } = require('../models/serializers/page-serializer');
  14. const BULK_REINDEX_SIZE = 100;
  15. class PageService {
  16. constructor(crowi) {
  17. this.crowi = crowi;
  18. this.pageEvent = crowi.event('page');
  19. // init
  20. this.pageEvent.on('create', this.pageEvent.onCreate);
  21. this.pageEvent.on('update', this.pageEvent.onUpdate);
  22. this.pageEvent.on('createMany', this.pageEvent.onCreateMany);
  23. this.pageEvent.on('addSeenUsers', this.pageEvent.onAddSeenUsers);
  24. }
  25. async findPageAndMetaDataByViewer({ pageId, path, user }) {
  26. const Page = this.crowi.model('Page');
  27. let page;
  28. if (pageId != null) { // prioritized
  29. page = await Page.findByIdAndViewer(pageId, user);
  30. }
  31. else {
  32. page = await Page.findByPathAndViewer(path, user);
  33. }
  34. const result = {};
  35. if (page == null) {
  36. const isExist = await Page.count({ $or: [{ _id: pageId }, { path }] }) > 0;
  37. result.isForbidden = isExist;
  38. result.isNotFound = !isExist;
  39. result.isCreatable = isCreatablePage(path);
  40. result.isDeletable = false;
  41. result.canDeleteCompletely = false;
  42. result.page = page;
  43. return result;
  44. }
  45. result.page = page;
  46. result.isForbidden = false;
  47. result.isNotFound = false;
  48. result.isCreatable = false;
  49. result.isDeletable = isDeletablePage(path);
  50. result.isDeleted = page.isDeleted();
  51. result.canDeleteCompletely = user != null && user.canDeleteCompletely(page.creator);
  52. return result;
  53. }
  54. /**
  55. * go back by using redirectTo and return the paths
  56. * ex: when
  57. * '/page1' redirects to '/page2' and
  58. * '/page2' redirects to '/page3'
  59. * and given '/page3',
  60. * '/page1' and '/page2' will be return
  61. *
  62. * @param {string} redirectTo
  63. * @param {object} redirectToPagePathMapping
  64. * @param {array} pagePaths
  65. */
  66. prepareShoudDeletePagesByRedirectTo(redirectTo, redirectToPagePathMapping, pagePaths = []) {
  67. const pagePath = redirectToPagePathMapping[redirectTo];
  68. if (pagePath == null) {
  69. return pagePaths;
  70. }
  71. pagePaths.push(pagePath);
  72. return this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping, pagePaths);
  73. }
  74. /**
  75. * Generate read stream to operate descendants of the specified page path
  76. * @param {string} targetPagePath
  77. * @param {User} viewer
  78. */
  79. async generateReadStreamToOperateOnlyDescendants(targetPagePath, userToOperate) {
  80. const Page = this.crowi.model('Page');
  81. const { PageQueryBuilder } = Page;
  82. const builder = new PageQueryBuilder(Page.find())
  83. .addConditionToExcludeRedirect()
  84. .addConditionToListOnlyDescendants(targetPagePath);
  85. await Page.addConditionToFilteringByViewerToEdit(builder, userToOperate);
  86. return builder
  87. .query
  88. .lean()
  89. .cursor({ batchSize: BULK_REINDEX_SIZE });
  90. }
  91. async renamePage(page, newPagePath, user, options, isRecursively = false) {
  92. const Page = this.crowi.model('Page');
  93. const Revision = this.crowi.model('Revision');
  94. const path = page.path;
  95. const createRedirectPage = options.createRedirectPage || false;
  96. const updateMetadata = options.updateMetadata || false;
  97. // sanitize path
  98. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  99. // create descendants first
  100. if (isRecursively) {
  101. await this.renameDescendantsWithStream(page, newPagePath, user, options);
  102. }
  103. const update = {};
  104. // update Page
  105. update.path = newPagePath;
  106. if (updateMetadata) {
  107. update.lastUpdateUser = user;
  108. update.updatedAt = Date.now();
  109. }
  110. const renamedPage = await Page.findByIdAndUpdate(page._id, { $set: update }, { new: true });
  111. // update Rivisions
  112. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  113. if (createRedirectPage) {
  114. const body = `redirect ${newPagePath}`;
  115. await Page.create(path, body, user, { redirectTo: newPagePath });
  116. }
  117. this.pageEvent.emit('delete', page, user);
  118. this.pageEvent.emit('create', renamedPage, user);
  119. return renamedPage;
  120. }
  121. async renameDescendants(pages, user, options, oldPagePathPrefix, newPagePathPrefix) {
  122. const Page = this.crowi.model('Page');
  123. const pageCollection = mongoose.connection.collection('pages');
  124. const revisionCollection = mongoose.connection.collection('revisions');
  125. const { updateMetadata, createRedirectPage } = options;
  126. const unorderedBulkOp = pageCollection.initializeUnorderedBulkOp();
  127. const createRediectPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  128. const revisionUnorderedBulkOp = revisionCollection.initializeUnorderedBulkOp();
  129. const createRediectRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  130. pages.forEach((page) => {
  131. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  132. const revisionId = new mongoose.Types.ObjectId();
  133. if (updateMetadata) {
  134. unorderedBulkOp
  135. .find({ _id: page._id })
  136. .update({ $set: { path: newPagePath, lastUpdateUser: user._id, updatedAt: new Date() } });
  137. }
  138. else {
  139. unorderedBulkOp.find({ _id: page._id }).update({ $set: { path: newPagePath } });
  140. }
  141. if (createRedirectPage) {
  142. createRediectPageBulkOp.insert({
  143. path: page.path, revision: revisionId, creator: user._id, lastUpdateUser: user._id, status: Page.STATUS_PUBLISHED, redirectTo: newPagePath,
  144. });
  145. createRediectRevisionBulkOp.insert({
  146. _id: revisionId, path: page.path, body: `redirect ${newPagePath}`, author: user._id, format: 'markdown',
  147. });
  148. }
  149. revisionUnorderedBulkOp.find({ path: page.path }).update({ $set: { path: newPagePath } }, { multi: true });
  150. });
  151. try {
  152. await unorderedBulkOp.execute();
  153. await revisionUnorderedBulkOp.execute();
  154. // Execute after unorderedBulkOp to prevent duplication
  155. if (createRedirectPage) {
  156. await createRediectPageBulkOp.execute();
  157. await createRediectRevisionBulkOp.execute();
  158. }
  159. }
  160. catch (err) {
  161. if (err.code !== 11000) {
  162. throw new Error('Failed to rename pages: ', err);
  163. }
  164. }
  165. this.pageEvent.emit('updateMany', pages, user);
  166. }
  167. /**
  168. * Create rename stream
  169. */
  170. async renameDescendantsWithStream(targetPage, newPagePath, user, options = {}) {
  171. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  172. const newPagePathPrefix = newPagePath;
  173. const pathRegExp = new RegExp(`^${escapeStringRegexp(targetPage.path)}`, 'i');
  174. const renameDescendants = this.renameDescendants.bind(this);
  175. const pageEvent = this.pageEvent;
  176. let count = 0;
  177. const writeStream = new Writable({
  178. objectMode: true,
  179. async write(batch, encoding, callback) {
  180. try {
  181. count += batch.length;
  182. await renameDescendants(batch, user, options, pathRegExp, newPagePathPrefix);
  183. logger.debug(`Reverting pages progressing: (count=${count})`);
  184. }
  185. catch (err) {
  186. logger.error('revertPages error on add anyway: ', err);
  187. }
  188. callback();
  189. },
  190. final(callback) {
  191. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  192. // update path
  193. targetPage.path = newPagePath;
  194. pageEvent.emit('syncDescendants', targetPage, user);
  195. callback();
  196. },
  197. });
  198. readStream
  199. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  200. .pipe(writeStream);
  201. await streamToPromise(readStream);
  202. }
  203. async deleteCompletelyOperation(pageIds, pagePaths) {
  204. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  205. const Bookmark = this.crowi.model('Bookmark');
  206. const Comment = this.crowi.model('Comment');
  207. const Page = this.crowi.model('Page');
  208. const PageTagRelation = this.crowi.model('PageTagRelation');
  209. const ShareLink = this.crowi.model('ShareLink');
  210. const Revision = this.crowi.model('Revision');
  211. const Attachment = this.crowi.model('Attachment');
  212. const { attachmentService } = this.crowi;
  213. const attachments = await Attachment.find({ page: { $in: pageIds } });
  214. const pages = await Page.find({ redirectTo: { $ne: null } });
  215. const redirectToPagePathMapping = {};
  216. pages.forEach((page) => {
  217. redirectToPagePathMapping[page.redirectTo] = page.path;
  218. });
  219. const redirectedFromPagePaths = [];
  220. pagePaths.forEach((pagePath) => {
  221. redirectedFromPagePaths.push(...this.prepareShoudDeletePagesByRedirectTo(pagePath, redirectToPagePathMapping));
  222. });
  223. return Promise.all([
  224. Bookmark.deleteMany({ page: { $in: pageIds } }),
  225. Comment.deleteMany({ page: { $in: pageIds } }),
  226. PageTagRelation.deleteMany({ relatedPage: { $in: pageIds } }),
  227. ShareLink.deleteMany({ relatedPage: { $in: pageIds } }),
  228. Revision.deleteMany({ path: { $in: pagePaths } }),
  229. Page.deleteMany({ $or: [{ path: { $in: pagePaths } }, { path: { $in: redirectedFromPagePaths } }, { _id: { $in: pageIds } }] }),
  230. attachmentService.removeAllAttachments(attachments),
  231. ]);
  232. }
  233. async duplicate(page, newPagePath, user, isRecursively) {
  234. const Page = this.crowi.model('Page');
  235. const PageTagRelation = mongoose.model('PageTagRelation');
  236. // populate
  237. await page.populate({ path: 'revision', model: 'Revision', select: 'body' });
  238. // create option
  239. const options = { page };
  240. options.grant = page.grant;
  241. options.grantUserGroupId = page.grantedGroup;
  242. options.grantedUsers = page.grantedUsers;
  243. newPagePath = this.crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  244. const createdPage = await Page.create(
  245. newPagePath, page.revision.body, user, options,
  246. );
  247. if (isRecursively) {
  248. this.duplicateDescendantsWithStream(page, newPagePath, user);
  249. }
  250. // take over tags
  251. const originTags = await page.findRelatedTagsById();
  252. let savedTags = [];
  253. if (originTags != null) {
  254. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  255. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  256. }
  257. const result = serializePageSecurely(createdPage);
  258. result.tags = savedTags;
  259. return result;
  260. }
  261. /**
  262. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  263. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  264. */
  265. async duplicateTags(pageIdMapping) {
  266. const PageTagRelation = mongoose.model('PageTagRelation');
  267. // convert pageId from string to ObjectId
  268. const pageIds = Object.keys(pageIdMapping);
  269. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: mongoose.Types.ObjectId(pageId) } }) };
  270. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  271. {
  272. $match: stage,
  273. },
  274. {
  275. $group: {
  276. _id: '$relatedTag',
  277. relatedPages: { $push: '$relatedPage' },
  278. },
  279. },
  280. ]);
  281. const newPageTagRelation = [];
  282. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  283. // relatedPages
  284. relatedPages.forEach((pageId) => {
  285. newPageTagRelation.push({
  286. relatedPage: pageIdMapping[pageId], // newPageId
  287. relatedTag: _id,
  288. });
  289. });
  290. });
  291. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  292. }
  293. async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix) {
  294. const Page = this.crowi.model('Page');
  295. const Revision = this.crowi.model('Revision');
  296. const paths = pages.map(page => (page.path));
  297. const revisions = await Revision.find({ path: { $in: paths } });
  298. // Mapping to set to the body of the new revision
  299. const pathRevisionMapping = {};
  300. revisions.forEach((revision) => {
  301. pathRevisionMapping[revision.path] = revision;
  302. });
  303. // key: oldPageId, value: newPageId
  304. const pageIdMapping = {};
  305. const newPages = [];
  306. const newRevisions = [];
  307. pages.forEach((page) => {
  308. const newPageId = new mongoose.Types.ObjectId();
  309. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  310. const revisionId = new mongoose.Types.ObjectId();
  311. pageIdMapping[page._id] = newPageId;
  312. newPages.push({
  313. _id: newPageId,
  314. path: newPagePath,
  315. creator: user._id,
  316. grant: page.grant,
  317. grantedGroup: page.grantedGroup,
  318. grantedUsers: page.grantedUsers,
  319. lastUpdateUser: user._id,
  320. redirectTo: null,
  321. revision: revisionId,
  322. });
  323. newRevisions.push({
  324. _id: revisionId, path: newPagePath, body: pathRevisionMapping[page.path].body, author: user._id, format: 'markdown',
  325. });
  326. });
  327. await Page.insertMany(newPages, { ordered: false });
  328. await Revision.insertMany(newRevisions, { ordered: false });
  329. await this.duplicateTags(pageIdMapping);
  330. }
  331. async duplicateDescendantsWithStream(page, newPagePath, user) {
  332. const readStream = await this.generateReadStreamToOperateOnlyDescendants(page.path, user);
  333. const newPagePathPrefix = newPagePath;
  334. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  335. const duplicateDescendants = this.duplicateDescendants.bind(this);
  336. const pageEvent = this.pageEvent;
  337. let count = 0;
  338. const writeStream = new Writable({
  339. objectMode: true,
  340. async write(batch, encoding, callback) {
  341. try {
  342. count += batch.length;
  343. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix);
  344. logger.debug(`Adding pages progressing: (count=${count})`);
  345. }
  346. catch (err) {
  347. logger.error('addAllPages error on add anyway: ', err);
  348. }
  349. callback();
  350. },
  351. final(callback) {
  352. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  353. // update path
  354. page.path = newPagePath;
  355. pageEvent.emit('syncDescendants', page, user);
  356. callback();
  357. },
  358. });
  359. readStream
  360. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  361. .pipe(writeStream);
  362. }
  363. async deletePage(page, user, options = {}, isRecursively = false) {
  364. const Page = this.crowi.model('Page');
  365. const Revision = this.crowi.model('Revision');
  366. const newPath = Page.getDeletedPageName(page.path);
  367. const isTrashed = isTrashPage(page.path);
  368. if (isTrashed) {
  369. throw new Error('This method does NOT support deleting trashed pages.');
  370. }
  371. if (!Page.isDeletableName(page.path)) {
  372. throw new Error('Page is not deletable.');
  373. }
  374. if (isRecursively) {
  375. this.deleteDescendantsWithStream(page, user, options);
  376. }
  377. // update Rivisions
  378. await Revision.updateRevisionListByPath(page.path, { path: newPath }, {});
  379. const deletedPage = await Page.findByIdAndUpdate(page._id, {
  380. $set: {
  381. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  382. },
  383. }, { new: true });
  384. const body = `redirect ${newPath}`;
  385. await Page.create(page.path, body, user, { redirectTo: newPath });
  386. this.pageEvent.emit('delete', page, user);
  387. this.pageEvent.emit('create', deletedPage, user);
  388. return deletedPage;
  389. }
  390. async deleteDescendants(pages, user) {
  391. const Page = this.crowi.model('Page');
  392. const pageCollection = mongoose.connection.collection('pages');
  393. const revisionCollection = mongoose.connection.collection('revisions');
  394. const deletePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  395. const updateRevisionListOp = revisionCollection.initializeUnorderedBulkOp();
  396. const createRediectRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  397. const newPagesForRedirect = [];
  398. pages.forEach((page) => {
  399. const newPath = Page.getDeletedPageName(page.path);
  400. const revisionId = new mongoose.Types.ObjectId();
  401. const body = `redirect ${newPath}`;
  402. deletePageBulkOp.find({ _id: page._id }).update({
  403. $set: {
  404. path: newPath, status: Page.STATUS_DELETED, deleteUser: user._id, deletedAt: Date.now(),
  405. },
  406. });
  407. updateRevisionListOp.find({ path: page.path }).update({ $set: { path: newPath } });
  408. createRediectRevisionBulkOp.insert({
  409. _id: revisionId, path: page.path, body, author: user._id, format: 'markdown',
  410. });
  411. newPagesForRedirect.push({
  412. path: page.path,
  413. creator: user._id,
  414. grant: page.grant,
  415. grantedGroup: page.grantedGroup,
  416. grantedUsers: page.grantedUsers,
  417. lastUpdateUser: user._id,
  418. redirectTo: newPath,
  419. revision: revisionId,
  420. });
  421. });
  422. try {
  423. await deletePageBulkOp.execute();
  424. await updateRevisionListOp.execute();
  425. await createRediectRevisionBulkOp.execute();
  426. await Page.insertMany(newPagesForRedirect, { ordered: false });
  427. }
  428. catch (err) {
  429. if (err.code !== 11000) {
  430. throw new Error('Failed to revert pages: ', err);
  431. }
  432. }
  433. }
  434. /**
  435. * Create delete stream
  436. */
  437. async deleteDescendantsWithStream(targetPage, user, options = {}) {
  438. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  439. const deleteDescendants = this.deleteDescendants.bind(this);
  440. let count = 0;
  441. const writeStream = new Writable({
  442. objectMode: true,
  443. async write(batch, encoding, callback) {
  444. try {
  445. count += batch.length;
  446. deleteDescendants(batch, user);
  447. logger.debug(`Reverting pages progressing: (count=${count})`);
  448. }
  449. catch (err) {
  450. logger.error('revertPages error on add anyway: ', err);
  451. }
  452. callback();
  453. },
  454. final(callback) {
  455. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  456. callback();
  457. },
  458. });
  459. readStream
  460. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  461. .pipe(writeStream);
  462. }
  463. // delete multiple pages
  464. async deleteMultipleCompletely(pages, user, options = {}) {
  465. const ids = pages.map(page => (page._id));
  466. const paths = pages.map(page => (page.path));
  467. logger.debug('Deleting completely', paths);
  468. await this.deleteCompletelyOperation(ids, paths);
  469. this.pageEvent.emit('deleteCompletely', pages, user); // update as renamed page
  470. return;
  471. }
  472. async deleteCompletely(page, user, options = {}, isRecursively = false) {
  473. const ids = [page._id];
  474. const paths = [page.path];
  475. logger.debug('Deleting completely', paths);
  476. await this.deleteCompletelyOperation(ids, paths);
  477. if (isRecursively) {
  478. this.deleteCompletelyDescendantsWithStream(page, user, options);
  479. }
  480. this.pageEvent.emit('delete', page, user); // update as renamed page
  481. return;
  482. }
  483. /**
  484. * Create delete completely stream
  485. */
  486. async deleteCompletelyDescendantsWithStream(targetPage, user, options = {}) {
  487. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  488. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  489. let count = 0;
  490. const writeStream = new Writable({
  491. objectMode: true,
  492. async write(batch, encoding, callback) {
  493. try {
  494. count += batch.length;
  495. await deleteMultipleCompletely(batch, user, options);
  496. logger.debug(`Adding pages progressing: (count=${count})`);
  497. }
  498. catch (err) {
  499. logger.error('addAllPages error on add anyway: ', err);
  500. }
  501. callback();
  502. },
  503. final(callback) {
  504. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  505. callback();
  506. },
  507. });
  508. readStream
  509. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  510. .pipe(writeStream);
  511. }
  512. async revertDeletedDescendants(pages, user) {
  513. const Page = this.crowi.model('Page');
  514. const pageCollection = mongoose.connection.collection('pages');
  515. const revisionCollection = mongoose.connection.collection('revisions');
  516. const removePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  517. const revertPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  518. const revertRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  519. // e.g. key: '/test'
  520. const pathToPageMapping = {};
  521. const toPaths = pages.map(page => Page.getRevertDeletedPageName(page.path));
  522. const toPages = await Page.find({ path: { $in: toPaths } });
  523. toPages.forEach((toPage) => {
  524. pathToPageMapping[toPage.path] = toPage;
  525. });
  526. pages.forEach((page) => {
  527. // e.g. page.path = /trash/test, toPath = /test
  528. const toPath = Page.getRevertDeletedPageName(page.path);
  529. if (pathToPageMapping[toPath] != null) {
  530. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  531. // So, it's ok to delete the page
  532. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  533. if (pathToPageMapping[toPath].redirectTo === page.path) {
  534. removePageBulkOp.find({ path: toPath }).delete();
  535. }
  536. }
  537. revertPageBulkOp.find({ _id: page._id }).update({
  538. $set: {
  539. path: toPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  540. },
  541. });
  542. revertRevisionBulkOp.find({ path: page.path }).update({ $set: { path: toPath } }, { multi: true });
  543. });
  544. try {
  545. await removePageBulkOp.execute();
  546. await revertPageBulkOp.execute();
  547. await revertRevisionBulkOp.execute();
  548. }
  549. catch (err) {
  550. if (err.code !== 11000) {
  551. throw new Error('Failed to revert pages: ', err);
  552. }
  553. }
  554. }
  555. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  556. const Page = this.crowi.model('Page');
  557. const Revision = this.crowi.model('Revision');
  558. const newPath = Page.getRevertDeletedPageName(page.path);
  559. const originPage = await Page.findByPath(newPath);
  560. if (originPage != null) {
  561. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  562. // So, it's ok to delete the page
  563. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  564. if (originPage.redirectTo !== page.path) {
  565. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  566. }
  567. await this.deleteCompletely(originPage, options);
  568. }
  569. if (isRecursively) {
  570. this.revertDeletedDescendantsWithStream(page, user, options);
  571. }
  572. page.status = Page.STATUS_PUBLISHED;
  573. page.lastUpdateUser = user;
  574. debug('Revert deleted the page', page, newPath);
  575. const updatedPage = await Page.findByIdAndUpdate(page._id, {
  576. $set: {
  577. path: newPath, status: Page.STATUS_PUBLISHED, lastUpdateUser: user._id, deleteUser: null, deletedAt: null,
  578. },
  579. }, { new: true });
  580. await Revision.updateMany({ path: page.path }, { $set: { path: newPath } });
  581. return updatedPage;
  582. }
  583. /**
  584. * Create revert stream
  585. */
  586. async revertDeletedDescendantsWithStream(targetPage, user, options = {}) {
  587. const readStream = await this.generateReadStreamToOperateOnlyDescendants(targetPage.path, user);
  588. const revertDeletedDescendants = this.revertDeletedDescendants.bind(this);
  589. let count = 0;
  590. const writeStream = new Writable({
  591. objectMode: true,
  592. async write(batch, encoding, callback) {
  593. try {
  594. count += batch.length;
  595. revertDeletedDescendants(batch, user);
  596. logger.debug(`Reverting pages progressing: (count=${count})`);
  597. }
  598. catch (err) {
  599. logger.error('revertPages error on add anyway: ', err);
  600. }
  601. callback();
  602. },
  603. final(callback) {
  604. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  605. callback();
  606. },
  607. });
  608. readStream
  609. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  610. .pipe(writeStream);
  611. }
  612. async handlePrivatePagesForDeletedGroup(deletedGroup, action, transferToUserGroupId, user) {
  613. const Page = this.crowi.model('Page');
  614. const pages = await Page.find({ grantedGroup: deletedGroup });
  615. switch (action) {
  616. case 'public':
  617. await Promise.all(pages.map((page) => {
  618. return Page.publicizePage(page);
  619. }));
  620. break;
  621. case 'delete':
  622. return this.deleteMultipleCompletely(pages, user);
  623. case 'transfer':
  624. await Promise.all(pages.map((page) => {
  625. return Page.transferPageToGroup(page, transferToUserGroupId);
  626. }));
  627. break;
  628. default:
  629. throw new Error('Unknown action for private pages');
  630. }
  631. }
  632. async shortBodiesMapByPageIds(pageIds = [], user) {
  633. const Page = mongoose.model('Page');
  634. const MAX_LENGTH = 350;
  635. // aggregation options
  636. const viewerCondition = await generateGrantCondition(user, null);
  637. const filterByIds = {
  638. _id: { $in: pageIds.map(id => mongoose.Types.ObjectId(id)) },
  639. };
  640. let pages;
  641. try {
  642. pages = await Page
  643. .aggregate([
  644. // filter by pageIds
  645. {
  646. $match: filterByIds,
  647. },
  648. // filter by viewer
  649. viewerCondition,
  650. // lookup: https://docs.mongodb.com/v4.4/reference/operator/aggregation/lookup/
  651. {
  652. $lookup: {
  653. from: 'revisions',
  654. let: { localRevision: '$revision' },
  655. pipeline: [
  656. {
  657. $match: {
  658. $expr: {
  659. $eq: ['$_id', '$$localRevision'],
  660. },
  661. },
  662. },
  663. {
  664. $project: {
  665. revision: { $substr: ['$body', 0, MAX_LENGTH] },
  666. },
  667. },
  668. ],
  669. as: 'revisionData',
  670. },
  671. },
  672. // projection
  673. {
  674. $project: {
  675. _id: 1,
  676. revisionData: 1,
  677. },
  678. },
  679. ]).exec();
  680. }
  681. catch (err) {
  682. logger.error('Error occurred while generating shortBodiesMap');
  683. throw err;
  684. }
  685. const shortBodiesMap = {};
  686. pages.forEach((page) => {
  687. shortBodiesMap[page._id] = page.revisionData?.[0]?.revision;
  688. });
  689. return shortBodiesMap;
  690. }
  691. validateCrowi() {
  692. if (this.crowi == null) {
  693. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  694. }
  695. }
  696. async v5MigrationByPageIds(pageIds) {
  697. const Page = mongoose.model('Page');
  698. if (pageIds == null || pageIds.length === 0) {
  699. logger.error('pageIds is null or 0 length.');
  700. return;
  701. }
  702. // generate regexps
  703. const regexps = await this._generateRegExpsByPageIds(pageIds);
  704. // migrate recursively
  705. try {
  706. await this._v5RecursiveMigration(null, regexps);
  707. }
  708. catch (err) {
  709. logger.error('V5 initial miration failed.', err);
  710. // socket.emit('v5InitialMirationFailed', { error: err.message }); TODO: use socket to tell user
  711. throw err;
  712. }
  713. }
  714. async _isPagePathIndexUnique() {
  715. const Page = this.crowi.model('Page');
  716. const now = (new Date()).toString();
  717. const path = `growi_check_is_path_index_unique_${now}`;
  718. let isUnique = false;
  719. try {
  720. await Page.insertMany([
  721. { path },
  722. { path },
  723. ]);
  724. }
  725. catch (err) {
  726. if (err?.code === 11000) { // Error code 11000 indicates the index is unique
  727. isUnique = true;
  728. logger.info('Page path index is unique.');
  729. }
  730. else {
  731. throw err;
  732. }
  733. }
  734. finally {
  735. await Page.deleteMany({ path: { $regex: new RegExp('growi_check_is_path_index_unique', 'g') } });
  736. }
  737. return isUnique;
  738. }
  739. // TODO: use socket to send status to the client
  740. async v5InitialMigration(grant) {
  741. // const socket = this.crowi.socketIoService.getAdminSocket();
  742. let isUnique;
  743. try {
  744. isUnique = await this._isPagePathIndexUnique();
  745. }
  746. catch (err) {
  747. logger.error('Failed to check path index status', err);
  748. throw err;
  749. }
  750. // drop unique index first
  751. if (isUnique) {
  752. try {
  753. await this._v5NormalizeIndex();
  754. }
  755. catch (err) {
  756. logger.error('V5 index normalization failed.', err);
  757. // socket.emit('v5IndexNormalizationFailed', { error: err.message });
  758. throw err;
  759. }
  760. }
  761. // then migrate
  762. try {
  763. await this._v5RecursiveMigration(grant, null, true);
  764. }
  765. catch (err) {
  766. logger.error('V5 initial miration failed.', err);
  767. // socket.emit('v5InitialMirationFailed', { error: err.message });
  768. throw err;
  769. }
  770. await this._setIsV5CompatibleTrue();
  771. }
  772. /*
  773. * returns an array of js RegExp instance instead of RE2 instance for mongo filter
  774. */
  775. async _generateRegExpsByPageIds(pageIds) {
  776. const Page = mongoose.model('Page');
  777. let result;
  778. try {
  779. result = await Page.findListByPageIds(pageIds, null, false);
  780. }
  781. catch (err) {
  782. logger.error('Failed to find pages by ids', err);
  783. throw err;
  784. }
  785. const { pages } = result;
  786. const regexps = pages.map(page => new RegExp(`^${page.path}`));
  787. return regexps;
  788. }
  789. async _setIsV5CompatibleTrue() {
  790. try {
  791. await this.crowi.configManager.updateConfigsInTheSameNamespace('crowi', {
  792. 'app:isV5Compatible': true,
  793. });
  794. logger.info('Successfully migrated all public pages.');
  795. }
  796. catch (err) {
  797. logger.warn('Failed to update app:isV5Compatible to true.');
  798. throw err;
  799. }
  800. }
  801. // TODO: use websocket to show progress
  802. async _v5RecursiveMigration(grant, regexps, publicOnly = false) {
  803. const BATCH_SIZE = 100;
  804. const PAGES_LIMIT = 1000;
  805. const Page = this.crowi.model('Page');
  806. const { PageQueryBuilder } = Page;
  807. // generate filter
  808. let filter = {
  809. parent: null,
  810. path: { $ne: '/' },
  811. };
  812. if (grant != null) {
  813. filter = {
  814. ...filter,
  815. grant,
  816. };
  817. }
  818. if (regexps != null && regexps.length !== 0) {
  819. filter = {
  820. ...filter,
  821. path: {
  822. $in: regexps,
  823. },
  824. };
  825. }
  826. const total = await Page.countDocuments(filter);
  827. let baseAggregation = Page
  828. .aggregate([
  829. {
  830. $match: filter,
  831. },
  832. {
  833. $project: { // minimize data to fetch
  834. _id: 1,
  835. path: 1,
  836. },
  837. },
  838. ]);
  839. // limit pages to get
  840. if (total > PAGES_LIMIT) {
  841. baseAggregation = baseAggregation.limit(Math.floor(total * 0.3));
  842. }
  843. const pagesStream = await baseAggregation.cursor({ batchSize: BATCH_SIZE });
  844. // use batch stream
  845. const batchStream = createBatchStream(BATCH_SIZE);
  846. let countPages = 0;
  847. let shouldContinue = true;
  848. // migrate all siblings for each page
  849. const migratePagesStream = new Writable({
  850. objectMode: true,
  851. async write(pages, encoding, callback) {
  852. // make list to create empty pages
  853. const parentPathsSet = new Set(pages.map(page => pathlib.dirname(page.path)));
  854. const parentPaths = Array.from(parentPathsSet);
  855. // fill parents with empty pages
  856. await Page.createEmptyPagesByPaths(parentPaths, publicOnly);
  857. // find parents again
  858. const builder = new PageQueryBuilder(Page.find({}, { _id: 1, path: 1 }), true);
  859. const parents = await builder
  860. .addConditionToListByPathsArray(parentPaths)
  861. .query
  862. .lean()
  863. .exec();
  864. // bulkWrite to update parent
  865. const updateManyOperations = parents.map((parent) => {
  866. const parentId = parent._id;
  867. // modify to adjust for RegExp
  868. let parentPath = parent.path === '/' ? '' : parent.path;
  869. // inject \ before brackets
  870. ['(', ')', '[', ']', '{', '}'].forEach((bracket) => {
  871. parentPath = parentPath.replace(bracket, `\\${bracket}`);
  872. });
  873. const filter = {
  874. // regexr.com/6889f
  875. // ex. /parent/any_child OR /any_level1
  876. path: { $regex: new RegExp(`^${parentPath}(\\/[^/]+)\\/?$`, 'g') },
  877. };
  878. if (grant != null) {
  879. filter.grant = grant;
  880. }
  881. return {
  882. updateMany: {
  883. filter,
  884. update: {
  885. parent: parentId,
  886. },
  887. },
  888. };
  889. });
  890. try {
  891. const res = await Page.bulkWrite(updateManyOperations);
  892. countPages += res.result.nModified;
  893. logger.info(`Page migration processing: (count=${countPages})`);
  894. // throw
  895. if (res.result.writeErrors.length > 0) {
  896. logger.error('Failed to migrate some pages', res.result.writeErrors);
  897. throw Error('Failed to migrate some pages');
  898. }
  899. // finish migration
  900. if (res.result.nModified === 0) { // TODO: find the best property to count updated documents
  901. shouldContinue = false;
  902. logger.error('Migration is unable to continue', 'parentPaths:', parentPaths, 'bulkWriteResult:', res);
  903. }
  904. }
  905. catch (err) {
  906. logger.error('Failed to update page.parent.', err);
  907. throw err;
  908. }
  909. callback();
  910. },
  911. final(callback) {
  912. callback();
  913. },
  914. });
  915. pagesStream
  916. .pipe(batchStream)
  917. .pipe(migratePagesStream);
  918. await streamToPromise(migratePagesStream);
  919. if (await Page.exists(filter) && shouldContinue) {
  920. return this._v5RecursiveMigration(grant, regexps, publicOnly);
  921. }
  922. }
  923. async _v5NormalizeIndex() {
  924. const collection = mongoose.connection.collection('pages');
  925. try {
  926. // drop pages.path_1 indexes
  927. await collection.dropIndex('path_1');
  928. logger.info('Succeeded to drop unique indexes from pages.path.');
  929. }
  930. catch (err) {
  931. logger.warn('Failed to drop unique indexes from pages.path.', err);
  932. throw err;
  933. }
  934. try {
  935. // create indexes without
  936. await collection.createIndex({ path: 1 }, { unique: false });
  937. logger.info('Succeeded to create non-unique indexes on pages.path.');
  938. }
  939. catch (err) {
  940. logger.warn('Failed to create non-unique indexes on pages.path.', err);
  941. throw err;
  942. }
  943. }
  944. async v5MigratablePrivatePagesCount(user) {
  945. if (user == null) {
  946. throw Error('user is required');
  947. }
  948. const Page = this.crowi.model('Page');
  949. return Page.count({ parent: null, creator: user, grant: { $ne: Page.GRANT_PUBLIC } });
  950. }
  951. }
  952. module.exports = PageService;