page.js 15 KB

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