page.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. module.exports = function(crowi) {
  2. var debug = require('debug')('crowi:models:page')
  3. , mongoose = require('mongoose')
  4. , ObjectId = mongoose.Schema.Types.ObjectId
  5. , GRANT_PUBLIC = 1
  6. , GRANT_RESTRICTED = 2
  7. , GRANT_SPECIFIED = 3
  8. , GRANT_OWNER = 4
  9. , PAGE_GRANT_ERROR = 1
  10. , STATUS_WIP = 'wip'
  11. , STATUS_PUBLISHED = 'published'
  12. , STATUS_DELETED = 'deleted'
  13. , STATUS_DEPRECATED = 'deprecated'
  14. , pageEvent = crowi.event('page')
  15. , pageSchema;
  16. function isPortalPath(path) {
  17. if (path.match(/.*\/$/)) {
  18. return true;
  19. }
  20. return false;
  21. }
  22. pageSchema = new mongoose.Schema({
  23. path: { type: String, required: true, index: true, unique: true },
  24. revision: { type: ObjectId, ref: 'Revision' },
  25. redirectTo: { type: String, index: true },
  26. status: { type: String, default: STATUS_PUBLISHED, index: true },
  27. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  28. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  29. creator: { type: ObjectId, ref: 'User', index: true },
  30. // lastUpdateUser: this schema is from 1.5.x (by deletion feature), and null is default.
  31. // the last update user on the screen is by revesion.author for B.C.
  32. lastUpdateUser: { type: ObjectId, ref: 'User', index: true },
  33. liker: [{ type: ObjectId, ref: 'User', index: true }],
  34. seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
  35. commentCount: { type: Number, default: 0 },
  36. extended: {
  37. type: String,
  38. default: '{}',
  39. get: function(data) {
  40. try {
  41. return JSON.parse(data);
  42. } catch(e) {
  43. return data;
  44. }
  45. },
  46. set: function(data) {
  47. return JSON.stringify(data);
  48. }
  49. },
  50. createdAt: { type: Date, default: Date.now },
  51. updatedAt: Date
  52. }, {
  53. toJSON: {getters: true},
  54. toObject: {getters: true}
  55. });
  56. pageEvent.on('create', pageEvent.onCreate);
  57. pageEvent.on('update', pageEvent.onUpdate);
  58. pageSchema.methods.isWIP = function() {
  59. return this.status === STATUS_WIP;
  60. };
  61. pageSchema.methods.isPublished = function() {
  62. // null: this is for B.C.
  63. return this.status === null || this.status === STATUS_PUBLISHED;
  64. };
  65. pageSchema.methods.isDeleted = function() {
  66. return this.status === STATUS_DELETED;
  67. };
  68. pageSchema.methods.isDeprecated = function() {
  69. return this.status === STATUS_DEPRECATED;
  70. };
  71. pageSchema.methods.isPublic = function() {
  72. if (!this.grant || this.grant == GRANT_PUBLIC) {
  73. return true;
  74. }
  75. return false;
  76. };
  77. pageSchema.methods.isPortal = function() {
  78. return isPortalPath(this.path);
  79. };
  80. pageSchema.methods.isCreator = function(userData) {
  81. if (this.populated('creator') && this.creator._id.toString() === userData._id.toString()) {
  82. return true;
  83. } else if (this.creator.toString() === userData._id.toString()) {
  84. return true
  85. }
  86. return false;
  87. };
  88. pageSchema.methods.isGrantedFor = function(userData) {
  89. if (this.isPublic() || this.isCreator(userData)) {
  90. return true;
  91. }
  92. if (this.grantedUsers.indexOf(userData._id) >= 0) {
  93. return true;
  94. }
  95. return false;
  96. };
  97. pageSchema.methods.isLatestRevision = function() {
  98. // populate されていなくて判断できない
  99. if (!this.latestRevision || !this.revision) {
  100. return true;
  101. }
  102. return (this.latestRevision == this.revision._id.toString());
  103. };
  104. pageSchema.methods.isUpdatable = function(previousRevision) {
  105. var revision = this.latestRevision || this.revision;
  106. if (revision != previousRevision) {
  107. return false;
  108. }
  109. return true;
  110. };
  111. pageSchema.methods.isLiked = function(userData) {
  112. return this.liker.some(function(likedUser) {
  113. return likedUser == userData._id.toString();
  114. });
  115. };
  116. pageSchema.methods.like = function(userData) {
  117. var self = this,
  118. Page = self;
  119. return new Promise(function(resolve, reject) {
  120. var added = self.liker.addToSet(userData._id);
  121. if (added.length > 0) {
  122. self.save(function(err, data) {
  123. if (err) {
  124. return reject(err);
  125. }
  126. debug('liker updated!', added);
  127. return resolve(data);
  128. });
  129. } else {
  130. debug('liker not updated');
  131. return reject(self);
  132. }
  133. });
  134. };
  135. pageSchema.methods.unlike = function(userData, callback) {
  136. var self = this,
  137. Page = self;
  138. return new Promise(function(resolve, reject) {
  139. var beforeCount = self.liker.length;
  140. self.liker.pull(userData._id);
  141. if (self.liker.length != beforeCount) {
  142. self.save(function(err, data) {
  143. if (err) {
  144. return reject(err);
  145. }
  146. return resolve(data);
  147. });
  148. } else {
  149. debug('liker not updated');
  150. return reject(self);
  151. }
  152. });
  153. };
  154. pageSchema.methods.isSeenUser = function(userData) {
  155. var self = this,
  156. Page = self;
  157. return this.seenUsers.some(function(seenUser) {
  158. return seenUser.equals(userData._id);
  159. });
  160. };
  161. pageSchema.methods.seen = function(userData) {
  162. var self = this,
  163. Page = self;
  164. if (this.isSeenUser(userData)) {
  165. debug('seenUsers not updated');
  166. return Promise.resolve(this);
  167. }
  168. return new Promise(function(resolve, reject) {
  169. if (!userData || !userData._id) {
  170. reject(new Error('User data is not valid'));
  171. }
  172. var added = self.seenUsers.addToSet(userData);
  173. self.save(function(err, data) {
  174. if (err) {
  175. return reject(err);
  176. }
  177. debug('seenUsers updated!', added);
  178. return resolve(self);
  179. });
  180. });
  181. };
  182. pageSchema.methods.getSlackChannel = function() {
  183. var extended = this.get('extended');
  184. if (!extended) {
  185. return '';
  186. }
  187. return extended.slack || '';
  188. };
  189. pageSchema.methods.updateSlackChannel = function(slackChannel) {
  190. var extended = this.extended;
  191. extended.slack = slackChannel;
  192. return this.updateExtended(extended);
  193. };
  194. pageSchema.methods.updateExtended = function(extended) {
  195. var page = this;
  196. page.extended = extended;
  197. return new Promise(function(resolve, reject) {
  198. return page.save(function(err, doc) {
  199. if (err) {
  200. return reject(err);
  201. }
  202. return resolve(doc);
  203. });
  204. });
  205. };
  206. pageSchema.statics.populatePageData = function(pageData, revisionId) {
  207. var Page = crowi.model('Page');
  208. var User = crowi.model('User');
  209. pageData.latestRevision = pageData.revision;
  210. if (revisionId) {
  211. pageData.revision = revisionId;
  212. }
  213. pageData.likerCount = pageData.liker.length || 0;
  214. pageData.seenUsersCount = pageData.seenUsers.length || 0;
  215. return new Promise(function(resolve, reject) {
  216. pageData.populate([
  217. {path: 'lastUpdateUser', model: 'User', select: User.USER_PUBLIC_FIELDS},
  218. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  219. {path: 'revision', model: 'Revision'},
  220. //{path: 'liker', options: { limit: 11 }},
  221. //{path: 'seenUsers', options: { limit: 11 }},
  222. ], function (err, pageData) {
  223. Page.populate(pageData, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  224. if (err) {
  225. return reject(err);
  226. }
  227. return resolve(data);
  228. });
  229. });
  230. });
  231. };
  232. pageSchema.statics.populatePageListToAnyObjects = function(pageIdObjectArray) {
  233. var Page = this;
  234. var pageIdMappings = {};
  235. var pageIds = pageIdObjectArray.map(function(page, idx) {
  236. if (!page._id) {
  237. throw new Error('Pass the arg of populatePageListToAnyObjects() must have _id on each element.');
  238. }
  239. pageIdMappings[String(page._id)] = idx;
  240. return page._id;
  241. });
  242. return new Promise(function(resolve, reject) {
  243. Page.findListByPageIds(pageIds, {limit: 100}) // limit => if the pagIds is greater than 100, ignore
  244. .then(function(pages) {
  245. pages.forEach(function(page) {
  246. Object.assign(pageIdObjectArray[pageIdMappings[String(page._id)]], page._doc);
  247. });
  248. resolve(pageIdObjectArray);
  249. });
  250. });
  251. };
  252. pageSchema.statics.updateCommentCount = function (page, num)
  253. {
  254. var self = this;
  255. return new Promise(function(resolve, reject) {
  256. self.update({_id: page}, {commentCount: num}, {}, function(err, data) {
  257. if (err) {
  258. debug('Update commentCount Error', err);
  259. return reject(err);
  260. }
  261. return resolve(data);
  262. });
  263. });
  264. };
  265. pageSchema.statics.hasPortalPage = function (path, user, revisionId) {
  266. var self = this;
  267. return new Promise(function(resolve, reject) {
  268. self.findPage(path, user, revisionId)
  269. .then(function(page) {
  270. resolve(page);
  271. }).catch(function(err) {
  272. resolve(null); // check only has portal page, through error
  273. });
  274. });
  275. };
  276. pageSchema.statics.getGrantLabels = function() {
  277. var grantLabels = {};
  278. grantLabels[GRANT_PUBLIC] = 'Public'; // 公開
  279. grantLabels[GRANT_RESTRICTED] = 'Anyone with the link'; // リンクを知っている人のみ
  280. //grantLabels[GRANT_SPECIFIED] = 'Specified users only'; // 特定ユーザーのみ
  281. grantLabels[GRANT_OWNER] = 'Just me'; // 自分のみ
  282. return grantLabels;
  283. };
  284. pageSchema.statics.normalizePath = function(path) {
  285. if (!path.match(/^\//)) {
  286. path = '/' + path;
  287. }
  288. path = path.replace(/\/\s+?/g, '/').replace(/\s+\//g, '/');
  289. return path;
  290. };
  291. pageSchema.statics.getUserPagePath = function(user) {
  292. return '/user/' + user.username;
  293. };
  294. pageSchema.statics.getDeletedPageName = function(path) {
  295. if (path.match('\/')) {
  296. path = path.substr(1);
  297. }
  298. return '/trash/' + path;
  299. };
  300. pageSchema.statics.getRevertDeletedPageName = function(path) {
  301. return path.replace('\/trash', '');
  302. };
  303. pageSchema.statics.isDeletableName = function(path) {
  304. var notDeletable = [
  305. /^\/user\/[^\/]+$/, // user page
  306. ];
  307. for (var i = 0; i < notDeletable.length; i++) {
  308. var pattern = notDeletable[i];
  309. if (path.match(pattern)) {
  310. return false;
  311. }
  312. }
  313. return true;
  314. };
  315. pageSchema.statics.isCreatableName = function(name) {
  316. var forbiddenPages = [
  317. /\^|\$|\*|\+|\#/,
  318. /^\/_.*/, // /_api/* and so on
  319. /^\/\-\/.*/,
  320. /^\/_r\/.*/,
  321. /^\/user\/[^\/]+\/(bookmarks|comments|activities|pages|recent-create|recent-edit)/, // reserved
  322. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  323. /\/{2,}/, // avoid miss in renaming
  324. /\s+\/\s+/, // avoid miss in renaming
  325. /.+\/edit$/,
  326. /.+\.md$/,
  327. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments)(\/.*|$)/,
  328. ];
  329. var isCreatable = true;
  330. forbiddenPages.forEach(function(page) {
  331. var pageNameReg = new RegExp(page);
  332. if (name.match(pageNameReg)) {
  333. isCreatable = false;
  334. return ;
  335. }
  336. });
  337. return isCreatable;
  338. };
  339. pageSchema.statics.fixToCreatableName = function(path) {
  340. return path
  341. .replace(/\/\//g, '/')
  342. ;
  343. };
  344. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  345. this.update({_id: pageId}, {revision: revisionId}, {}, function(err, data) {
  346. cb(err, data);
  347. });
  348. };
  349. pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
  350. this
  351. .find({})
  352. .sort({updatedAt: -1})
  353. .skip(offset)
  354. .limit(limit)
  355. .exec(function(err, data) {
  356. cb(err, data);
  357. });
  358. };
  359. pageSchema.statics.findPageById = function(id) {
  360. var Page = this;
  361. return new Promise(function(resolve, reject) {
  362. Page.findOne({_id: id}, function(err, pageData) {
  363. if (err) {
  364. return reject(err);
  365. }
  366. if (pageData == null) {
  367. return reject(new Error('Page not found'));
  368. }
  369. return Page.populatePageData(pageData, null).then(resolve);
  370. });
  371. });
  372. };
  373. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
  374. var Page = this;
  375. return new Promise(function(resolve, reject) {
  376. Page.findPageById(id)
  377. .then(function(pageData) {
  378. if (userData && !pageData.isGrantedFor(userData)) {
  379. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  380. }
  381. return resolve(pageData);
  382. }).catch(function(err) {
  383. return reject(err);
  384. });
  385. });
  386. };
  387. // find page and check if granted user
  388. pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
  389. var self = this;
  390. return new Promise(function(resolve, reject) {
  391. self.findOne({path: path}, function(err, pageData) {
  392. if (err) {
  393. return reject(err);
  394. }
  395. if (pageData === null) {
  396. if (ignoreNotFound) {
  397. return resolve(null);
  398. }
  399. var pageNotFoundError = new Error('Page Not Found')
  400. pageNotFoundError.name = 'Crowi:Page:NotFound';
  401. return reject(pageNotFoundError);
  402. }
  403. if (!pageData.isGrantedFor(userData)) {
  404. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  405. }
  406. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  407. });
  408. });
  409. };
  410. // find page by path
  411. pageSchema.statics.findPageByPath = function(path) {
  412. var Page = this;
  413. return new Promise(function(resolve, reject) {
  414. Page.findOne({path: path}, function(err, pageData) {
  415. if (err || pageData === null) {
  416. return reject(err);
  417. }
  418. return resolve(pageData);
  419. });
  420. });
  421. };
  422. pageSchema.statics.findListByPageIds = function(ids, options) {
  423. var Page = this;
  424. var User = crowi.model('User');
  425. var options = options || {}
  426. , limit = options.limit || 50
  427. , offset = options.skip || 0
  428. ;
  429. return new Promise(function(resolve, reject) {
  430. Page
  431. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  432. //.sort({createdAt: -1}) // TODO optionize
  433. .skip(offset)
  434. .limit(limit)
  435. .populate([
  436. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  437. {path: 'revision', model: 'Revision'},
  438. ])
  439. .exec(function(err, pages) {
  440. if (err) {
  441. return reject(err);
  442. }
  443. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  444. if (err) {
  445. return reject(err);
  446. }
  447. return resolve(data);
  448. });
  449. });
  450. });
  451. };
  452. pageSchema.statics.findPageByRedirectTo = function(path) {
  453. var Page = this;
  454. return new Promise(function(resolve, reject) {
  455. Page.findOne({redirectTo: path}, function(err, pageData) {
  456. if (err || pageData === null) {
  457. return reject(err);
  458. }
  459. return resolve(pageData);
  460. });
  461. });
  462. };
  463. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  464. var Page = this;
  465. var User = crowi.model('User');
  466. var limit = option.limit || 50;
  467. var offset = option.offset || 0;
  468. var conditions = {
  469. creator: user._id,
  470. redirectTo: null,
  471. $or: [
  472. {status: null},
  473. {status: STATUS_PUBLISHED},
  474. ],
  475. };
  476. if (!user.equals(currentUser._id)) {
  477. conditions.grant = GRANT_PUBLIC;
  478. }
  479. return new Promise(function(resolve, reject) {
  480. Page
  481. .find(conditions)
  482. .sort({createdAt: -1})
  483. .skip(offset)
  484. .limit(limit)
  485. .populate('revision')
  486. .exec()
  487. .then(function(pages) {
  488. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  489. });
  490. });
  491. };
  492. /**
  493. * Bulk get (for internal only)
  494. */
  495. pageSchema.statics.getStreamOfFindAll = function(options) {
  496. var Page = this
  497. , options = options || {}
  498. , publicOnly = options.publicOnly || true
  499. , criteria = {redirectTo: null,}
  500. ;
  501. if (publicOnly) {
  502. criteria.grant = GRANT_PUBLIC;
  503. }
  504. return this.find(criteria)
  505. .populate([
  506. {path: 'creator', model: 'User'},
  507. {path: 'revision', model: 'Revision'},
  508. ])
  509. .sort({updatedAt: -1})
  510. .cursor();
  511. };
  512. /**
  513. * findListByStartWith
  514. *
  515. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  516. * If `path` doesn't have `/` at the end, returns '{path}*'
  517. * e.g.
  518. */
  519. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  520. var Page = this;
  521. var User = crowi.model('User');
  522. if (!option) {
  523. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  524. }
  525. var opt = {
  526. sort: option.sort || 'updatedAt',
  527. desc: option.desc || -1,
  528. offset: option.offset || 0,
  529. limit: option.limit || 50
  530. };
  531. var sortOpt = {};
  532. sortOpt[opt.sort] = opt.desc;
  533. var isPopulateRevisionBody = option.isPopulateRevisionBody || false;
  534. return new Promise(function(resolve, reject) {
  535. var q = Page.generateQueryToListByStartWith(path, userData, option)
  536. .sort(sortOpt)
  537. .skip(opt.offset)
  538. .limit(opt.limit);
  539. // retrieve revision data
  540. if (isPopulateRevisionBody) {
  541. q = q.populate('revision');
  542. }
  543. else {
  544. q = q.populate('revision', '-body'); // exclude body
  545. }
  546. q.exec()
  547. .then(function(pages) {
  548. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  549. .then(resolve)
  550. .catch(reject);
  551. })
  552. });
  553. };
  554. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  555. var Page = this;
  556. var pathCondition = [];
  557. var includeDeletedPage = option.includeDeletedPage || false;
  558. var queryReg = new RegExp('^' + path);
  559. pathCondition.push({path: queryReg});
  560. if (path.match(/\/$/)) {
  561. debug('Page list by ending with /, so find also upper level page');
  562. pathCondition.push({path: path.substr(0, path.length -1)});
  563. }
  564. var q = Page.find({
  565. redirectTo: null,
  566. $or: [
  567. {grant: null},
  568. {grant: GRANT_PUBLIC},
  569. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  570. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  571. {grant: GRANT_OWNER, grantedUsers: userData._id},
  572. ],})
  573. .and({
  574. $or: pathCondition
  575. });
  576. if (!includeDeletedPage) {
  577. q.and({
  578. $or: [
  579. {status: null},
  580. {status: STATUS_PUBLISHED},
  581. ],
  582. });
  583. }
  584. return q;
  585. }
  586. pageSchema.statics.updatePageProperty = function(page, updateData) {
  587. var Page = this;
  588. return new Promise(function(resolve, reject) {
  589. // TODO foreach して save
  590. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  591. if (err) {
  592. return reject(err);
  593. }
  594. return resolve(data);
  595. });
  596. });
  597. };
  598. pageSchema.statics.updateGrant = function(page, grant, userData) {
  599. var Page = this;
  600. return new Promise(function(resolve, reject) {
  601. page.grant = grant;
  602. if (grant == GRANT_PUBLIC) {
  603. page.grantedUsers = [];
  604. } else {
  605. page.grantedUsers = [];
  606. page.grantedUsers.push(userData._id);
  607. }
  608. page.save(function(err, data) {
  609. debug('Page.updateGrant, saved grantedUsers.', err, data);
  610. if (err) {
  611. return reject(err);
  612. }
  613. return resolve(data);
  614. });
  615. });
  616. };
  617. // Instance method でいいのでは
  618. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  619. return new Promise(function(resolve, reject) {
  620. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  621. page.grantedUsers = [];
  622. }
  623. page.grantedUsers.push(userData);
  624. page.save(function(err, data) {
  625. if (err) {
  626. return reject(err);
  627. }
  628. return resolve(data);
  629. });
  630. });
  631. };
  632. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  633. var isCreate = false;
  634. if (pageData.revision === undefined) {
  635. debug('pushRevision on Create');
  636. isCreate = true;
  637. }
  638. return new Promise(function(resolve, reject) {
  639. newRevision.save(function(err, newRevision) {
  640. if (err) {
  641. debug('Error on saving revision', err);
  642. return reject(err);
  643. }
  644. debug('Successfully saved new revision', newRevision);
  645. pageData.revision = newRevision;
  646. pageData.lastUpdateUser = user;
  647. pageData.updatedAt = Date.now();
  648. pageData.save(function(err, data) {
  649. if (err) {
  650. // todo: remove new revision?
  651. debug('Error on save page data (after push revision)', err);
  652. return reject(err);
  653. }
  654. resolve(data);
  655. if (!isCreate) {
  656. debug('pushRevision on Update');
  657. }
  658. });
  659. });
  660. });
  661. };
  662. pageSchema.statics.create = function(path, body, user, options) {
  663. var Page = this
  664. , Revision = crowi.model('Revision')
  665. , format = options.format || 'markdown'
  666. , grant = options.grant || GRANT_PUBLIC
  667. , redirectTo = options.redirectTo || null;
  668. // force public
  669. if (isPortalPath(path)) {
  670. grant = GRANT_PUBLIC;
  671. }
  672. return new Promise(function(resolve, reject) {
  673. Page.findOne({path: path}, function(err, pageData) {
  674. if (pageData) {
  675. return reject(new Error('Cannot create new page to existed path'));
  676. }
  677. var newPage = new Page();
  678. newPage.path = path;
  679. newPage.creator = user;
  680. newPage.lastUpdateUser = user;
  681. newPage.createdAt = Date.now();
  682. newPage.updatedAt = Date.now();
  683. newPage.redirectTo = redirectTo;
  684. newPage.grant = grant;
  685. newPage.status = STATUS_PUBLISHED;
  686. newPage.grantedUsers = [];
  687. newPage.grantedUsers.push(user);
  688. newPage.save(function (err, newPage) {
  689. if (err) {
  690. return reject(err);
  691. }
  692. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  693. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  694. resolve(data);
  695. pageEvent.emit('create', data, user);
  696. }).catch(function(err) {
  697. debug('Push Revision Error on create page', err);
  698. return reject(err);
  699. });
  700. });
  701. });
  702. });
  703. };
  704. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  705. var Page = this
  706. , Revision = crowi.model('Revision')
  707. , grant = options.grant || null
  708. ;
  709. // update existing page
  710. var newRevision = Revision.prepareRevision(pageData, body, user);
  711. return new Promise(function(resolve, reject) {
  712. Page.pushRevision(pageData, newRevision, user)
  713. .then(function(revision) {
  714. if (grant != pageData.grant) {
  715. return Page.updateGrant(pageData, grant, user).then(function(data) {
  716. debug('Page grant update:', data);
  717. resolve(data);
  718. pageEvent.emit('update', data, user);
  719. });
  720. } else {
  721. resolve(pageData);
  722. pageEvent.emit('update', pageData, user);
  723. }
  724. }).catch(function(err) {
  725. debug('Error on update', err);
  726. debug('Error on update', err.stack);
  727. });
  728. });
  729. };
  730. pageSchema.statics.deletePage = function(pageData, user, options) {
  731. var Page = this
  732. , newPath = Page.getDeletedPageName(pageData.path)
  733. ;
  734. if (Page.isDeletableName(pageData.path)) {
  735. return new Promise(function(resolve, reject) {
  736. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  737. .then(function(data) {
  738. pageData.status = STATUS_DELETED;
  739. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  740. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  741. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  742. debug('Deleted the page, and rename it', pageData.path, newPath);
  743. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  744. }).then(function(pageData) {
  745. resolve(pageData);
  746. }).catch(reject);
  747. });
  748. } else {
  749. return Promise.reject('Page is not deletable.');
  750. }
  751. };
  752. pageSchema.statics.deletePageRecursively = function (pageData, user, options) {
  753. var Page = this
  754. , path = pageData.path
  755. , options = options || {}
  756. ;
  757. return new Promise(function (resolve, reject) {
  758. Page
  759. .generateQueryToListByStartWith(path, user, options)
  760. .then(function (pages) {
  761. Promise.all(pages.map(function (page) {
  762. return Page.deletePage(page, user, options);
  763. }))
  764. .then(function (data) {
  765. return resolve(pageData);
  766. });
  767. });
  768. });
  769. };
  770. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  771. var Page = this
  772. , newPath = Page.getRevertDeletedPageName(pageData.path)
  773. ;
  774. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  775. // そのため、そいつは削除してOK
  776. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  777. return new Promise(function(resolve, reject) {
  778. Page.findPageByPath(newPath)
  779. .then(function(originPageData) {
  780. if (originPageData.redirectTo !== pageData.path) {
  781. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  782. }
  783. return Page.completelyDeletePage(originPageData);
  784. }).then(function(done) {
  785. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  786. }).then(function(done) {
  787. pageData.status = STATUS_PUBLISHED;
  788. debug('Revert deleted the page, and rename again it', pageData, newPath);
  789. return Page.rename(pageData, newPath, user, {})
  790. }).then(function(done) {
  791. pageData.path = newPath;
  792. resolve(pageData);
  793. }).catch(reject);
  794. });
  795. };
  796. pageSchema.statics.revertDeletedPageRecursively = function (pageData, user, options) {
  797. var Page = this
  798. , path = pageData.path
  799. , options = options || { includeDeletedPage: true}
  800. ;
  801. return new Promise(function (resolve, reject) {
  802. Page
  803. .generateQueryToListByStartWith(path, user, options)
  804. .then(function (pages) {
  805. Promise.all(pages.map(function (page) {
  806. return Page.revertDeletedPage(page, user, options);
  807. }))
  808. .then(function (data) {
  809. return resolve(data[0]);
  810. });
  811. });
  812. });
  813. };
  814. /**
  815. * This is danger.
  816. */
  817. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  818. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  819. var Bookmark = crowi.model('Bookmark')
  820. , Attachment = crowi.model('Attachment')
  821. , Comment = crowi.model('Comment')
  822. , Revision = crowi.model('Revision')
  823. , Page = this
  824. , pageId = pageData._id
  825. ;
  826. debug('Completely delete', pageData.path);
  827. return new Promise(function(resolve, reject) {
  828. Bookmark.removeBookmarksByPageId(pageId)
  829. .then(function(done) {
  830. }).then(function(done) {
  831. return Attachment.removeAttachmentsByPageId(pageId);
  832. }).then(function(done) {
  833. return Comment.removeCommentsByPageId(pageId);
  834. }).then(function(done) {
  835. return Revision.removeRevisionsByPath(pageData.path);
  836. }).then(function(done) {
  837. return Page.removePageById(pageId);
  838. }).then(function(done) {
  839. return Page.removeRedirectOriginPageByPath(pageData.path);
  840. }).then(function(done) {
  841. pageEvent.emit('delete', pageData, user); // update as renamed page
  842. resolve(pageData);
  843. }).catch(reject);
  844. });
  845. };
  846. pageSchema.statics.completelyDeletePageRecursively = function (pageData, user, options) {
  847. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  848. var Page = this
  849. , path = pageData.path
  850. , options = options || { includeDeletedPage: true }
  851. ;
  852. return new Promise(function (resolve, reject) {
  853. Page
  854. .generateQueryToListByStartWith(path, user, options)
  855. .then(function (pages) {
  856. Promise.all(pages.map(function (page) {
  857. return Page.completelyDeletePage(page, user, options);
  858. }))
  859. .then(function (data) {
  860. return resolve(data[0]);
  861. });
  862. });
  863. });
  864. };
  865. pageSchema.statics.removePageById = function(pageId) {
  866. var Page = this;
  867. return new Promise(function(resolve, reject) {
  868. Page.remove({_id: pageId}, function(err, done) {
  869. debug('Remove phisiaclly, the page', pageId, err, done);
  870. if (err) {
  871. return reject(err);
  872. }
  873. resolve(done);
  874. });
  875. });
  876. };
  877. pageSchema.statics.removePageByPath = function(pagePath) {
  878. var Page = this;
  879. return Page.findPageByPath(pagePath)
  880. .then(function(pageData) {
  881. return Page.removePageById(pageData.id);
  882. });
  883. };
  884. /**
  885. * remove the page that is redirecting to specified `pagePath` recursively
  886. * ex: when
  887. * '/page1' redirects to '/page2' and
  888. * '/page2' redirects to '/page3'
  889. * and given '/page3',
  890. * '/page1' and '/page2' will be removed
  891. *
  892. * @param {string} pagePath
  893. */
  894. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  895. var Page = this;
  896. return Page.findPageByRedirectTo(pagePath)
  897. .then((redirectOriginPageData) => {
  898. // remove
  899. return Page.removePageById(redirectOriginPageData.id)
  900. // remove recursive
  901. .then(() => {
  902. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  903. });
  904. })
  905. .catch((err) => {
  906. // do nothing if origin page doesn't exist
  907. return Promise.resolve();
  908. })
  909. };
  910. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  911. var Page = this
  912. , Revision = crowi.model('Revision')
  913. , path = pageData.path
  914. , createRedirectPage = options.createRedirectPage || 0
  915. , moveUnderTrees = options.moveUnderTrees || 0;
  916. return new Promise(function(resolve, reject) {
  917. // pageData の path を変更
  918. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  919. .then(function(data) {
  920. // reivisions の path を変更
  921. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  922. }).then(function(data) {
  923. pageData.path = newPagePath;
  924. if (createRedirectPage) {
  925. var body = 'redirect ' + newPagePath;
  926. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  927. } else {
  928. resolve(data);
  929. }
  930. pageEvent.emit('update', pageData, user); // update as renamed page
  931. });
  932. });
  933. };
  934. pageSchema.statics.renameRecursively = function(pageData, newPagePathPrefix, user, options) {
  935. var Page = this
  936. , path = pageData.path
  937. , pathRegExp = new RegExp('^' + path, 'i');
  938. return new Promise(function(resolve, reject) {
  939. Page
  940. .generateQueryToListByStartWith(path, user, options)
  941. .then(function(pages) {
  942. Promise.all(pages.map(function(page) {
  943. newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
  944. return Page.rename(page, newPagePath, user, options);
  945. }))
  946. .then(function() {
  947. pageData.path = newPagePathPrefix;
  948. return resolve();
  949. });
  950. });
  951. });
  952. };
  953. pageSchema.statics.getHistories = function() {
  954. // TODO
  955. return;
  956. };
  957. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  958. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  959. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  960. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  961. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  962. return mongoose.model('Page', pageSchema);
  963. };