page.js 32 KB

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