page.js 29 KB

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