2
0

page.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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.revertDeletedPage = function(pageData, user, options) {
  753. var Page = this
  754. , newPath = Page.getRevertDeletedPageName(pageData.path)
  755. ;
  756. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  757. // そのため、そいつは削除してOK
  758. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  759. return new Promise(function(resolve, reject) {
  760. Page.findPageByPath(newPath)
  761. .then(function(originPageData) {
  762. if (originPageData.redirectTo !== pageData.path) {
  763. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  764. }
  765. return Page.completelyDeletePage(originPageData);
  766. }).then(function(done) {
  767. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  768. }).then(function(done) {
  769. pageData.status = STATUS_PUBLISHED;
  770. debug('Revert deleted the page, and rename again it', pageData, newPath);
  771. return Page.rename(pageData, newPath, user, {})
  772. }).then(function(done) {
  773. pageData.path = newPath;
  774. resolve(pageData);
  775. }).catch(reject);
  776. });
  777. };
  778. /**
  779. * This is danger.
  780. */
  781. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  782. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  783. var Bookmark = crowi.model('Bookmark')
  784. , Attachment = crowi.model('Attachment')
  785. , Comment = crowi.model('Comment')
  786. , Revision = crowi.model('Revision')
  787. , Page = this
  788. , pageId = pageData._id
  789. ;
  790. debug('Completely delete', pageData.path);
  791. return new Promise(function(resolve, reject) {
  792. Bookmark.removeBookmarksByPageId(pageId)
  793. .then(function(done) {
  794. }).then(function(done) {
  795. return Attachment.removeAttachmentsByPageId(pageId);
  796. }).then(function(done) {
  797. return Comment.removeCommentsByPageId(pageId);
  798. }).then(function(done) {
  799. return Revision.removeRevisionsByPath(pageData.path);
  800. }).then(function(done) {
  801. return Page.removePageById(pageId);
  802. }).then(function(done) {
  803. return Page.removeRedirectOriginPageByPath(pageData.path);
  804. }).then(function(done) {
  805. pageEvent.emit('delete', pageData, user); // update as renamed page
  806. resolve(pageData);
  807. }).catch(reject);
  808. });
  809. };
  810. pageSchema.statics.removePageById = function(pageId) {
  811. var Page = this;
  812. return new Promise(function(resolve, reject) {
  813. Page.remove({_id: pageId}, function(err, done) {
  814. debug('Remove phisiaclly, the page', pageId, err, done);
  815. if (err) {
  816. return reject(err);
  817. }
  818. resolve(done);
  819. });
  820. });
  821. };
  822. pageSchema.statics.removePageByPath = function(pagePath) {
  823. var Page = this;
  824. return Page.findPageByPath(pagePath)
  825. .then(function(pageData) {
  826. return Page.removePageById(pageData.id);
  827. });
  828. };
  829. /**
  830. * remove the page that is redirecting to specified `pagePath` recursively
  831. * ex: when
  832. * '/page1' redirects to '/page2' and
  833. * '/page2' redirects to '/page3'
  834. * and given '/page3',
  835. * '/page1' and '/page2' will be removed
  836. *
  837. * @param {string} pagePath
  838. */
  839. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  840. var Page = this;
  841. return Page.findPageByRedirectTo(pagePath)
  842. .then((redirectOriginPageData) => {
  843. // remove
  844. return Page.removePageById(redirectOriginPageData.id)
  845. // remove recursive
  846. .then(() => {
  847. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  848. });
  849. })
  850. .catch((err) => {
  851. // do nothing if origin page doesn't exist
  852. return Promise.resolve();
  853. })
  854. };
  855. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  856. var Page = this
  857. , Revision = crowi.model('Revision')
  858. , path = pageData.path
  859. , createRedirectPage = options.createRedirectPage || 0
  860. , moveUnderTrees = options.moveUnderTrees || 0;
  861. return new Promise(function(resolve, reject) {
  862. // pageData の path を変更
  863. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  864. .then(function(data) {
  865. // reivisions の path を変更
  866. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  867. }).then(function(data) {
  868. pageData.path = newPagePath;
  869. if (createRedirectPage) {
  870. var body = 'redirect ' + newPagePath;
  871. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  872. } else {
  873. resolve(data);
  874. }
  875. pageEvent.emit('update', pageData, user); // update as renamed page
  876. });
  877. });
  878. };
  879. pageSchema.statics.getHistories = function() {
  880. // TODO
  881. return;
  882. };
  883. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  884. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  885. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  886. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  887. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  888. return mongoose.model('Page', pageSchema);
  889. };