page.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. , USER_PUBLIC_FIELDS = '_id fbId image googleId name username email status createdAt' // TODO: どこか別の場所へ...
  11. , pageSchema;
  12. function populatePageData(pageData, revisionId, callback) {
  13. var Page = crowi.model('Page');
  14. pageData.latestRevision = pageData.revision;
  15. if (revisionId) {
  16. pageData.revision = revisionId;
  17. }
  18. pageData.likerCount = pageData.liker.length || 0;
  19. pageData.seenUsersCount = pageData.seenUsers.length || 0;
  20. pageData.populate([
  21. {path: 'creator', model: 'User'},
  22. {path: 'revision', model: 'Revision'},
  23. {path: 'liker', options: { limit: 11 }},
  24. {path: 'seenUsers', options: { limit: 11 }},
  25. ], function (err, pageData) {
  26. Page.populate(pageData, {path: 'revision.author', model: 'User'}, callback);
  27. });
  28. }
  29. pageSchema = new mongoose.Schema({
  30. path: { type: String, required: true, index: true },
  31. revision: { type: ObjectId, ref: 'Revision' },
  32. redirectTo: { type: String, index: true },
  33. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  34. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  35. creator: { type: ObjectId, ref: 'User', index: true },
  36. liker: [{ type: ObjectId, ref: 'User', index: true }],
  37. seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
  38. commentCount: { type: Number, default: 0 },
  39. createdAt: { type: Date, default: Date.now },
  40. updatedAt: Date
  41. });
  42. pageSchema.methods.isPublic = function() {
  43. if (!this.grant || this.grant == GRANT_PUBLIC) {
  44. return true;
  45. }
  46. return false;
  47. };
  48. pageSchema.methods.isCreator = function(userData) {
  49. if (this.populated('creator') && this.creator._id.toString() === userData._id.toString()) {
  50. return true;
  51. } else if (this.creator.toString() === userData._id.toString()) {
  52. return true
  53. }
  54. return false;
  55. };
  56. pageSchema.methods.isGrantedFor = function(userData) {
  57. if (this.isPublic() || this.isCreator(userData)) {
  58. return true;
  59. }
  60. if (this.grantedUsers.indexOf(userData._id) >= 0) {
  61. return true;
  62. }
  63. return false;
  64. };
  65. pageSchema.methods.isLatestRevision = function() {
  66. // populate されていなくて判断できない
  67. if (!this.latestRevision || !this.revision) {
  68. return true;
  69. }
  70. return (this.latestRevision == this.revision._id.toString());
  71. };
  72. pageSchema.methods.isUpdatable = function(previousRevision) {
  73. var revision = this.latestRevision || this.revision;
  74. if (revision != previousRevision) {
  75. return false;
  76. }
  77. return true;
  78. };
  79. pageSchema.methods.isLiked = function(userData) {
  80. if (undefined === this.populated('liker')) {
  81. if (this.liker.indexOf(userData._id.toString()) != -1) {
  82. return true;
  83. }
  84. return true;
  85. } else {
  86. return this.liker.some(function(likedUser) {
  87. return likedUser._id.equals(userData._id);
  88. });
  89. }
  90. };
  91. pageSchema.methods.like = function(userData, callback) {
  92. var self = this,
  93. Page = self;
  94. var added = this.liker.addToSet(userData._id);
  95. if (added.length > 0) {
  96. this.save(function(err, data) {
  97. debug('liker updated!', added);
  98. return callback(err, data);
  99. });
  100. } else {
  101. debug('liker not updated');
  102. return callback(null, this);
  103. }
  104. };
  105. pageSchema.methods.unlike = function(userData, callback) {
  106. var self = this,
  107. Page = self;
  108. var removed = this.liker.pull(userData._id);
  109. if (removed.length > 0) {
  110. this.save(function(err, data) {
  111. debug('unlike updated!', removed);
  112. return callback(err, data);
  113. });
  114. } else {
  115. debug('unlike not updated');
  116. callback(null, this);
  117. }
  118. };
  119. pageSchema.methods.isSeenUser = function(userData) {
  120. var self = this,
  121. Page = self;
  122. return this.seenUsers.some(function(seenUser) {
  123. return seenUser._id.equals(userData._id);
  124. });
  125. };
  126. pageSchema.methods.seen = function(userData, callback) {
  127. var self = this,
  128. Page = self;
  129. if (!userData || !userData._id) {
  130. callback(new Error('User data is not valid'), null);
  131. }
  132. if (this.isSeenUser(userData)) {
  133. debug('seenUsers not updated');
  134. return callback(null, self);
  135. }
  136. var added = self.seenUsers.addToSet(userData);
  137. this.save(function(err, data) {
  138. debug('seenUsers updated!', added);
  139. return callback(err, self);
  140. });
  141. };
  142. pageSchema.statics.updateCommentCount = function (page, num)
  143. {
  144. var self = this;
  145. return new Promise(function(resolve, reject) {
  146. self.update({_id: page}, {commentCount: num}, {}, function(err, data) {
  147. if (err) {
  148. debug('Update commentCount Error', err);
  149. return reject(err);
  150. }
  151. return resolve(data);
  152. });
  153. });
  154. };
  155. pageSchema.statics.getGrantLabels = function() {
  156. var grantLabels = {};
  157. grantLabels[GRANT_PUBLIC] = '公開';
  158. grantLabels[GRANT_RESTRICTED] = 'リンクを知っている人のみ';
  159. //grantLabels[GRANT_SPECIFIED] = '特定ユーザーのみ';
  160. grantLabels[GRANT_OWNER] = '自分のみ';
  161. return grantLabels;
  162. };
  163. pageSchema.statics.normalizePath = function(path) {
  164. if (!path.match(/^\//)) {
  165. path = '/' + path;
  166. }
  167. return path;
  168. };
  169. pageSchema.statics.isCreatableName = function(name) {
  170. var forbiddenPages = [
  171. /\^|\$|\*|\+|\#/,
  172. /^\/_api\/.*/,
  173. /^\/\-\/.*/,
  174. /^\/_r\/.*/,
  175. /.+\/edit$/,
  176. /\/$/,
  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. newRevision.save(function(err, newRevision) {
  303. if (err) {
  304. debug('Error on saving revision', err);
  305. return cb(err, null);
  306. }
  307. debug('Successfully saved new revision', newRevision);
  308. pageData.revision = newRevision._id;
  309. pageData.updatedAt = Date.now();
  310. pageData.save(function(err, data) {
  311. if (err) {
  312. debug('Error on save page data (after push revision)', err);
  313. cb(err, null);
  314. return;
  315. }
  316. cb(err, data);
  317. });
  318. });
  319. };
  320. pageSchema.statics.create = function(path, body, user, options, cb) {
  321. var Page = this
  322. , Revision = crowi.model('Revision')
  323. , format = options.format || 'markdown'
  324. , grant = options.grant || GRANT_PUBLIC
  325. , redirectTo = options.redirectTo || null;
  326. this.findOne({path: path}, function(err, pageData) {
  327. if (pageData) {
  328. cb(new Error('Cannot create new page to existed path'), null);
  329. return;
  330. }
  331. var newPage = new Page();
  332. newPage.path = path;
  333. newPage.creator = user;
  334. newPage.createdAt = Date.now();
  335. newPage.updatedAt = Date.now();
  336. newPage.redirectTo = redirectTo;
  337. newPage.grant = grant;
  338. newPage.grantedUsers = [];
  339. newPage.grantedUsers.push(user);
  340. newPage.save(function (err, newPage) {
  341. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  342. Page.pushRevision(newPage, newRevision, user, function(err, data) {
  343. if (err) {
  344. console.log('Push Revision Error on create page', err);
  345. }
  346. cb(err, data);
  347. return;
  348. });
  349. });
  350. });
  351. };
  352. pageSchema.statics.rename = function(pageData, newPageName, user, options, cb) {
  353. var Page = this
  354. , Revision = crowi.model('Revision')
  355. , path = pageData.path
  356. , createRedirectPage = options.createRedirectPage || 0
  357. , moveUnderTrees = options.moveUnderTrees || 0;
  358. // pageData の path を変更
  359. this.updatePage(pageData, {updatedAt: Date.now(), path: newPageName}, function(err, data) {
  360. if (err) {
  361. return cb(err, null);
  362. }
  363. // reivisions の path を変更
  364. Revision.updateRevisionListByPath(path, {path: newPageName}, {}, function(err, data) {
  365. if (err) {
  366. return cb(err, null);
  367. }
  368. pageData.path = newPageName;
  369. if (createRedirectPage) {
  370. Page.create(path, 'redirect ' + newPageName, user, {redirectTo: newPageName}, function(err, data) {
  371. // @TODO error handling
  372. return cb(err, pageData);
  373. });
  374. } else {
  375. return cb(err, pageData);
  376. }
  377. });
  378. });
  379. };
  380. pageSchema.statics.getHistories = function() {
  381. // TODO
  382. return;
  383. };
  384. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  385. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  386. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  387. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  388. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  389. return mongoose.model('Page', pageSchema);
  390. };