page.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. , pageSchema;
  11. function populatePageData(pageData, revisionId, callback) {
  12. var Page = crowi.model('Page');
  13. pageData.latestRevision = pageData.revision;
  14. if (revisionId) {
  15. pageData.revision = revisionId;
  16. }
  17. pageData.likerCount = pageData.liker.length || 0;
  18. pageData.seenUsersCount = pageData.seenUsers.length || 0;
  19. pageData.populate([
  20. {path: 'creator', model: 'User'},
  21. {path: 'revision', model: 'Revision'},
  22. {path: 'liker', options: { limit: 11 }},
  23. {path: 'seenUsers', options: { limit: 11 }},
  24. ], function (err, pageData) {
  25. Page.populate(pageData, {path: 'revision.author', model: 'User'}, callback);
  26. });
  27. }
  28. pageSchema = new mongoose.Schema({
  29. path: { type: String, required: true, index: true },
  30. revision: { type: ObjectId, ref: 'Revision' },
  31. redirectTo: { type: String, index: true },
  32. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  33. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  34. creator: { type: ObjectId, ref: 'User', index: true },
  35. liker: [{ type: ObjectId, ref: 'User', index: true }],
  36. seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
  37. createdAt: { type: Date, default: Date.now },
  38. updatedAt: Date
  39. });
  40. pageSchema.methods.isPublic = function() {
  41. if (!this.grant || this.grant == GRANT_PUBLIC) {
  42. return true;
  43. }
  44. return false;
  45. };
  46. pageSchema.methods.isCreator = function(userData) {
  47. if (this.populated('creator') && this.creator._id.toString() === userData._id.toString()) {
  48. return true;
  49. } else if (this.creator.toString() === userData._id.toString()) {
  50. return true
  51. }
  52. return false;
  53. };
  54. pageSchema.methods.isGrantedFor = function(userData) {
  55. if (this.isPublic() || this.isCreator(userData)) {
  56. return true;
  57. }
  58. if (this.grantedUsers.indexOf(userData._id) >= 0) {
  59. return true;
  60. }
  61. return false;
  62. };
  63. pageSchema.methods.isLatestRevision = function() {
  64. // populate されていなくて判断できない
  65. if (!this.latestRevision || !this.revision) {
  66. return true;
  67. }
  68. return (this.latestRevision == this.revision._id.toString());
  69. };
  70. pageSchema.methods.isUpdatable = function(previousRevision) {
  71. var revision = this.latestRevision || this.revision;
  72. if (revision != previousRevision) {
  73. return false;
  74. }
  75. return true;
  76. };
  77. pageSchema.methods.isLiked = function(userData) {
  78. if (undefined === this.populated('liker')) {
  79. if (this.liker.indexOf(userData._id) != -1) {
  80. return true;
  81. }
  82. return true;
  83. } else {
  84. return this.liker.some(function(likedUser) {
  85. return likedUser._id.toString() == userData._id.toString();
  86. });
  87. }
  88. };
  89. pageSchema.methods.like = function(userData, callback) {
  90. var self = this,
  91. Page = self;
  92. if (undefined === this.populated('liker')) {
  93. var added = this.liker.addToSet(userData._id);
  94. if (added.length > 0) {
  95. this.save(function(err, data) {
  96. debug('liker updated!', added);
  97. return callback(err, data);
  98. });
  99. } else {
  100. debug('liker not updated');
  101. return callback(null, this);
  102. }
  103. } else {
  104. Page.update(
  105. {_id: self._id},
  106. { $addToSet: { liker: userData._id }},
  107. function(err, numAffected, raw) {
  108. debug('Updated liker,', err, numAffected, raw);
  109. callback(null, self);
  110. }
  111. );
  112. }
  113. };
  114. pageSchema.methods.unlike = function(userData, callback) {
  115. var self = this,
  116. Page = self;
  117. if (undefined === this.populated('liker')) {
  118. var removed = this.liker.pull(userData._id);
  119. if (removed.length > 0) {
  120. this.save(function(err, data) {
  121. debug('unlike updated!', removed);
  122. return callback(err, data);
  123. });
  124. } else {
  125. debug('unlike not updated');
  126. callback(null, this);
  127. }
  128. } else {
  129. Page.update(
  130. {_id: self._id},
  131. { $pull: { liker: userData._id }},
  132. function(err, numAffected, raw) {
  133. debug('Updated liker (unlike)', err, numAffected, raw);
  134. callback(null, self);
  135. }
  136. );
  137. }
  138. };
  139. pageSchema.methods.seen = function(userData, callback) {
  140. var self = this,
  141. Page = self;
  142. if (undefined === this.populated('seenUsers')) {
  143. var added = this.seenUsers.addToSet(userData._id);
  144. if (added.length > 0) {
  145. this.save(function(err, data) {
  146. debug('seenUsers updated!', added);
  147. return callback(err, data);
  148. });
  149. } else {
  150. debug('seenUsers not updated');
  151. return callback(null, this);
  152. }
  153. } else {
  154. Page.update(
  155. {_id: self._id},
  156. { $addToSet: { seenUsers: userData._id }},
  157. function(err, numAffected, raw) {
  158. debug('Updated seenUsers,', err, numAffected, raw);
  159. callback(null, self);
  160. }
  161. );
  162. }
  163. };
  164. pageSchema.statics.getGrantLabels = function() {
  165. var grantLabels = {};
  166. grantLabels[GRANT_PUBLIC] = '公開';
  167. grantLabels[GRANT_RESTRICTED] = 'リンクを知っている人のみ';
  168. //grantLabels[GRANT_SPECIFIED] = '特定ユーザーのみ';
  169. grantLabels[GRANT_OWNER] = '自分のみ';
  170. return grantLabels;
  171. };
  172. pageSchema.statics.normalizePath = function(path) {
  173. if (!path.match(/^\//)) {
  174. path = '/' + path;
  175. }
  176. return path;
  177. };
  178. pageSchema.statics.isCreatableName = function(name) {
  179. var forbiddenPages = [
  180. /\^|\$|\*|\+/,
  181. /^\/_api\/.*/,
  182. /^\/\-\/.*/,
  183. /^\/_r\/.*/,
  184. /.+\/edit$/,
  185. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments).+/,
  186. ];
  187. var isCreatable = true;
  188. forbiddenPages.forEach(function(page) {
  189. var pageNameReg = new RegExp(page);
  190. if (name.match(pageNameReg)) {
  191. isCreatable = false;
  192. return ;
  193. }
  194. });
  195. return isCreatable;
  196. };
  197. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  198. this.update({_id: pageId}, {revision: revisionId}, {}, function(err, data) {
  199. cb(err, data);
  200. });
  201. };
  202. pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
  203. this
  204. .find({})
  205. .sort('updatedAt', -1)
  206. .skip(offset)
  207. .limit(limit)
  208. .exec(function(err, data) {
  209. cb(err, data);
  210. });
  211. };
  212. pageSchema.statics.findPageById = function(id, cb) {
  213. var Page = this;
  214. Page.findOne({_id: id}, function(err, pageData) {
  215. if (pageData === null) {
  216. return cb(new Error('Page Not Found'), null);
  217. }
  218. return populatePageData(pageData, null, cb);
  219. });
  220. };
  221. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData, cb) {
  222. var Page = this;
  223. Page.findPageById(id, function(err, pageData) {
  224. if (pageData === null) {
  225. return cb(new Error('Page Not Found'), null);
  226. }
  227. if (userData && !pageData.isGrantedFor(userData)) {
  228. return cb(PAGE_GRANT_ERROR, null);
  229. }
  230. return cb(null,pageData);
  231. });
  232. };
  233. pageSchema.statics.findPage = function(path, userData, revisionId, options, cb) {
  234. var Page = this;
  235. this.findOne({path: path}, function(err, pageData) {
  236. if (pageData === null) {
  237. return cb(new Error('Page Not Found'), null);
  238. }
  239. if (!pageData.isGrantedFor(userData)) {
  240. return cb(PAGE_GRANT_ERROR, null);
  241. }
  242. return populatePageData(pageData, revisionId, cb);
  243. });
  244. };
  245. pageSchema.statics.findListByPageIds = function(ids, options, cb) {
  246. };
  247. pageSchema.statics.findListByStartWith = function(path, userData, options, cb) {
  248. if (!options) {
  249. options = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  250. }
  251. var opt = {
  252. sort: options.sort || 'updatedAt',
  253. desc: options.desc || -1,
  254. offset: options.offset || 0,
  255. limit: options.limit || 50
  256. };
  257. var sortOpt = {};
  258. sortOpt[opt.sort] = opt.desc;
  259. var queryReg = new RegExp('^' + path);
  260. var sliceOption = options.revisionSlice || {$slice: 1};
  261. var q = this.find({
  262. path: queryReg,
  263. redirectTo: null,
  264. $or: [
  265. {grant: null},
  266. {grant: GRANT_PUBLIC},
  267. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  268. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  269. {grant: GRANT_OWNER, grantedUsers: userData._id},
  270. ],
  271. })
  272. .populate('revision')
  273. .sort(sortOpt)
  274. .skip(opt.offset)
  275. .limit(opt.limit);
  276. q.exec(function(err, data) {
  277. cb(err, data);
  278. });
  279. };
  280. pageSchema.statics.updatePage = function(page, updateData, cb) {
  281. // TODO foreach して save
  282. this.update({_id: page._id}, {$set: updateData}, function(err, data) {
  283. return cb(err, data);
  284. });
  285. };
  286. pageSchema.statics.updateGrant = function(page, grant, userData, cb) {
  287. this.update({_id: page._id}, {$set: {grant: grant}}, function(err, data) {
  288. if (grant == GRANT_PUBLIC) {
  289. page.grantedUsers = [];
  290. } else {
  291. page.grantedUsers = [];
  292. page.grantedUsers.push(userData._id);
  293. }
  294. page.save(function(err, data) {
  295. return cb(err, data);
  296. });
  297. });
  298. };
  299. // Instance method でいいのでは
  300. pageSchema.statics.pushToGrantedUsers = function(page, userData, cb) {
  301. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  302. page.grantedUsers = [];
  303. }
  304. page.grantedUsers.push(userData._id);
  305. page.save(function(err, data) {
  306. return cb(err, data);
  307. });
  308. };
  309. pageSchema.statics.pushRevision = function(pageData, newRevision, user, cb) {
  310. newRevision.save(function(err, newRevision) {
  311. if (err) {
  312. debug('Error on saving revision', err);
  313. return cb(err, null);
  314. }
  315. debug('Successfully saved new revision', newRevision);
  316. pageData.revision = newRevision._id;
  317. pageData.updatedAt = Date.now();
  318. pageData.save(function(err, data) {
  319. if (err) {
  320. debug('Error on save page data (after push revision)', err);
  321. cb(err, null);
  322. return;
  323. }
  324. cb(err, data);
  325. });
  326. });
  327. };
  328. pageSchema.statics.create = function(path, body, user, options, cb) {
  329. var Page = this
  330. , Revision = crowi.model('Revision')
  331. , format = options.format || 'markdown'
  332. , grant = options.grant || GRANT_PUBLIC
  333. , redirectTo = options.redirectTo || null;
  334. this.findOne({path: path}, function(err, pageData) {
  335. if (pageData) {
  336. cb(new Error('Cannot create new page to existed path'), null);
  337. return;
  338. }
  339. var newPage = new Page();
  340. newPage.path = path;
  341. newPage.creator = user;
  342. newPage.createdAt = Date.now();
  343. newPage.updatedAt = Date.now();
  344. newPage.redirectTo = redirectTo;
  345. newPage.grant = grant;
  346. newPage.grantedUsers = [];
  347. newPage.grantedUsers.push(user);
  348. newPage.save(function (err, newPage) {
  349. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  350. Page.pushRevision(newPage, newRevision, user, function(err, data) {
  351. if (err) {
  352. console.log('Push Revision Error on create page', err);
  353. }
  354. cb(err, data);
  355. return;
  356. });
  357. });
  358. });
  359. };
  360. pageSchema.statics.rename = function(pageData, newPageName, user, options, cb) {
  361. var Page = this
  362. , Revision = crowi.model('Revision')
  363. , path = pageData.path
  364. , createRedirectPage = options.createRedirectPage || 0
  365. , moveUnderTrees = options.moveUnderTrees || 0;
  366. // pageData の path を変更
  367. this.updatePage(pageData, {updatedAt: Date.now(), path: newPageName}, function(err, data) {
  368. if (err) {
  369. return cb(err, null);
  370. }
  371. // reivisions の path を変更
  372. Revision.updateRevisionListByPath(path, {path: newPageName}, {}, function(err, data) {
  373. if (err) {
  374. return cb(err, null);
  375. }
  376. pageData.path = newPageName;
  377. if (createRedirectPage) {
  378. Page.create(path, 'redirect ' + newPageName, user, {redirectTo: newPageName}, function(err, data) {
  379. // @TODO error handling
  380. return cb(err, pageData);
  381. });
  382. } else {
  383. return cb(err, pageData);
  384. }
  385. });
  386. });
  387. };
  388. pageSchema.statics.getHistories = function() {
  389. // TODO
  390. return;
  391. };
  392. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  393. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  394. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  395. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  396. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  397. return mongoose.model('Page', pageSchema);
  398. };