page.js 12 KB

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