page.js 12 KB

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