page.js 12 KB

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