page.js 12 KB

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