page.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. var pathCondition = [];
  523. var includeDeletedPage = option.includeDeletedPage || false
  524. if (!option) {
  525. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  526. }
  527. var opt = {
  528. sort: option.sort || 'updatedAt',
  529. desc: option.desc || -1,
  530. offset: option.offset || 0,
  531. limit: option.limit || 50
  532. };
  533. var sortOpt = {};
  534. sortOpt[opt.sort] = opt.desc;
  535. var queryReg = new RegExp('^' + path);
  536. var sliceOption = option.revisionSlice || {$slice: 1};
  537. pathCondition.push({path: queryReg});
  538. if (path.match(/\/$/)) {
  539. debug('Page list by ending with /, so find also upper level page');
  540. pathCondition.push({path: path.substr(0, path.length -1)});
  541. }
  542. return new Promise(function(resolve, reject) {
  543. // FIXME: might be heavy
  544. var q = Page.find({
  545. redirectTo: null,
  546. $or: [
  547. {grant: null},
  548. {grant: GRANT_PUBLIC},
  549. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  550. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  551. {grant: GRANT_OWNER, grantedUsers: userData._id},
  552. ],})
  553. .populate('revision')
  554. .and({
  555. $or: pathCondition
  556. })
  557. .sort(sortOpt)
  558. .skip(opt.offset)
  559. .limit(opt.limit);
  560. if (!includeDeletedPage) {
  561. q.and({
  562. $or: [
  563. {status: null},
  564. {status: STATUS_PUBLISHED},
  565. ],
  566. });
  567. }
  568. q.exec()
  569. .then(function(pages) {
  570. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  571. .then(resolve)
  572. .catch(reject);
  573. })
  574. });
  575. };
  576. pageSchema.statics.updatePageProperty = function(page, updateData) {
  577. var Page = this;
  578. return new Promise(function(resolve, reject) {
  579. // TODO foreach して save
  580. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  581. if (err) {
  582. return reject(err);
  583. }
  584. return resolve(data);
  585. });
  586. });
  587. };
  588. pageSchema.statics.updateGrant = function(page, grant, userData) {
  589. var Page = this;
  590. return new Promise(function(resolve, reject) {
  591. page.grant = grant;
  592. if (grant == GRANT_PUBLIC) {
  593. page.grantedUsers = [];
  594. } else {
  595. page.grantedUsers = [];
  596. page.grantedUsers.push(userData._id);
  597. }
  598. page.save(function(err, data) {
  599. debug('Page.updateGrant, saved grantedUsers.', err, data);
  600. if (err) {
  601. return reject(err);
  602. }
  603. return resolve(data);
  604. });
  605. });
  606. };
  607. // Instance method でいいのでは
  608. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  609. return new Promise(function(resolve, reject) {
  610. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  611. page.grantedUsers = [];
  612. }
  613. page.grantedUsers.push(userData);
  614. page.save(function(err, data) {
  615. if (err) {
  616. return reject(err);
  617. }
  618. return resolve(data);
  619. });
  620. });
  621. };
  622. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  623. var isCreate = false;
  624. if (pageData.revision === undefined) {
  625. debug('pushRevision on Create');
  626. isCreate = true;
  627. }
  628. return new Promise(function(resolve, reject) {
  629. newRevision.save(function(err, newRevision) {
  630. if (err) {
  631. debug('Error on saving revision', err);
  632. return reject(err);
  633. }
  634. debug('Successfully saved new revision', newRevision);
  635. pageData.revision = newRevision;
  636. pageData.lastUpdateUser = user;
  637. pageData.updatedAt = Date.now();
  638. pageData.save(function(err, data) {
  639. if (err) {
  640. // todo: remove new revision?
  641. debug('Error on save page data (after push revision)', err);
  642. return reject(err);
  643. }
  644. resolve(data);
  645. if (!isCreate) {
  646. debug('pushRevision on Update');
  647. }
  648. });
  649. });
  650. });
  651. };
  652. pageSchema.statics.create = function(path, body, user, options) {
  653. var Page = this
  654. , Revision = crowi.model('Revision')
  655. , format = options.format || 'markdown'
  656. , grant = options.grant || GRANT_PUBLIC
  657. , redirectTo = options.redirectTo || null;
  658. // force public
  659. if (isPortalPath(path)) {
  660. grant = GRANT_PUBLIC;
  661. }
  662. return new Promise(function(resolve, reject) {
  663. Page.findOne({path: path}, function(err, pageData) {
  664. if (pageData) {
  665. return reject(new Error('Cannot create new page to existed path'));
  666. }
  667. var newPage = new Page();
  668. newPage.path = path;
  669. newPage.creator = user;
  670. newPage.lastUpdateUser = user;
  671. newPage.createdAt = Date.now();
  672. newPage.updatedAt = Date.now();
  673. newPage.redirectTo = redirectTo;
  674. newPage.grant = grant;
  675. newPage.status = STATUS_PUBLISHED;
  676. newPage.grantedUsers = [];
  677. newPage.grantedUsers.push(user);
  678. newPage.save(function (err, newPage) {
  679. if (err) {
  680. return reject(err);
  681. }
  682. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  683. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  684. resolve(data);
  685. pageEvent.emit('create', data, user);
  686. }).catch(function(err) {
  687. debug('Push Revision Error on create page', err);
  688. return reject(err);
  689. });
  690. });
  691. });
  692. });
  693. };
  694. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  695. var Page = this
  696. , Revision = crowi.model('Revision')
  697. , grant = options.grant || null
  698. ;
  699. // update existing page
  700. var newRevision = Revision.prepareRevision(pageData, body, user);
  701. return new Promise(function(resolve, reject) {
  702. Page.pushRevision(pageData, newRevision, user)
  703. .then(function(revision) {
  704. if (grant != pageData.grant) {
  705. return Page.updateGrant(pageData, grant, user).then(function(data) {
  706. debug('Page grant update:', data);
  707. resolve(data);
  708. pageEvent.emit('update', data, user);
  709. });
  710. } else {
  711. resolve(pageData);
  712. pageEvent.emit('update', pageData, user);
  713. }
  714. }).catch(function(err) {
  715. debug('Error on update', err);
  716. debug('Error on update', err.stack);
  717. });
  718. });
  719. };
  720. pageSchema.statics.deletePage = function(pageData, user, options) {
  721. var Page = this
  722. , newPath = Page.getDeletedPageName(pageData.path)
  723. ;
  724. if (Page.isDeletableName(pageData.path)) {
  725. return new Promise(function(resolve, reject) {
  726. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  727. .then(function(data) {
  728. pageData.status = STATUS_DELETED;
  729. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  730. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  731. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  732. debug('Deleted the page, and rename it', pageData.path, newPath);
  733. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  734. }).then(function(pageData) {
  735. resolve(pageData);
  736. }).catch(reject);
  737. });
  738. } else {
  739. return Promise.reject('Page is not deletable.');
  740. }
  741. };
  742. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  743. var Page = this
  744. , newPath = Page.getRevertDeletedPageName(pageData.path)
  745. ;
  746. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  747. // そのため、そいつは削除してOK
  748. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  749. return new Promise(function(resolve, reject) {
  750. Page.findPageByPath(newPath)
  751. .then(function(originPageData) {
  752. if (originPageData.redirectTo !== pageData.path) {
  753. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  754. }
  755. return Page.completelyDeletePage(originPageData);
  756. }).then(function(done) {
  757. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  758. }).then(function(done) {
  759. pageData.status = STATUS_PUBLISHED;
  760. debug('Revert deleted the page, and rename again it', pageData, newPath);
  761. return Page.rename(pageData, newPath, user, {})
  762. }).then(function(done) {
  763. pageData.path = newPath;
  764. resolve(pageData);
  765. }).catch(reject);
  766. });
  767. };
  768. /**
  769. * This is danger.
  770. */
  771. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  772. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  773. var Bookmark = crowi.model('Bookmark')
  774. , Attachment = crowi.model('Attachment')
  775. , Comment = crowi.model('Comment')
  776. , Revision = crowi.model('Revision')
  777. , Page = this
  778. , pageId = pageData._id
  779. ;
  780. debug('Completely delete', pageData.path);
  781. return new Promise(function(resolve, reject) {
  782. Bookmark.removeBookmarksByPageId(pageId)
  783. .then(function(done) {
  784. }).then(function(done) {
  785. return Attachment.removeAttachmentsByPageId(pageId);
  786. }).then(function(done) {
  787. return Comment.removeCommentsByPageId(pageId);
  788. }).then(function(done) {
  789. return Revision.removeRevisionsByPath(pageData.path);
  790. }).then(function(done) {
  791. return Page.removePageById(pageId);
  792. }).then(function(done) {
  793. return Page.removeRedirectOriginPageByPath(pageData.path);
  794. }).then(function(done) {
  795. pageEvent.emit('delete', pageData, user); // update as renamed page
  796. resolve(pageData);
  797. }).catch(reject);
  798. });
  799. };
  800. pageSchema.statics.removePageById = function(pageId) {
  801. var Page = this;
  802. return new Promise(function(resolve, reject) {
  803. Page.remove({_id: pageId}, function(err, done) {
  804. debug('Remove phisiaclly, the page', pageId, err, done);
  805. if (err) {
  806. return reject(err);
  807. }
  808. resolve(done);
  809. });
  810. });
  811. };
  812. pageSchema.statics.removePageByPath = function(pagePath) {
  813. var Page = this;
  814. return Page.findPageByPath(redirectPath)
  815. .then(function(pageData) {
  816. return Page.removePageById(pageData.id);
  817. });
  818. };
  819. /**
  820. * remove the page that is redirecting to specified `pagePath` recursively
  821. * ex: when
  822. * '/page1' redirects to '/page2' and
  823. * '/page2' redirects to '/page3'
  824. * and given '/page3',
  825. * '/page1' and '/page2' will be removed
  826. *
  827. * @param {string} pagePath
  828. */
  829. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  830. var Page = this;
  831. return Page.findPageByRedirectTo(pagePath)
  832. .then((redirectOriginPageData) => {
  833. // remove
  834. return Page.removePageById(redirectOriginPageData.id)
  835. // remove recursive
  836. .then(() => {
  837. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  838. });
  839. })
  840. .catch((err) => {
  841. // do nothing if origin page doesn't exist
  842. return Promise.resolve();
  843. })
  844. };
  845. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  846. var Page = this
  847. , Revision = crowi.model('Revision')
  848. , path = pageData.path
  849. , createRedirectPage = options.createRedirectPage || 0
  850. , moveUnderTrees = options.moveUnderTrees || 0;
  851. return new Promise(function(resolve, reject) {
  852. // pageData の path を変更
  853. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  854. .then(function(data) {
  855. // reivisions の path を変更
  856. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  857. }).then(function(data) {
  858. pageData.path = newPagePath;
  859. if (createRedirectPage) {
  860. var body = 'redirect ' + newPagePath;
  861. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  862. } else {
  863. resolve(data);
  864. }
  865. pageEvent.emit('update', pageData, user); // update as renamed page
  866. });
  867. });
  868. };
  869. pageSchema.statics.getHistories = function() {
  870. // TODO
  871. return;
  872. };
  873. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  874. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  875. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  876. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  877. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  878. return mongoose.model('Page', pageSchema);
  879. };