page.js 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. return path;
  289. };
  290. pageSchema.statics.getUserPagePath = function(user) {
  291. return '/user/' + user.username;
  292. };
  293. pageSchema.statics.getDeletedPageName = function(path) {
  294. if (path.match('\/')) {
  295. path = path.substr(1);
  296. }
  297. return '/trash/' + path;
  298. };
  299. pageSchema.statics.getRevertDeletedPageName = function(path) {
  300. return path.replace('\/trash', '');
  301. };
  302. pageSchema.statics.isDeletableName = function(path) {
  303. var notDeletable = [
  304. /^\/user\/[^\/]+$/, // user page
  305. ];
  306. for (var i = 0; i < notDeletable.length; i++) {
  307. var pattern = notDeletable[i];
  308. if (path.match(pattern)) {
  309. return false;
  310. }
  311. }
  312. return true;
  313. };
  314. pageSchema.statics.isCreatableName = function(name) {
  315. var forbiddenPages = [
  316. /\^|\$|\*|\+|\#/,
  317. /^\/_.*/, // /_api/* and so on
  318. /^\/\-\/.*/,
  319. /^\/_r\/.*/,
  320. /^\/user\/[^\/]+\/(bookmarks|comments|activities|pages|recent-create|recent-edit)/, // reserved
  321. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  322. /\/{2,}/, // avoid miss in renaming
  323. /.+\/edit$/,
  324. /.+\.md$/,
  325. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments)(\/.*|$)/,
  326. ];
  327. var isCreatable = true;
  328. forbiddenPages.forEach(function(page) {
  329. var pageNameReg = new RegExp(page);
  330. if (name.match(pageNameReg)) {
  331. isCreatable = false;
  332. return ;
  333. }
  334. });
  335. return isCreatable;
  336. };
  337. pageSchema.statics.fixToCreatableName = function(path) {
  338. return path
  339. .replace(/\/\//g, '/')
  340. ;
  341. };
  342. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  343. this.update({_id: pageId}, {revision: revisionId}, {}, function(err, data) {
  344. cb(err, data);
  345. });
  346. };
  347. pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
  348. this
  349. .find({})
  350. .sort({updatedAt: -1})
  351. .skip(offset)
  352. .limit(limit)
  353. .exec(function(err, data) {
  354. cb(err, data);
  355. });
  356. };
  357. pageSchema.statics.findPageById = function(id) {
  358. var Page = this;
  359. return new Promise(function(resolve, reject) {
  360. Page.findOne({_id: id}, function(err, pageData) {
  361. if (err) {
  362. return reject(err);
  363. }
  364. if (pageData == null) {
  365. return reject(new Error('Page not found'));
  366. }
  367. return Page.populatePageData(pageData, null).then(resolve);
  368. });
  369. });
  370. };
  371. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
  372. var Page = this;
  373. return new Promise(function(resolve, reject) {
  374. Page.findPageById(id)
  375. .then(function(pageData) {
  376. if (userData && !pageData.isGrantedFor(userData)) {
  377. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  378. }
  379. return resolve(pageData);
  380. }).catch(function(err) {
  381. return reject(err);
  382. });
  383. });
  384. };
  385. // find page and check if granted user
  386. pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
  387. var self = this;
  388. return new Promise(function(resolve, reject) {
  389. self.findOne({path: path}, function(err, pageData) {
  390. if (err) {
  391. return reject(err);
  392. }
  393. if (pageData === null) {
  394. if (ignoreNotFound) {
  395. return resolve(null);
  396. }
  397. var pageNotFoundError = new Error('Page Not Found')
  398. pageNotFoundError.name = 'Crowi:Page:NotFound';
  399. return reject(pageNotFoundError);
  400. }
  401. if (!pageData.isGrantedFor(userData)) {
  402. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  403. }
  404. self.populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  405. });
  406. });
  407. };
  408. // find page by path
  409. pageSchema.statics.findPageByPath = function(path) {
  410. var Page = this;
  411. return new Promise(function(resolve, reject) {
  412. Page.findOne({path: path}, function(err, pageData) {
  413. if (err || pageData === null) {
  414. return reject(err);
  415. }
  416. return resolve(pageData);
  417. });
  418. });
  419. };
  420. pageSchema.statics.findListByPageIds = function(ids, options) {
  421. var Page = this;
  422. var User = crowi.model('User');
  423. var options = options || {}
  424. , limit = options.limit || 50
  425. , offset = options.skip || 0
  426. ;
  427. return new Promise(function(resolve, reject) {
  428. Page
  429. .find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
  430. //.sort({createdAt: -1}) // TODO optionize
  431. .skip(offset)
  432. .limit(limit)
  433. .populate([
  434. {path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS},
  435. {path: 'revision', model: 'Revision'},
  436. ])
  437. .exec(function(err, pages) {
  438. if (err) {
  439. return reject(err);
  440. }
  441. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  442. if (err) {
  443. return reject(err);
  444. }
  445. return resolve(data);
  446. });
  447. });
  448. });
  449. };
  450. pageSchema.statics.findPageByRedirectTo = function(path) {
  451. var Page = this;
  452. return new Promise(function(resolve, reject) {
  453. Page.findOne({redirectTo: path}, function(err, pageData) {
  454. if (err || pageData === null) {
  455. return reject(err);
  456. }
  457. return resolve(pageData);
  458. });
  459. });
  460. };
  461. pageSchema.statics.findListByCreator = function(user, option, currentUser) {
  462. var Page = this;
  463. var User = crowi.model('User');
  464. var limit = option.limit || 50;
  465. var offset = option.offset || 0;
  466. var conditions = { creator: user._id, redirectTo: null };
  467. if (!user.equals(currentUser._id)) {
  468. conditions.grant = GRANT_PUBLIC;
  469. }
  470. return new Promise(function(resolve, reject) {
  471. Page
  472. .find(conditions)
  473. .sort({createdAt: -1})
  474. .skip(offset)
  475. .limit(limit)
  476. .populate('revision')
  477. .exec()
  478. .then(function(pages) {
  479. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  480. });
  481. });
  482. };
  483. /**
  484. * Bulk get (for internal only)
  485. */
  486. pageSchema.statics.getStreamOfFindAll = function(options) {
  487. var Page = this
  488. , options = options || {}
  489. , publicOnly = options.publicOnly || true
  490. , criteria = {redirectTo: null,}
  491. ;
  492. if (publicOnly) {
  493. criteria.grant = GRANT_PUBLIC;
  494. }
  495. return this.find(criteria)
  496. .populate([
  497. {path: 'creator', model: 'User'},
  498. {path: 'revision', model: 'Revision'},
  499. ])
  500. .sort({updatedAt: -1})
  501. .cursor();
  502. };
  503. /**
  504. * findListByStartWith
  505. *
  506. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  507. * If `path` doesn't have `/` at the end, returns '{path}*'
  508. * e.g.
  509. */
  510. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  511. var Page = this;
  512. var User = crowi.model('User');
  513. if (!option) {
  514. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  515. }
  516. var opt = {
  517. sort: option.sort || 'updatedAt',
  518. desc: option.desc || -1,
  519. offset: option.offset || 0,
  520. limit: option.limit || 50
  521. };
  522. var sortOpt = {};
  523. sortOpt[opt.sort] = opt.desc;
  524. return new Promise(function(resolve, reject) {
  525. var q = Page.generateQueryToListByStartWith(path, userData, option)
  526. .populate('revision')
  527. .sort(sortOpt)
  528. .skip(opt.offset)
  529. .limit(opt.limit);
  530. q.exec()
  531. .then(function(pages) {
  532. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  533. .then(resolve)
  534. .catch(reject);
  535. })
  536. });
  537. };
  538. pageSchema.statics.generateQueryToListByStartWith = function(path, userData, option) {
  539. var Page = this;
  540. var pathCondition = [];
  541. var includeDeletedPage = option.includeDeletedPage || false;
  542. var queryReg = new RegExp('^' + path);
  543. pathCondition.push({path: queryReg});
  544. if (path.match(/\/$/)) {
  545. debug('Page list by ending with /, so find also upper level page');
  546. pathCondition.push({path: path.substr(0, path.length -1)});
  547. }
  548. var q = Page.find({
  549. redirectTo: null,
  550. $or: [
  551. {grant: null},
  552. {grant: GRANT_PUBLIC},
  553. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  554. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  555. {grant: GRANT_OWNER, grantedUsers: userData._id},
  556. ],})
  557. .and({
  558. $or: pathCondition
  559. });
  560. if (!includeDeletedPage) {
  561. q.and({
  562. $or: [
  563. {status: null},
  564. {status: STATUS_PUBLISHED},
  565. ],
  566. });
  567. }
  568. return q;
  569. }
  570. pageSchema.statics.updatePageProperty = function(page, updateData) {
  571. var Page = this;
  572. return new Promise(function(resolve, reject) {
  573. // TODO foreach して save
  574. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  575. if (err) {
  576. return reject(err);
  577. }
  578. return resolve(data);
  579. });
  580. });
  581. };
  582. pageSchema.statics.updateGrant = function(page, grant, userData) {
  583. var Page = this;
  584. return new Promise(function(resolve, reject) {
  585. page.grant = grant;
  586. if (grant == GRANT_PUBLIC) {
  587. page.grantedUsers = [];
  588. } else {
  589. page.grantedUsers = [];
  590. page.grantedUsers.push(userData._id);
  591. }
  592. page.save(function(err, data) {
  593. debug('Page.updateGrant, saved grantedUsers.', err, data);
  594. if (err) {
  595. return reject(err);
  596. }
  597. return resolve(data);
  598. });
  599. });
  600. };
  601. // Instance method でいいのでは
  602. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  603. return new Promise(function(resolve, reject) {
  604. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  605. page.grantedUsers = [];
  606. }
  607. page.grantedUsers.push(userData);
  608. page.save(function(err, data) {
  609. if (err) {
  610. return reject(err);
  611. }
  612. return resolve(data);
  613. });
  614. });
  615. };
  616. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  617. var isCreate = false;
  618. if (pageData.revision === undefined) {
  619. debug('pushRevision on Create');
  620. isCreate = true;
  621. }
  622. return new Promise(function(resolve, reject) {
  623. newRevision.save(function(err, newRevision) {
  624. if (err) {
  625. debug('Error on saving revision', err);
  626. return reject(err);
  627. }
  628. debug('Successfully saved new revision', newRevision);
  629. pageData.revision = newRevision;
  630. pageData.lastUpdateUser = user;
  631. pageData.updatedAt = Date.now();
  632. pageData.save(function(err, data) {
  633. if (err) {
  634. // todo: remove new revision?
  635. debug('Error on save page data (after push revision)', err);
  636. return reject(err);
  637. }
  638. resolve(data);
  639. if (!isCreate) {
  640. debug('pushRevision on Update');
  641. }
  642. });
  643. });
  644. });
  645. };
  646. pageSchema.statics.create = function(path, body, user, options) {
  647. var Page = this
  648. , Revision = crowi.model('Revision')
  649. , format = options.format || 'markdown'
  650. , grant = options.grant || GRANT_PUBLIC
  651. , redirectTo = options.redirectTo || null;
  652. // force public
  653. if (isPortalPath(path)) {
  654. grant = GRANT_PUBLIC;
  655. }
  656. return new Promise(function(resolve, reject) {
  657. Page.findOne({path: path}, function(err, pageData) {
  658. if (pageData) {
  659. return reject(new Error('Cannot create new page to existed path'));
  660. }
  661. var newPage = new Page();
  662. newPage.path = path;
  663. newPage.creator = user;
  664. newPage.lastUpdateUser = user;
  665. newPage.createdAt = Date.now();
  666. newPage.updatedAt = Date.now();
  667. newPage.redirectTo = redirectTo;
  668. newPage.grant = grant;
  669. newPage.status = STATUS_PUBLISHED;
  670. newPage.grantedUsers = [];
  671. newPage.grantedUsers.push(user);
  672. newPage.save(function (err, newPage) {
  673. if (err) {
  674. return reject(err);
  675. }
  676. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  677. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  678. resolve(data);
  679. pageEvent.emit('create', data, user);
  680. }).catch(function(err) {
  681. debug('Push Revision Error on create page', err);
  682. return reject(err);
  683. });
  684. });
  685. });
  686. });
  687. };
  688. pageSchema.statics.updatePage = function(pageData, body, user, options) {
  689. var Page = this
  690. , Revision = crowi.model('Revision')
  691. , grant = options.grant || null
  692. ;
  693. // update existing page
  694. var newRevision = Revision.prepareRevision(pageData, body, user);
  695. return new Promise(function(resolve, reject) {
  696. Page.pushRevision(pageData, newRevision, user)
  697. .then(function(revision) {
  698. if (grant != pageData.grant) {
  699. return Page.updateGrant(pageData, grant, user).then(function(data) {
  700. debug('Page grant update:', data);
  701. resolve(data);
  702. pageEvent.emit('update', data, user);
  703. });
  704. } else {
  705. resolve(pageData);
  706. pageEvent.emit('update', pageData, user);
  707. }
  708. }).catch(function(err) {
  709. debug('Error on update', err);
  710. debug('Error on update', err.stack);
  711. });
  712. });
  713. };
  714. pageSchema.statics.deletePage = function(pageData, user, options) {
  715. var Page = this
  716. , newPath = Page.getDeletedPageName(pageData.path)
  717. ;
  718. if (Page.isDeletableName(pageData.path)) {
  719. return new Promise(function(resolve, reject) {
  720. Page.updatePageProperty(pageData, {status: STATUS_DELETED, lastUpdateUser: user})
  721. .then(function(data) {
  722. pageData.status = STATUS_DELETED;
  723. // ページ名が /trash/ 以下に存在する場合、おかしなことになる
  724. // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
  725. // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
  726. debug('Deleted the page, and rename it', pageData.path, newPath);
  727. return Page.rename(pageData, newPath, user, {createRedirectPage: true})
  728. }).then(function(pageData) {
  729. resolve(pageData);
  730. }).catch(reject);
  731. });
  732. } else {
  733. return Promise.reject('Page is not deletable.');
  734. }
  735. };
  736. pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
  737. var Page = this
  738. , newPath = Page.getRevertDeletedPageName(pageData.path)
  739. ;
  740. // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
  741. // そのため、そいつは削除してOK
  742. // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
  743. return new Promise(function(resolve, reject) {
  744. Page.findPageByPath(newPath)
  745. .then(function(originPageData) {
  746. if (originPageData.redirectTo !== pageData.path) {
  747. throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.');
  748. }
  749. return Page.completelyDeletePage(originPageData);
  750. }).then(function(done) {
  751. return Page.updatePageProperty(pageData, {status: STATUS_PUBLISHED, lastUpdateUser: user})
  752. }).then(function(done) {
  753. pageData.status = STATUS_PUBLISHED;
  754. debug('Revert deleted the page, and rename again it', pageData, newPath);
  755. return Page.rename(pageData, newPath, user, {})
  756. }).then(function(done) {
  757. pageData.path = newPath;
  758. resolve(pageData);
  759. }).catch(reject);
  760. });
  761. };
  762. /**
  763. * This is danger.
  764. */
  765. pageSchema.statics.completelyDeletePage = function(pageData, user, options) {
  766. // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
  767. var Bookmark = crowi.model('Bookmark')
  768. , Attachment = crowi.model('Attachment')
  769. , Comment = crowi.model('Comment')
  770. , Revision = crowi.model('Revision')
  771. , Page = this
  772. , pageId = pageData._id
  773. ;
  774. debug('Completely delete', pageData.path);
  775. return new Promise(function(resolve, reject) {
  776. Bookmark.removeBookmarksByPageId(pageId)
  777. .then(function(done) {
  778. }).then(function(done) {
  779. return Attachment.removeAttachmentsByPageId(pageId);
  780. }).then(function(done) {
  781. return Comment.removeCommentsByPageId(pageId);
  782. }).then(function(done) {
  783. return Revision.removeRevisionsByPath(pageData.path);
  784. }).then(function(done) {
  785. return Page.removePageById(pageId);
  786. }).then(function(done) {
  787. pageEvent.emit('delete', pageData, user); // update as renamed page
  788. resolve();
  789. }).catch(reject);
  790. });
  791. };
  792. pageSchema.statics.removePageById = function(pageId) {
  793. var Page = this;
  794. return new Promise(function(resolve, reject) {
  795. Page.remove({_id: pageId}, function(err, done) {
  796. debug('Remove phisiaclly, the page', pageId, err, done);
  797. if (err) {
  798. return reject(err);
  799. }
  800. resolve(done);
  801. });
  802. });
  803. };
  804. pageSchema.statics.removePageByPath = function(pagePath) {
  805. var Page = this;
  806. return Page.findPageByPath(redirectPath)
  807. .then(function(pageData) {
  808. return Page.removePageById(pageData.id);
  809. });
  810. };
  811. /**
  812. * remove the page that is redirecting to specified `pagePath` recursively
  813. * ex: when
  814. * '/page1' redirects to '/page2' and
  815. * '/page2' redirects to '/page3'
  816. * and given '/page3',
  817. * '/page1' and '/page2' will be removed
  818. *
  819. * @param {string} pagePath
  820. */
  821. pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
  822. var Page = this;
  823. return Page.findPageByRedirectTo(pagePath)
  824. .then((redirectOriginPageData) => {
  825. // remove
  826. return Page.removePageById(redirectOriginPageData.id)
  827. // remove recursive
  828. .then(() => {
  829. return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
  830. });
  831. })
  832. .catch((err) => {
  833. // do nothing if origin page doesn't exist
  834. return Promise.resolve();
  835. })
  836. };
  837. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  838. var Page = this
  839. , Revision = crowi.model('Revision')
  840. , path = pageData.path
  841. , createRedirectPage = options.createRedirectPage || 0
  842. , moveUnderTrees = options.moveUnderTrees || 0;
  843. return new Promise(function(resolve, reject) {
  844. // pageData の path を変更
  845. Page.updatePageProperty(pageData, {updatedAt: Date.now(), path: newPagePath, lastUpdateUser: user})
  846. .then(function(data) {
  847. // reivisions の path を変更
  848. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  849. }).then(function(data) {
  850. pageData.path = newPagePath;
  851. if (createRedirectPage) {
  852. var body = 'redirect ' + newPagePath;
  853. Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  854. } else {
  855. resolve(data);
  856. }
  857. pageEvent.emit('update', pageData, user); // update as renamed page
  858. });
  859. });
  860. };
  861. pageSchema.statics.getHistories = function() {
  862. // TODO
  863. return;
  864. };
  865. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  866. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  867. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  868. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  869. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  870. return mongoose.model('Page', pageSchema);
  871. };