page.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. const mongoose = require('mongoose');
  2. const escapeStringRegexp = require('escape-string-regexp');
  3. const logger = require('@alias/logger')('growi:models:page');
  4. const debug = require('debug')('growi:models:page');
  5. const { Writable } = require('stream');
  6. const { createBatchStream } = require('@server/util/batch-stream');
  7. const { serializePageSecurely } = require('../models/serializers/page-serializer');
  8. const STATUS_PUBLISHED = 'published';
  9. const BULK_REINDEX_SIZE = 100;
  10. class PageService {
  11. constructor(crowi) {
  12. this.crowi = crowi;
  13. }
  14. async deleteCompletelyOperation(pageIds, pagePaths) {
  15. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  16. const Bookmark = this.crowi.model('Bookmark');
  17. const Comment = this.crowi.model('Comment');
  18. const Page = this.crowi.model('Page');
  19. const PageTagRelation = this.crowi.model('PageTagRelation');
  20. const ShareLink = this.crowi.model('ShareLink');
  21. const Revision = this.crowi.model('Revision');
  22. const Attachment = this.crowi.model('Attachment');
  23. const { attachmentService } = this.crowi;
  24. const attachments = await Attachment.find({ page: { $in: pageIds } });
  25. return Promise.all([
  26. Bookmark.find({ page: { $in: pageIds } }).remove({}),
  27. Comment.find({ page: { $in: pageIds } }).remove({}),
  28. PageTagRelation.find({ relatedPage: { $in: pageIds } }).remove({}),
  29. ShareLink.find({ relatedPage: { $in: pageIds } }).remove({}),
  30. Revision.find({ path: { $in: pagePaths } }).remove({}),
  31. Page.find({ _id: { $in: pageIds } }).remove({}),
  32. Page.find({ path: { $in: pagePaths } }).remove({}),
  33. attachmentService.removeAllAttachments(attachments),
  34. ]);
  35. }
  36. async duplicate(page, newPagePath, user, isRecursively) {
  37. const Page = this.crowi.model('Page');
  38. const PageTagRelation = mongoose.model('PageTagRelation');
  39. // populate
  40. await page.populate({ path: 'revision', model: 'Revision', select: 'body' }).execPopulate();
  41. // create option
  42. const options = { page };
  43. options.grant = page.grant;
  44. options.grantUserGroupId = page.grantedGroup;
  45. options.grantedUsers = page.grantedUsers;
  46. const createdPage = await Page.create(
  47. newPagePath, page.revision.body, user, options,
  48. );
  49. if (isRecursively) {
  50. this.duplicateDescendantsWithStream(page, newPagePath, user);
  51. }
  52. // take over tags
  53. const originTags = await page.findRelatedTagsById();
  54. let savedTags = [];
  55. if (originTags != null) {
  56. await PageTagRelation.updatePageTags(createdPage.id, originTags);
  57. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  58. }
  59. const result = serializePageSecurely(createdPage);
  60. result.tags = savedTags;
  61. return result;
  62. }
  63. /**
  64. * Receive the object with oldPageId and newPageId and duplicate the tags from oldPage to newPage
  65. * @param {Object} pageIdMapping e.g. key: oldPageId, value: newPageId
  66. */
  67. async duplicateTags(pageIdMapping) {
  68. const PageTagRelation = mongoose.model('PageTagRelation');
  69. // convert pageId from string to ObjectId
  70. const pageIds = Object.keys(pageIdMapping);
  71. const stage = { $or: pageIds.map((pageId) => { return { relatedPage: mongoose.Types.ObjectId(pageId) } }) };
  72. const pagesAssociatedWithTag = await PageTagRelation.aggregate([
  73. {
  74. $match: stage,
  75. },
  76. {
  77. $group: {
  78. _id: '$relatedTag',
  79. relatedPages: { $push: '$relatedPage' },
  80. },
  81. },
  82. ]);
  83. const newPageTagRelation = [];
  84. pagesAssociatedWithTag.forEach(({ _id, relatedPages }) => {
  85. // relatedPages
  86. relatedPages.forEach((pageId) => {
  87. newPageTagRelation.push({
  88. relatedPage: pageIdMapping[pageId], // newPageId
  89. relatedTag: _id,
  90. });
  91. });
  92. });
  93. return PageTagRelation.insertMany(newPageTagRelation, { ordered: false });
  94. }
  95. async duplicateDescendants(pages, user, oldPagePathPrefix, newPagePathPrefix, pathRevisionMapping) {
  96. const Page = this.crowi.model('Page');
  97. const Revision = this.crowi.model('Revision');
  98. // key: oldPageId, value: newPageId
  99. const pageIdMapping = {};
  100. const newPages = [];
  101. const newRevisions = [];
  102. pages.forEach((page) => {
  103. const newPageId = new mongoose.Types.ObjectId();
  104. const newPagePath = page.path.replace(oldPagePathPrefix, newPagePathPrefix);
  105. const revisionId = new mongoose.Types.ObjectId();
  106. pageIdMapping[page._id] = newPageId;
  107. newPages.push({
  108. _id: newPageId,
  109. path: newPagePath,
  110. creator: user._id,
  111. grant: page.grant,
  112. grantedGroup: page.grantedGroup,
  113. grantedUsers: page.grantedUsers,
  114. lastUpdateUser: user._id,
  115. redirectTo: null,
  116. revision: revisionId,
  117. });
  118. newRevisions.push({
  119. _id: revisionId, path: newPagePath, body: pathRevisionMapping[page.path].body, author: user._id, format: 'markdown',
  120. });
  121. });
  122. await Page.insertMany(newPages, { ordered: false });
  123. await Revision.insertMany(newRevisions, { ordered: false });
  124. await this.duplicateTags(pageIdMapping);
  125. }
  126. async duplicateDescendantsWithStream(page, newPagePath, user) {
  127. const Page = this.crowi.model('Page');
  128. const Revision = this.crowi.model('Revision');
  129. const newPagePathPrefix = newPagePath;
  130. const pathRegExp = new RegExp(`^${escapeStringRegexp(page.path)}`, 'i');
  131. const revisions = await Revision.find({ path: pathRegExp });
  132. const { PageQueryBuilder } = Page;
  133. const readStream = new PageQueryBuilder(Page.find())
  134. .addConditionToExcludeRedirect()
  135. .addConditionToListOnlyDescendants(page.path)
  136. .addConditionToFilteringByViewer(user)
  137. .query
  138. .lean()
  139. .cursor();
  140. // Mapping to set to the body of the new revision
  141. const pathRevisionMapping = {};
  142. revisions.forEach((revision) => {
  143. pathRevisionMapping[revision.path] = revision;
  144. });
  145. const duplicateDescendants = this.duplicateDescendants.bind(this);
  146. let count = 0;
  147. const writeStream = new Writable({
  148. objectMode: true,
  149. async write(batch, encoding, callback) {
  150. try {
  151. count += batch.length;
  152. await duplicateDescendants(batch, user, pathRegExp, newPagePathPrefix, pathRevisionMapping);
  153. logger.debug(`Adding pages progressing: (count=${count})`);
  154. }
  155. catch (err) {
  156. logger.error('addAllPages error on add anyway: ', err);
  157. }
  158. callback();
  159. },
  160. final(callback) {
  161. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  162. callback();
  163. },
  164. });
  165. readStream
  166. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  167. .pipe(writeStream);
  168. }
  169. // delete multiple pages
  170. async deleteMultipleCompletely(pages, user, options = {}) {
  171. this.validateCrowi();
  172. let pageEvent;
  173. // init event
  174. if (this.crowi != null) {
  175. pageEvent = this.crowi.event('page');
  176. pageEvent.on('create', pageEvent.onCreate);
  177. pageEvent.on('update', pageEvent.onUpdate);
  178. }
  179. const ids = pages.map(page => (page._id));
  180. const paths = pages.map(page => (page.path));
  181. const socketClientId = options.socketClientId || null;
  182. logger.debug('Deleting completely', paths);
  183. await this.deleteCompletelyOperation(ids, paths);
  184. if (socketClientId != null) {
  185. pageEvent.emit('deleteCompletely', pages, user, socketClientId); // update as renamed page
  186. }
  187. return;
  188. }
  189. async deleteCompletely(page, user, options = {}, isRecursively = false) {
  190. this.validateCrowi();
  191. let pageEvent;
  192. // init event
  193. if (this.crowi != null) {
  194. pageEvent = this.crowi.event('page');
  195. pageEvent.on('create', pageEvent.onCreate);
  196. pageEvent.on('update', pageEvent.onUpdate);
  197. }
  198. const ids = [page._id];
  199. const paths = [page.path];
  200. const socketClientId = options.socketClientId || null;
  201. logger.debug('Deleting completely', paths);
  202. await this.deleteCompletelyOperation(ids, paths);
  203. if (isRecursively) {
  204. this.deleteDescendantsWithStream(page, user, options);
  205. }
  206. if (socketClientId != null) {
  207. pageEvent.emit('delete', page, user, socketClientId); // update as renamed page
  208. }
  209. return;
  210. }
  211. /**
  212. * Create delete stream
  213. */
  214. async deleteDescendantsWithStream(targetPage, user, options = {}) {
  215. const Page = this.crowi.model('Page');
  216. const { PageQueryBuilder } = Page;
  217. const readStream = new PageQueryBuilder(Page.find())
  218. .addConditionToExcludeRedirect()
  219. .addConditionToListOnlyDescendants(targetPage.path)
  220. .addConditionToFilteringByViewer(user)
  221. .query
  222. .lean()
  223. .cursor();
  224. const deleteMultipleCompletely = this.deleteMultipleCompletely.bind(this);
  225. let count = 0;
  226. const writeStream = new Writable({
  227. objectMode: true,
  228. async write(batch, encoding, callback) {
  229. try {
  230. count += batch.length;
  231. await deleteMultipleCompletely(batch, user, options);
  232. logger.debug(`Adding pages progressing: (count=${count})`);
  233. }
  234. catch (err) {
  235. logger.error('addAllPages error on add anyway: ', err);
  236. }
  237. callback();
  238. },
  239. final(callback) {
  240. logger.debug(`Adding pages has completed: (totalCount=${count})`);
  241. callback();
  242. },
  243. });
  244. readStream
  245. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  246. .pipe(writeStream);
  247. }
  248. async revertDeletedPages(pages, user) {
  249. const Page = this.crowi.model('Page');
  250. const pageCollection = mongoose.connection.collection('pages');
  251. const revisionCollection = mongoose.connection.collection('revisions');
  252. const removePageBulkOp = pageCollection.initializeUnorderedBulkOp();
  253. const revertPageBulkOp = pageCollection.initializeUnorderedBulkOp();
  254. const revertRevisionBulkOp = revisionCollection.initializeUnorderedBulkOp();
  255. // e.g. key: '/test'
  256. const pathToPageMapping = {};
  257. const toPaths = pages.map(page => Page.getRevertDeletedPageName(page.path));
  258. const toPages = await Page.find({ path: { $in: toPaths } });
  259. toPages.forEach((toPage) => {
  260. pathToPageMapping[toPage.path] = toPage;
  261. });
  262. pages.forEach((page) => {
  263. // e.g. page.path = /trash/test, toPath = /test
  264. const toPath = Page.getRevertDeletedPageName(page.path);
  265. if (pathToPageMapping[toPath] != null) {
  266. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  267. // So, it's ok to delete the page
  268. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  269. if (pathToPageMapping[toPath].redirectTo === page.path) {
  270. removePageBulkOp.find({ path: toPath }).remove();
  271. }
  272. }
  273. revertPageBulkOp.find({ _id: page._id }).update({ $set: { path: toPath, status: STATUS_PUBLISHED, lastUpdateUser: user._id } });
  274. revertRevisionBulkOp.find({ path: page.path }).update({ $set: { path: toPath } }, { multi: true });
  275. });
  276. try {
  277. await removePageBulkOp.execute();
  278. await revertPageBulkOp.execute();
  279. await revertRevisionBulkOp.execute();
  280. }
  281. catch (err) {
  282. if (err.code !== 11000) {
  283. throw new Error('Failed to revert pages: ', err);
  284. }
  285. }
  286. }
  287. async revertDeletedPage(page, user, options = {}, isRecursively = false) {
  288. const Page = this.crowi.model('Page');
  289. const newPath = Page.getRevertDeletedPageName(page.path);
  290. const originPage = await Page.findByPath(newPath);
  291. if (originPage != null) {
  292. // When the page is deleted, it will always be created with "redirectTo" in the path of the original page.
  293. // So, it's ok to delete the page
  294. // However, If a page exists that is not "redirectTo", something is wrong. (Data correction is needed).
  295. if (originPage.redirectTo !== page.path) {
  296. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  297. }
  298. await this.deleteCompletely(originPage, options);
  299. }
  300. if (isRecursively) {
  301. this.revertDeletedDescendantsWithStream(page, user, options);
  302. }
  303. page.status = STATUS_PUBLISHED;
  304. page.lastUpdateUser = user;
  305. debug('Revert deleted the page', page, newPath);
  306. const updatedPage = await Page.rename(page, newPath, user, {});
  307. return updatedPage;
  308. }
  309. /**
  310. * Create revert stream
  311. */
  312. async revertDeletedDescendantsWithStream(targetPage, user, options = {}) {
  313. const Page = this.crowi.model('Page');
  314. const { PageQueryBuilder } = Page;
  315. const readStream = new PageQueryBuilder(Page.find())
  316. .addConditionToExcludeRedirect()
  317. .addConditionToListOnlyDescendants(targetPage.path)
  318. .addConditionToFilteringByViewer(user)
  319. .query
  320. .lean()
  321. .cursor();
  322. const revertDeletedPages = this.revertDeletedPages.bind(this);
  323. let count = 0;
  324. const writeStream = new Writable({
  325. objectMode: true,
  326. async write(batch, encoding, callback) {
  327. try {
  328. count += batch.length;
  329. revertDeletedPages(batch, user);
  330. logger.debug(`Reverting pages progressing: (count=${count})`);
  331. }
  332. catch (err) {
  333. logger.error('revertPages error on add anyway: ', err);
  334. }
  335. callback();
  336. },
  337. final(callback) {
  338. logger.debug(`Reverting pages has completed: (totalCount=${count})`);
  339. callback();
  340. },
  341. });
  342. readStream
  343. .pipe(createBatchStream(BULK_REINDEX_SIZE))
  344. .pipe(writeStream);
  345. }
  346. async handlePrivatePagesForDeletedGroup(deletedGroup, action, transferToUserGroupId) {
  347. const Page = this.crowi.model('Page');
  348. const pages = await Page.find({ grantedGroup: deletedGroup });
  349. switch (action) {
  350. case 'public':
  351. await Promise.all(pages.map((page) => {
  352. return Page.publicizePage(page);
  353. }));
  354. break;
  355. case 'delete':
  356. return this.deleteMultiplePagesCompletely(pages);
  357. case 'transfer':
  358. await Promise.all(pages.map((page) => {
  359. return Page.transferPageToGroup(page, transferToUserGroupId);
  360. }));
  361. break;
  362. default:
  363. throw new Error('Unknown action for private pages');
  364. }
  365. }
  366. validateCrowi() {
  367. if (this.crowi == null) {
  368. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  369. }
  370. }
  371. }
  372. module.exports = PageService;