page.js 29 KB

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