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