page.js 12 KB

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