page.js 42 KB

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