2
0

page.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. // disable no-return-await for model functions
  2. /* eslint-disable no-return-await */
  3. /* eslint-disable no-use-before-define */
  4. const logger = require('@alias/logger')('growi:models:page');
  5. const debug = require('debug')('growi:models:page');
  6. const nodePath = require('path');
  7. const urljoin = require('url-join');
  8. const mongoose = require('mongoose');
  9. const mongoosePaginate = require('mongoose-paginate-v2');
  10. const uniqueValidator = require('mongoose-unique-validator');
  11. const differenceInYears = require('date-fns/differenceInYears');
  12. const { pathUtils } = require('growi-commons');
  13. const templateChecker = require('@commons/util/template-checker');
  14. const { isTopPage } = require('@commons/util/path-utils');
  15. const escapeStringRegexp = require('escape-string-regexp');
  16. const ObjectId = mongoose.Schema.Types.ObjectId;
  17. /*
  18. * define schema
  19. */
  20. const GRANT_PUBLIC = 1;
  21. const GRANT_RESTRICTED = 2;
  22. const GRANT_SPECIFIED = 3;
  23. const GRANT_OWNER = 4;
  24. const GRANT_USER_GROUP = 5;
  25. const PAGE_GRANT_ERROR = 1;
  26. const STATUS_PUBLISHED = 'published';
  27. const STATUS_DELETED = 'deleted';
  28. const pageSchema = new mongoose.Schema({
  29. path: {
  30. type: String, required: true, index: true, unique: true,
  31. },
  32. revision: { type: ObjectId, ref: 'Revision' },
  33. redirectTo: { type: String, index: true },
  34. status: { type: String, default: STATUS_PUBLISHED, index: true },
  35. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  36. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  37. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  38. creator: { type: ObjectId, ref: 'User', index: true },
  39. lastUpdateUser: { type: ObjectId, ref: 'User' },
  40. liker: [{ type: ObjectId, ref: 'User' }],
  41. seenUsers: [{ type: ObjectId, ref: 'User' }],
  42. commentCount: { type: Number, default: 0 },
  43. extended: {
  44. type: String,
  45. default: '{}',
  46. get(data) {
  47. try {
  48. return JSON.parse(data);
  49. }
  50. catch (e) {
  51. return data;
  52. }
  53. },
  54. set(data) {
  55. return JSON.stringify(data);
  56. },
  57. },
  58. pageIdOnHackmd: String,
  59. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  60. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  61. createdAt: { type: Date, default: Date.now },
  62. updatedAt: { type: Date, default: Date.now },
  63. }, {
  64. toJSON: { getters: true },
  65. toObject: { getters: true },
  66. });
  67. // apply plugins
  68. pageSchema.plugin(mongoosePaginate);
  69. pageSchema.plugin(uniqueValidator);
  70. /**
  71. * return an array of ancestors paths that is extracted from specified pagePath
  72. * e.g.
  73. * when `pagePath` is `/foo/bar/baz`,
  74. * this method returns [`/foo/bar/baz`, `/foo/bar`, `/foo`, `/`]
  75. *
  76. * @param {string} pagePath
  77. * @return {string[]} ancestors paths
  78. */
  79. const extractToAncestorsPaths = (pagePath) => {
  80. const ancestorsPaths = [];
  81. let parentPath;
  82. while (parentPath !== '/') {
  83. parentPath = nodePath.dirname(parentPath || pagePath);
  84. ancestorsPaths.push(parentPath);
  85. }
  86. return ancestorsPaths;
  87. };
  88. /**
  89. * populate page (Query or Document) to show revision
  90. * @param {any} page Query or Document
  91. * @param {string} userPublicFields string to set to select
  92. */
  93. /* eslint-disable object-curly-newline, object-property-newline */
  94. const populateDataToShowRevision = (page, userPublicFields) => {
  95. return page
  96. .populate([
  97. { path: 'lastUpdateUser', model: 'User', select: userPublicFields },
  98. { path: 'creator', model: 'User', select: userPublicFields },
  99. { path: 'grantedGroup', model: 'UserGroup' },
  100. { path: 'revision', model: 'Revision', populate: {
  101. path: 'author', model: 'User', select: userPublicFields,
  102. } },
  103. ]);
  104. };
  105. /* eslint-enable object-curly-newline, object-property-newline */
  106. class PageQueryBuilder {
  107. constructor(query) {
  108. this.query = query;
  109. }
  110. addConditionToExcludeTrashed() {
  111. this.query = this.query
  112. .and({
  113. $or: [
  114. { status: null },
  115. { status: STATUS_PUBLISHED },
  116. ],
  117. });
  118. return this;
  119. }
  120. addConditionToExcludeRedirect() {
  121. this.query = this.query.and({ redirectTo: null });
  122. return this;
  123. }
  124. /**
  125. * generate the query to find the pages '{path}/*' and '{path}' self.
  126. * If top page, return without doing anything.
  127. */
  128. addConditionToListWithDescendants(path, option) {
  129. // No request is set for the top page
  130. if (isTopPage(path)) {
  131. return this;
  132. }
  133. const pathNormalized = pathUtils.normalizePath(path);
  134. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  135. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  136. this.query = this.query
  137. .and({
  138. $or: [
  139. { path: pathNormalized },
  140. { path: new RegExp(`^${startsPattern}`) },
  141. ],
  142. });
  143. return this;
  144. }
  145. /**
  146. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  147. * If top page, return without doing anything.
  148. */
  149. addConditionToListOnlyDescendants(path, option) {
  150. // No request is set for the top page
  151. if (isTopPage(path)) {
  152. return this;
  153. }
  154. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  155. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  156. this.query = this.query
  157. .and({ path: new RegExp(`^${startsPattern}`) });
  158. return this;
  159. }
  160. /**
  161. * generate the query to find pages that start with `path`
  162. *
  163. * In normal case, returns '{path}/*' and '{path}' self.
  164. * If top page, return without doing anything.
  165. *
  166. * *option*
  167. * Left for backward compatibility
  168. */
  169. addConditionToListByStartWith(path, option) {
  170. // No request is set for the top page
  171. if (isTopPage(path)) {
  172. return this;
  173. }
  174. const startsPattern = escapeStringRegexp(path);
  175. this.query = this.query
  176. .and({ path: new RegExp(`^${startsPattern}`) });
  177. return this;
  178. }
  179. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  180. const grantConditions = [
  181. { grant: null },
  182. { grant: GRANT_PUBLIC },
  183. ];
  184. if (showAnyoneKnowsLink) {
  185. grantConditions.push({ grant: GRANT_RESTRICTED });
  186. }
  187. if (showPagesRestrictedByOwner) {
  188. grantConditions.push(
  189. { grant: GRANT_SPECIFIED },
  190. { grant: GRANT_OWNER },
  191. );
  192. }
  193. else if (user != null) {
  194. grantConditions.push(
  195. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  196. { grant: GRANT_OWNER, grantedUsers: user._id },
  197. );
  198. }
  199. if (showPagesRestrictedByGroup) {
  200. grantConditions.push(
  201. { grant: GRANT_USER_GROUP },
  202. );
  203. }
  204. else if (userGroups != null && userGroups.length > 0) {
  205. grantConditions.push(
  206. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  207. );
  208. }
  209. this.query = this.query
  210. .and({
  211. $or: grantConditions,
  212. });
  213. return this;
  214. }
  215. addConditionToPagenate(offset, limit, sortOpt) {
  216. this.query = this.query
  217. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  218. return this;
  219. }
  220. addConditionToListByPathsArray(paths) {
  221. this.query = this.query
  222. .and({
  223. path: {
  224. $in: paths,
  225. },
  226. });
  227. return this;
  228. }
  229. populateDataToList(userPublicFields) {
  230. this.query = this.query
  231. .populate({
  232. path: 'lastUpdateUser',
  233. select: userPublicFields,
  234. });
  235. return this;
  236. }
  237. populateDataToShowRevision(userPublicFields) {
  238. this.query = populateDataToShowRevision(this.query, userPublicFields);
  239. return this;
  240. }
  241. }
  242. module.exports = function(crowi) {
  243. let pageEvent;
  244. // init event
  245. if (crowi != null) {
  246. pageEvent = crowi.event('page');
  247. pageEvent.on('create', pageEvent.onCreate);
  248. pageEvent.on('update', pageEvent.onUpdate);
  249. }
  250. function validateCrowi() {
  251. if (crowi == null) {
  252. throw new Error('"crowi" is null. Init User model with "crowi" argument first.');
  253. }
  254. }
  255. pageSchema.methods.isDeleted = function() {
  256. return (this.status === STATUS_DELETED) || checkIfTrashed(this.path);
  257. };
  258. pageSchema.methods.isPublic = function() {
  259. if (!this.grant || this.grant === GRANT_PUBLIC) {
  260. return true;
  261. }
  262. return false;
  263. };
  264. pageSchema.methods.isTopPage = function() {
  265. return isTopPage(this.path);
  266. };
  267. pageSchema.methods.isTemplate = function() {
  268. return templateChecker(this.path);
  269. };
  270. pageSchema.methods.isLatestRevision = function() {
  271. // populate されていなくて判断できない
  272. if (!this.latestRevision || !this.revision) {
  273. return true;
  274. }
  275. // comparing ObjectId with string
  276. // eslint-disable-next-line eqeqeq
  277. return (this.latestRevision == this.revision._id.toString());
  278. };
  279. pageSchema.methods.findRelatedTagsById = async function() {
  280. const PageTagRelation = mongoose.model('PageTagRelation');
  281. const relations = await PageTagRelation.find({ relatedPage: this._id }).populate('relatedTag');
  282. return relations.map((relation) => { return relation.relatedTag.name });
  283. };
  284. pageSchema.methods.isUpdatable = function(previousRevision) {
  285. const revision = this.latestRevision || this.revision;
  286. // comparing ObjectId with string
  287. // eslint-disable-next-line eqeqeq
  288. if (revision != previousRevision) {
  289. return false;
  290. }
  291. return true;
  292. };
  293. pageSchema.methods.isLiked = function(user) {
  294. if (user == null || user._id == null) {
  295. return false;
  296. }
  297. return this.liker.some((likedUserId) => {
  298. return likedUserId.toString() === user._id.toString();
  299. });
  300. };
  301. pageSchema.methods.like = function(userData) {
  302. const self = this;
  303. return new Promise(((resolve, reject) => {
  304. const added = self.liker.addToSet(userData._id);
  305. if (added.length > 0) {
  306. self.save((err, data) => {
  307. if (err) {
  308. return reject(err);
  309. }
  310. logger.debug('liker updated!', added);
  311. return resolve(data);
  312. });
  313. }
  314. else {
  315. logger.debug('liker not updated');
  316. return reject(self);
  317. }
  318. }));
  319. };
  320. pageSchema.methods.unlike = function(userData, callback) {
  321. const self = this;
  322. return new Promise(((resolve, reject) => {
  323. const beforeCount = self.liker.length;
  324. self.liker.pull(userData._id);
  325. if (self.liker.length !== beforeCount) {
  326. self.save((err, data) => {
  327. if (err) {
  328. return reject(err);
  329. }
  330. return resolve(data);
  331. });
  332. }
  333. else {
  334. logger.debug('liker not updated');
  335. return reject(self);
  336. }
  337. }));
  338. };
  339. pageSchema.methods.isSeenUser = function(userData) {
  340. return this.seenUsers.includes(userData._id);
  341. };
  342. pageSchema.methods.seen = async function(userData) {
  343. if (this.isSeenUser(userData)) {
  344. debug('seenUsers not updated');
  345. return this;
  346. }
  347. if (!userData || !userData._id) {
  348. throw new Error('User data is not valid');
  349. }
  350. const added = this.seenUsers.addToSet(userData._id);
  351. const saved = await this.save();
  352. debug('seenUsers updated!', added);
  353. return saved;
  354. };
  355. pageSchema.methods.getSlackChannel = function() {
  356. const extended = this.get('extended');
  357. if (!extended) {
  358. return '';
  359. }
  360. return extended.slack || '';
  361. };
  362. pageSchema.methods.updateSlackChannel = function(slackChannel) {
  363. const extended = this.extended;
  364. extended.slack = slackChannel;
  365. return this.updateExtended(extended);
  366. };
  367. pageSchema.methods.updateExtended = function(extended) {
  368. const page = this;
  369. page.extended = extended;
  370. return new Promise(((resolve, reject) => {
  371. return page.save((err, doc) => {
  372. if (err) {
  373. return reject(err);
  374. }
  375. return resolve(doc);
  376. });
  377. }));
  378. };
  379. pageSchema.methods.initLatestRevisionField = async function(revisionId) {
  380. this.latestRevision = this.revision;
  381. if (revisionId != null) {
  382. this.revision = revisionId;
  383. }
  384. };
  385. pageSchema.methods.populateDataToShowRevision = async function() {
  386. validateCrowi();
  387. const User = crowi.model('User');
  388. return populateDataToShowRevision(this, User.USER_PUBLIC_FIELDS)
  389. .execPopulate();
  390. };
  391. pageSchema.methods.populateDataToMakePresentation = async function(revisionId) {
  392. this.latestRevision = this.revision;
  393. if (revisionId != null) {
  394. this.revision = revisionId;
  395. }
  396. return this.populate('revision').execPopulate();
  397. };
  398. pageSchema.methods.applyScope = function(user, grant, grantUserGroupId) {
  399. // reset
  400. this.grantedUsers = [];
  401. this.grantedGroup = null;
  402. this.grant = grant || GRANT_PUBLIC;
  403. if (grant !== GRANT_PUBLIC && grant !== GRANT_USER_GROUP) {
  404. this.grantedUsers.push(user._id);
  405. }
  406. if (grant === GRANT_USER_GROUP) {
  407. this.grantedGroup = grantUserGroupId;
  408. }
  409. };
  410. pageSchema.methods.getContentAge = function() {
  411. return differenceInYears(new Date(), this.updatedAt);
  412. };
  413. pageSchema.statics.updateCommentCount = function(pageId) {
  414. validateCrowi();
  415. const self = this;
  416. const Comment = crowi.model('Comment');
  417. return Comment.countCommentByPageId(pageId)
  418. .then((count) => {
  419. self.update({ _id: pageId }, { commentCount: count }, {}, (err, data) => {
  420. if (err) {
  421. debug('Update commentCount Error', err);
  422. throw err;
  423. }
  424. return data;
  425. });
  426. });
  427. };
  428. pageSchema.statics.getGrantLabels = function() {
  429. const grantLabels = {};
  430. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  431. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  432. // grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  433. grantLabels[GRANT_USER_GROUP] = 'Only inside the group'; // 特定グループのみ
  434. grantLabels[GRANT_OWNER] = 'Only me'; // 自分のみ
  435. return grantLabels;
  436. };
  437. pageSchema.statics.getUserPagePath = function(user) {
  438. return `/user/${user.username}`;
  439. };
  440. pageSchema.statics.getDeletedPageName = function(path) {
  441. if (path.match('/')) {
  442. // eslint-disable-next-line no-param-reassign
  443. path = path.substr(1);
  444. }
  445. return `/trash/${path}`;
  446. };
  447. pageSchema.statics.getRevertDeletedPageName = function(path) {
  448. return path.replace('/trash', '');
  449. };
  450. pageSchema.statics.isDeletableName = function(path) {
  451. const notDeletable = [
  452. /^\/user\/[^/]+$/, // user page
  453. ];
  454. for (let i = 0; i < notDeletable.length; i++) {
  455. const pattern = notDeletable[i];
  456. if (path.match(pattern)) {
  457. return false;
  458. }
  459. }
  460. return true;
  461. };
  462. pageSchema.statics.isCreatableName = function(name) {
  463. const forbiddenPages = [
  464. /\^|\$|\*|\+|#|%/,
  465. /^\/-\/.*/,
  466. /^\/_r\/.*/,
  467. /^\/_apix?(\/.*)?/,
  468. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  469. /\/{2,}/, // avoid miss in renaming
  470. /\s+\/\s+/, // avoid miss in renaming
  471. /.+\/edit$/,
  472. /.+\.md$/,
  473. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments|tags)(\/.*|$)/,
  474. ];
  475. let isCreatable = true;
  476. forbiddenPages.forEach((page) => {
  477. const pageNameReg = new RegExp(page);
  478. if (name.match(pageNameReg)) {
  479. isCreatable = false;
  480. }
  481. });
  482. return isCreatable;
  483. };
  484. pageSchema.statics.fixToCreatableName = function(path) {
  485. return path
  486. .replace(/\/\//g, '/');
  487. };
  488. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  489. this.update({ _id: pageId }, { revision: revisionId }, {}, (err, data) => {
  490. cb(err, data);
  491. });
  492. };
  493. /**
  494. * return whether the user is accessible to the page
  495. * @param {string} id ObjectId
  496. * @param {User} user
  497. */
  498. pageSchema.statics.isAccessiblePageByViewer = async function(id, user) {
  499. const baseQuery = this.count({ _id: id });
  500. let userGroups = [];
  501. if (user != null) {
  502. validateCrowi();
  503. const UserGroupRelation = crowi.model('UserGroupRelation');
  504. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  505. }
  506. const queryBuilder = new PageQueryBuilder(baseQuery);
  507. queryBuilder.addConditionToFilteringByViewer(user, userGroups, true);
  508. const count = await queryBuilder.query.exec();
  509. return count > 0;
  510. };
  511. /**
  512. * @param {string} id ObjectId
  513. * @param {User} user User instance
  514. * @param {UserGroup[]} userGroups List of UserGroup instances
  515. */
  516. pageSchema.statics.findByIdAndViewer = async function(id, user, userGroups) {
  517. const baseQuery = this.findOne({ _id: id });
  518. let relatedUserGroups = userGroups;
  519. if (user != null && relatedUserGroups == null) {
  520. validateCrowi();
  521. const UserGroupRelation = crowi.model('UserGroupRelation');
  522. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  523. }
  524. const queryBuilder = new PageQueryBuilder(baseQuery);
  525. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  526. return await queryBuilder.query.exec();
  527. };
  528. // find page by path
  529. pageSchema.statics.findByPath = function(path) {
  530. if (path == null) {
  531. return null;
  532. }
  533. return this.findOne({ path });
  534. };
  535. /**
  536. * @param {string} path Page path
  537. * @param {User} user User instance
  538. * @param {UserGroup[]} userGroups List of UserGroup instances
  539. */
  540. pageSchema.statics.findByPathAndViewer = async function(path, user, userGroups) {
  541. if (path == null) {
  542. throw new Error('path is required.');
  543. }
  544. const baseQuery = this.findOne({ path });
  545. let relatedUserGroups = userGroups;
  546. if (user != null && relatedUserGroups == null) {
  547. validateCrowi();
  548. const UserGroupRelation = crowi.model('UserGroupRelation');
  549. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  550. }
  551. const queryBuilder = new PageQueryBuilder(baseQuery);
  552. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, true);
  553. return await queryBuilder.query.exec();
  554. };
  555. /**
  556. * @param {string} path Page path
  557. * @param {User} user User instance
  558. * @param {UserGroup[]} userGroups List of UserGroup instances
  559. */
  560. pageSchema.statics.findAncestorByPathAndViewer = async function(path, user, userGroups) {
  561. if (path == null) {
  562. throw new Error('path is required.');
  563. }
  564. if (path === '/') {
  565. return null;
  566. }
  567. const ancestorsPaths = extractToAncestorsPaths(path);
  568. // pick the longest one
  569. const baseQuery = this.findOne({ path: { $in: ancestorsPaths } }).sort({ path: -1 });
  570. let relatedUserGroups = userGroups;
  571. if (user != null && relatedUserGroups == null) {
  572. validateCrowi();
  573. const UserGroupRelation = crowi.model('UserGroupRelation');
  574. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  575. }
  576. const queryBuilder = new PageQueryBuilder(baseQuery);
  577. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups);
  578. return await queryBuilder.query.exec();
  579. };
  580. pageSchema.statics.findByRedirectTo = function(path) {
  581. return this.findOne({ redirectTo: path });
  582. };
  583. /**
  584. * find pages that is match with `path` and its descendants
  585. */
  586. pageSchema.statics.findListWithDescendants = async function(path, user, option = {}) {
  587. const builder = new PageQueryBuilder(this.find());
  588. builder.addConditionToListWithDescendants(path, option);
  589. return await findListFromBuilderAndViewer(builder, user, false, option);
  590. };
  591. /**
  592. * find pages that is match with `path` and its descendants whitch user is able to manage
  593. */
  594. pageSchema.statics.findManageableListWithDescendants = async function(page, user, option = {}) {
  595. if (user == null) {
  596. return null;
  597. }
  598. const builder = new PageQueryBuilder(this.find());
  599. builder.addConditionToListWithDescendants(page.path, option);
  600. builder.addConditionToExcludeRedirect();
  601. // add grant conditions
  602. await addConditionToFilteringByViewerToEdit(builder, user);
  603. const { pages } = await findListFromBuilderAndViewer(builder, user, false, option);
  604. // add page if 'grant' is GRANT_RESTRICTED
  605. // because addConditionToListWithDescendants excludes GRANT_RESTRICTED pages
  606. if (page.grant === GRANT_RESTRICTED) {
  607. pages.push(page);
  608. }
  609. return pages;
  610. };
  611. /**
  612. * find pages that start with `path`
  613. */
  614. pageSchema.statics.findListByStartWith = async function(path, user, option) {
  615. const builder = new PageQueryBuilder(this.find());
  616. builder.addConditionToListByStartWith(path, option);
  617. return await findListFromBuilderAndViewer(builder, user, false, option);
  618. };
  619. /**
  620. * find pages that is created by targetUser
  621. *
  622. * @param {User} targetUser
  623. * @param {User} currentUser
  624. * @param {any} option
  625. */
  626. pageSchema.statics.findListByCreator = async function(targetUser, currentUser, option) {
  627. const opt = Object.assign({ sort: 'createdAt', desc: -1 }, option);
  628. const builder = new PageQueryBuilder(this.find({ creator: targetUser._id }));
  629. let showAnyoneKnowsLink = null;
  630. if (targetUser != null && currentUser != null) {
  631. showAnyoneKnowsLink = targetUser._id.equals(currentUser._id);
  632. }
  633. return await findListFromBuilderAndViewer(builder, currentUser, showAnyoneKnowsLink, opt);
  634. };
  635. pageSchema.statics.findListByPageIds = async function(ids, option) {
  636. const User = crowi.model('User');
  637. const opt = Object.assign({}, option);
  638. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }));
  639. builder.addConditionToExcludeRedirect();
  640. builder.addConditionToPagenate(opt.offset, opt.limit);
  641. // count
  642. const totalCount = await builder.query.exec('count');
  643. // find
  644. builder.populateDataToList(User.USER_PUBLIC_FIELDS);
  645. const pages = await builder.query.exec('find');
  646. const result = {
  647. pages, totalCount, offset: opt.offset, limit: opt.limit,
  648. };
  649. return result;
  650. };
  651. /**
  652. * find pages by PageQueryBuilder
  653. * @param {PageQueryBuilder} builder
  654. * @param {User} user
  655. * @param {boolean} showAnyoneKnowsLink
  656. * @param {any} option
  657. */
  658. async function findListFromBuilderAndViewer(builder, user, showAnyoneKnowsLink, option) {
  659. validateCrowi();
  660. const User = crowi.model('User');
  661. const opt = Object.assign({ sort: 'updatedAt', desc: -1 }, option);
  662. const sortOpt = {};
  663. sortOpt[opt.sort] = opt.desc;
  664. // exclude trashed pages
  665. if (!opt.includeTrashed) {
  666. builder.addConditionToExcludeTrashed();
  667. }
  668. // exclude redirect pages
  669. if (!opt.includeRedirect) {
  670. builder.addConditionToExcludeRedirect();
  671. }
  672. // add grant conditions
  673. await addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink);
  674. // count
  675. const totalCount = await builder.query.exec('count');
  676. // find
  677. builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
  678. builder.populateDataToList(User.USER_PUBLIC_FIELDS);
  679. const pages = await builder.query.exec('find');
  680. const result = {
  681. pages, totalCount, offset: opt.offset, limit: opt.limit,
  682. };
  683. return result;
  684. }
  685. /**
  686. * Add condition that filter pages by viewer
  687. * by considering Config
  688. *
  689. * @param {PageQueryBuilder} builder
  690. * @param {User} user
  691. * @param {boolean} showAnyoneKnowsLink
  692. */
  693. async function addConditionToFilteringByViewerForList(builder, user, showAnyoneKnowsLink) {
  694. validateCrowi();
  695. // determine User condition
  696. const hidePagesRestrictedByOwner = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByOwner');
  697. const hidePagesRestrictedByGroup = crowi.configManager.getConfig('crowi', 'security:list-policy:hideRestrictedByGroup');
  698. // determine UserGroup condition
  699. let userGroups = null;
  700. if (user != null) {
  701. const UserGroupRelation = crowi.model('UserGroupRelation');
  702. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  703. }
  704. return builder.addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink, !hidePagesRestrictedByOwner, !hidePagesRestrictedByGroup);
  705. }
  706. /**
  707. * Add condition that filter pages by viewer
  708. * by considering Config
  709. *
  710. * @param {PageQueryBuilder} builder
  711. * @param {User} user
  712. * @param {boolean} showAnyoneKnowsLink
  713. */
  714. async function addConditionToFilteringByViewerToEdit(builder, user) {
  715. validateCrowi();
  716. // determine UserGroup condition
  717. let userGroups = null;
  718. if (user != null) {
  719. const UserGroupRelation = crowi.model('UserGroupRelation');
  720. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  721. }
  722. return builder.addConditionToFilteringByViewer(user, userGroups, false, false, false);
  723. }
  724. /**
  725. * export addConditionToFilteringByViewerForList as static method
  726. */
  727. pageSchema.statics.addConditionToFilteringByViewerForList = addConditionToFilteringByViewerForList;
  728. /**
  729. * Throw error for growi-lsx-plugin (v1.x)
  730. */
  731. pageSchema.statics.generateQueryToListByStartWith = function(path, user, option) {
  732. const dummyQuery = this.find();
  733. dummyQuery.exec = async() => {
  734. throw new Error('Plugin version mismatch. Upgrade growi-lsx-plugin to v2.0.0 or above.');
  735. };
  736. return dummyQuery;
  737. };
  738. pageSchema.statics.generateQueryToListWithDescendants = pageSchema.statics.generateQueryToListByStartWith;
  739. /**
  740. * find all templates applicable to the new page
  741. */
  742. pageSchema.statics.findTemplate = async function(path) {
  743. const templatePath = nodePath.posix.dirname(path);
  744. const pathList = generatePathsOnTree(path, []);
  745. const regexpList = pathList.map((path) => {
  746. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  747. return new RegExp(`^${escapeStringRegexp(pathWithTrailingSlash)}_{1,2}template$`);
  748. });
  749. const templatePages = await this.find({ path: { $in: regexpList } })
  750. .populate({ path: 'revision', model: 'Revision' })
  751. .exec();
  752. return fetchTemplate(templatePages, templatePath);
  753. };
  754. const generatePathsOnTree = (path, pathList) => {
  755. pathList.push(path);
  756. if (path === '/') {
  757. return pathList;
  758. }
  759. const newPath = nodePath.posix.dirname(path);
  760. return generatePathsOnTree(newPath, pathList);
  761. };
  762. const assignTemplateByType = (templates, path, type) => {
  763. const targetTemplatePath = urljoin(path, `${type}template`);
  764. return templates.find((template) => {
  765. return (template.path === targetTemplatePath);
  766. });
  767. };
  768. const assignDecendantsTemplate = (decendantsTemplates, path) => {
  769. const decendantsTemplate = assignTemplateByType(decendantsTemplates, path, '__');
  770. if (decendantsTemplate) {
  771. return decendantsTemplate;
  772. }
  773. if (path === '/') {
  774. return;
  775. }
  776. const newPath = nodePath.posix.dirname(path);
  777. return assignDecendantsTemplate(decendantsTemplates, newPath);
  778. };
  779. const fetchTemplate = async(templates, templatePath) => {
  780. let templateBody;
  781. let templateTags;
  782. /**
  783. * get children template
  784. * __tempate: applicable only to immediate decendants
  785. */
  786. const childrenTemplate = assignTemplateByType(templates, templatePath, '_');
  787. /**
  788. * get decendants templates
  789. * _tempate: applicable to all pages under
  790. */
  791. const decendantsTemplate = assignDecendantsTemplate(templates, templatePath);
  792. if (childrenTemplate) {
  793. templateBody = childrenTemplate.revision.body;
  794. templateTags = await childrenTemplate.findRelatedTagsById();
  795. }
  796. else if (decendantsTemplate) {
  797. templateBody = decendantsTemplate.revision.body;
  798. templateTags = await decendantsTemplate.findRelatedTagsById();
  799. }
  800. return { templateBody, templateTags };
  801. };
  802. async function pushRevision(pageData, newRevision, user) {
  803. await newRevision.save();
  804. debug('Successfully saved new revision', newRevision);
  805. pageData.revision = newRevision;
  806. pageData.lastUpdateUser = user;
  807. pageData.updatedAt = Date.now();
  808. return pageData.save();
  809. }
  810. async function validateAppliedScope(user, grant, grantUserGroupId) {
  811. if (grant === GRANT_USER_GROUP && grantUserGroupId == null) {
  812. throw new Error('grant userGroupId is not specified');
  813. }
  814. if (grant === GRANT_USER_GROUP) {
  815. const UserGroupRelation = crowi.model('UserGroupRelation');
  816. const count = await UserGroupRelation.countByGroupIdAndUser(grantUserGroupId, user);
  817. if (count === 0) {
  818. throw new Error('no relations were exist for group and user.');
  819. }
  820. }
  821. }
  822. pageSchema.statics.create = async function(path, body, user, options = {}) {
  823. validateCrowi();
  824. const Page = this;
  825. const Revision = crowi.model('Revision');
  826. const format = options.format || 'markdown';
  827. const redirectTo = options.redirectTo || null;
  828. const grantUserGroupId = options.grantUserGroupId || null;
  829. const socketClientId = options.socketClientId || null;
  830. // sanitize path
  831. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  832. let grant = options.grant;
  833. // force public
  834. if (isTopPage(path)) {
  835. grant = GRANT_PUBLIC;
  836. }
  837. const isExist = await this.count({ path });
  838. if (isExist) {
  839. throw new Error('Cannot create new page to existed path');
  840. }
  841. const page = new Page();
  842. page.path = path;
  843. page.creator = user;
  844. page.lastUpdateUser = user;
  845. page.redirectTo = redirectTo;
  846. page.status = STATUS_PUBLISHED;
  847. await validateAppliedScope(user, grant, grantUserGroupId);
  848. page.applyScope(user, grant, grantUserGroupId);
  849. let savedPage = await page.save();
  850. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  851. const revision = await pushRevision(savedPage, newRevision, user);
  852. savedPage = await this.findByPath(revision.path);
  853. await savedPage.populateDataToShowRevision();
  854. if (socketClientId != null) {
  855. pageEvent.emit('create', savedPage, user, socketClientId);
  856. }
  857. return savedPage;
  858. };
  859. pageSchema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  860. validateCrowi();
  861. const Revision = crowi.model('Revision');
  862. const grant = options.grant || pageData.grant; // use the previous data if absence
  863. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  864. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  865. const socketClientId = options.socketClientId || null;
  866. await validateAppliedScope(user, grant, grantUserGroupId);
  867. pageData.applyScope(user, grant, grantUserGroupId);
  868. // update existing page
  869. let savedPage = await pageData.save();
  870. const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
  871. const revision = await pushRevision(savedPage, newRevision, user);
  872. savedPage = await this.findByPath(revision.path);
  873. await savedPage.populateDataToShowRevision();
  874. if (isSyncRevisionToHackmd) {
  875. savedPage = await this.syncRevisionToHackmd(savedPage);
  876. }
  877. if (socketClientId != null) {
  878. pageEvent.emit('update', savedPage, user, socketClientId);
  879. }
  880. return savedPage;
  881. };
  882. pageSchema.statics.applyScopesToDescendantsAsyncronously = async function(parentPage, user) {
  883. const builder = new PageQueryBuilder(this.find());
  884. builder.addConditionToListWithDescendants(parentPage.path);
  885. builder.addConditionToExcludeRedirect();
  886. // add grant conditions
  887. await addConditionToFilteringByViewerToEdit(builder, user);
  888. // get all pages that the specified user can update
  889. const pages = await builder.query.exec();
  890. for (const page of pages) {
  891. // skip parentPage
  892. if (page.id === parentPage.id) {
  893. continue;
  894. }
  895. page.applyScope(user, parentPage.grant, parentPage.grantedGroup);
  896. page.save();
  897. }
  898. };
  899. pageSchema.statics.deletePage = async function(pageData, user, options = {}) {
  900. const newPath = this.getDeletedPageName(pageData.path);
  901. const isTrashed = checkIfTrashed(pageData.path);
  902. if (isTrashed) {
  903. throw new Error('This method does NOT support deleting trashed pages.');
  904. }
  905. const socketClientId = options.socketClientId || null;
  906. if (this.isDeletableName(pageData.path)) {
  907. pageData.status = STATUS_DELETED;
  908. const updatedPageData = await this.rename(pageData, newPath, user, { socketClientId, createRedirectPage: true });
  909. return updatedPageData;
  910. }
  911. return Promise.reject(new Error('Page is not deletable.'));
  912. };
  913. const checkIfTrashed = (path) => {
  914. return (path.search(/^\/trash/) !== -1);
  915. };
  916. pageSchema.statics.deletePageRecursively = async function(targetPage, user, options = {}) {
  917. const isTrashed = checkIfTrashed(targetPage.path);
  918. if (isTrashed) {
  919. throw new Error('This method does NOT supports deleting trashed pages.');
  920. }
  921. // find manageable descendants (this array does not include GRANT_RESTRICTED)
  922. const pages = await this.findManageableListWithDescendants(targetPage, user, options);
  923. await Promise.all(pages.map((page) => {
  924. return this.deletePage(page, user, options);
  925. }));
  926. };
  927. // TODO: transplant to service/page.js because page deletion affects various models data
  928. pageSchema.statics.revertDeletedPage = async function(page, user, options = {}) {
  929. const newPath = this.getRevertDeletedPageName(page.path);
  930. const originPage = await this.findByPath(newPath);
  931. if (originPage != null) {
  932. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  933. // そのため、そいつは削除してOK
  934. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  935. if (originPage.redirectTo !== page.path) {
  936. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  937. }
  938. await this.completelyDeletePage(originPage, options);
  939. }
  940. page.status = STATUS_PUBLISHED;
  941. page.lastUpdateUser = user;
  942. debug('Revert deleted the page', page, newPath);
  943. const updatedPage = await this.rename(page, newPath, user, {});
  944. return updatedPage;
  945. };
  946. pageSchema.statics.revertDeletedPageRecursively = async function(targetPage, user, options = {}) {
  947. const findOpts = { includeTrashed: true };
  948. const pages = await this.findManageableListWithDescendants(targetPage, user, findOpts);
  949. let updatedPage = null;
  950. await Promise.all(pages.map((page) => {
  951. const isParent = (page.path === targetPage.path);
  952. const p = this.revertDeletedPage(page, user, options);
  953. if (isParent) {
  954. updatedPage = p;
  955. }
  956. return p;
  957. }));
  958. return updatedPage;
  959. };
  960. /**
  961. * This is danger.
  962. */
  963. // TODO: transplant to service/page.js because page deletion affects various models data
  964. pageSchema.statics.completelyDeletePage = async function(pageData, user, options = {}) {
  965. validateCrowi();
  966. const { _id, path } = pageData;
  967. const socketClientId = options.socketClientId || null;
  968. logger.debug('Deleting completely', path);
  969. await crowi.pageService.deleteCompletely(_id, path);
  970. if (socketClientId != null) {
  971. pageEvent.emit('delete', pageData, user, socketClientId); // update as renamed page
  972. }
  973. return pageData;
  974. };
  975. /**
  976. * Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  977. */
  978. // TODO: transplant to service/page.js because page deletion affects various models data
  979. pageSchema.statics.completelyDeletePageRecursively = async function(targetPage, user, options = {}) {
  980. const findOpts = { includeTrashed: true };
  981. // find manageable descendants (this array does not include GRANT_RESTRICTED)
  982. const pages = await this.findManageableListWithDescendants(targetPage, user, findOpts);
  983. await Promise.all(pages.map((page) => {
  984. return this.completelyDeletePage(page, user, options);
  985. }));
  986. };
  987. pageSchema.statics.removeByPath = function(path) {
  988. if (path == null) {
  989. throw new Error('path is required');
  990. }
  991. return this.findOneAndRemove({ path }).exec();
  992. };
  993. /**
  994. * remove the page that is redirecting to specified `pagePath` recursively
  995. * ex: when
  996. * '/page1' redirects to '/page2' and
  997. * '/page2' redirects to '/page3'
  998. * and given '/page3',
  999. * '/page1' and '/page2' will be removed
  1000. *
  1001. * @param {string} pagePath
  1002. */
  1003. pageSchema.statics.removeRedirectOriginPageByPath = async function(pagePath) {
  1004. const redirectPage = await this.findByRedirectTo(pagePath);
  1005. if (redirectPage == null) {
  1006. return;
  1007. }
  1008. // remove
  1009. await this.findByIdAndRemove(redirectPage.id);
  1010. // remove recursive
  1011. await this.removeRedirectOriginPageByPath(redirectPage.path);
  1012. };
  1013. pageSchema.statics.rename = async function(pageData, newPagePath, user, options) {
  1014. validateCrowi();
  1015. const Page = this;
  1016. const Revision = crowi.model('Revision');
  1017. const path = pageData.path;
  1018. const createRedirectPage = options.createRedirectPage || false;
  1019. const updateMetadata = options.updateMetadata || false;
  1020. const socketClientId = options.socketClientId || null;
  1021. // sanitize path
  1022. newPagePath = crowi.xss.process(newPagePath); // eslint-disable-line no-param-reassign
  1023. // update Page
  1024. pageData.path = newPagePath;
  1025. if (updateMetadata) {
  1026. pageData.lastUpdateUser = user;
  1027. pageData.updatedAt = Date.now();
  1028. }
  1029. const updatedPageData = await pageData.save();
  1030. // update Rivisions
  1031. await Revision.updateRevisionListByPath(path, { path: newPagePath }, {});
  1032. if (createRedirectPage) {
  1033. const body = `redirect ${newPagePath}`;
  1034. await Page.create(path, body, user, { redirectTo: newPagePath });
  1035. }
  1036. pageEvent.emit('delete', pageData, user, socketClientId);
  1037. pageEvent.emit('create', updatedPageData, user, socketClientId);
  1038. return updatedPageData;
  1039. };
  1040. pageSchema.statics.renameRecursively = async function(targetPage, newPagePathPrefix, user, options) {
  1041. validateCrowi();
  1042. const path = targetPage.path;
  1043. const pathRegExp = new RegExp(`^${escapeStringRegexp(path)}`, 'i');
  1044. // sanitize path
  1045. newPagePathPrefix = crowi.xss.process(newPagePathPrefix); // eslint-disable-line no-param-reassign
  1046. // find manageable descendants
  1047. const pages = await this.findManageableListWithDescendants(targetPage, user, options);
  1048. await Promise.all(pages.map((page) => {
  1049. const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  1050. return this.rename(page, newPagePath, user, options);
  1051. }));
  1052. targetPage.path = newPagePathPrefix;
  1053. return targetPage;
  1054. };
  1055. pageSchema.statics.duplicate = async function(page, newPagePath, user) {
  1056. const Page = this;
  1057. // populate
  1058. await page.populate({ path: 'revision', model: 'Revision', select: 'body' }).execPopulate();
  1059. // create option
  1060. const options = { page };
  1061. options.grant = page.grant;
  1062. options.grantUserGroupId = page.grantedGroup;
  1063. options.grantedUsers = page.grantedUsers;
  1064. const createdPage = await Page.create(
  1065. newPagePath, page.revision.body, user, options,
  1066. );
  1067. const originTags = await page.findRelatedTagsById();
  1068. const savedTags = await saveTagsAction({ page, createdPage, pageTags: originTags });
  1069. // global notification
  1070. if (globalNotificationService != null) {
  1071. try {
  1072. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage, user);
  1073. }
  1074. catch (err) {
  1075. logger.error('Create grobal notification failed', err);
  1076. }
  1077. }
  1078. return { page: pageService.serializeToObj(createdPage), tags: savedTags };
  1079. };
  1080. pageSchema.statics.findListByPathsArray = async function(paths) {
  1081. const queryBuilder = new PageQueryBuilder(this.find());
  1082. queryBuilder.addConditionToListByPathsArray(paths);
  1083. return await queryBuilder.query.exec();
  1084. };
  1085. // TODO: transplant to service/page.js because page deletion affects various models data
  1086. pageSchema.statics.handlePrivatePagesForDeletedGroup = async function(deletedGroup, action, transferToUserGroupId) {
  1087. const Page = mongoose.model('Page');
  1088. const pages = await this.find({ grantedGroup: deletedGroup });
  1089. switch (action) {
  1090. case 'public':
  1091. await Promise.all(pages.map((page) => {
  1092. return Page.publicizePage(page);
  1093. }));
  1094. break;
  1095. case 'delete':
  1096. await Promise.all(pages.map((page) => {
  1097. return Page.completelyDeletePage(page);
  1098. }));
  1099. break;
  1100. case 'transfer':
  1101. await Promise.all(pages.map((page) => {
  1102. return Page.transferPageToGroup(page, transferToUserGroupId);
  1103. }));
  1104. break;
  1105. default:
  1106. throw new Error('Unknown action for private pages');
  1107. }
  1108. };
  1109. pageSchema.statics.publicizePage = async function(page) {
  1110. page.grantedGroup = null;
  1111. page.grant = GRANT_PUBLIC;
  1112. await page.save();
  1113. };
  1114. pageSchema.statics.transferPageToGroup = async function(page, transferToUserGroupId) {
  1115. const UserGroup = mongoose.model('UserGroup');
  1116. // check page existence
  1117. const isExist = await UserGroup.count({ _id: transferToUserGroupId }) > 0;
  1118. if (isExist) {
  1119. page.grantedGroup = transferToUserGroupId;
  1120. await page.save();
  1121. }
  1122. else {
  1123. throw new Error('Cannot find the group to which private pages belong to. _id: ', transferToUserGroupId);
  1124. }
  1125. };
  1126. /**
  1127. * associate GROWI page and HackMD page
  1128. * @param {Page} pageData
  1129. * @param {string} pageIdOnHackmd
  1130. */
  1131. pageSchema.statics.registerHackmdPage = function(pageData, pageIdOnHackmd) {
  1132. pageData.pageIdOnHackmd = pageIdOnHackmd;
  1133. return this.syncRevisionToHackmd(pageData);
  1134. };
  1135. /**
  1136. * update revisionHackmdSynced
  1137. * @param {Page} pageData
  1138. * @param {bool} isSave whether save or not
  1139. */
  1140. pageSchema.statics.syncRevisionToHackmd = function(pageData, isSave = true) {
  1141. pageData.revisionHackmdSynced = pageData.revision;
  1142. pageData.hasDraftOnHackmd = false;
  1143. let returnData = pageData;
  1144. if (isSave) {
  1145. returnData = pageData.save();
  1146. }
  1147. return returnData;
  1148. };
  1149. /**
  1150. * update hasDraftOnHackmd
  1151. * !! This will be invoked many time from many people !!
  1152. *
  1153. * @param {Page} pageData
  1154. * @param {Boolean} newValue
  1155. */
  1156. pageSchema.statics.updateHasDraftOnHackmd = async function(pageData, newValue) {
  1157. if (pageData.hasDraftOnHackmd === newValue) {
  1158. // do nothing when hasDraftOnHackmd equals to newValue
  1159. return;
  1160. }
  1161. pageData.hasDraftOnHackmd = newValue;
  1162. return pageData.save();
  1163. };
  1164. pageSchema.statics.getHistories = function() {
  1165. // TODO
  1166. };
  1167. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  1168. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  1169. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  1170. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  1171. pageSchema.statics.GRANT_USER_GROUP = GRANT_USER_GROUP;
  1172. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  1173. pageSchema.statics.PageQueryBuilder = PageQueryBuilder;
  1174. return mongoose.model('Page', pageSchema);
  1175. };