page.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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) {
  140. var self = this,
  141. Page = self;
  142. if (this.isSeenUser(userData)) {
  143. debug('seenUsers not updated');
  144. return Promise.resolve(this);
  145. }
  146. return new Promise(function(resolve, reject) {
  147. if (!userData || !userData._id) {
  148. reject(new Error('User data is not valid'));
  149. }
  150. var added = self.seenUsers.addToSet(userData);
  151. self.save(function(err, data) {
  152. if (err) {
  153. return reject(err);
  154. }
  155. debug('seenUsers updated!', added);
  156. return resolve(self);
  157. });
  158. });
  159. };
  160. pageSchema.statics.updateCommentCount = function (page, num)
  161. {
  162. var self = this;
  163. return new Promise(function(resolve, reject) {
  164. self.update({_id: page}, {commentCount: num}, {}, function(err, data) {
  165. if (err) {
  166. debug('Update commentCount Error', err);
  167. return reject(err);
  168. }
  169. return resolve(data);
  170. });
  171. });
  172. };
  173. pageSchema.statics.hasPortalPage = function (path, user) {
  174. var self = this;
  175. return new Promise(function(resolve, reject) {
  176. self.findPage(path, user)
  177. .then(function(page) {
  178. resolve(page);
  179. }).catch(function(err) {
  180. resolve(null); // check only has portal page, through error
  181. });
  182. });
  183. };
  184. pageSchema.statics.getGrantLabels = function() {
  185. var grantLabels = {};
  186. grantLabels[GRANT_PUBLIC] = '公開';
  187. grantLabels[GRANT_RESTRICTED] = 'リンクを知っている人のみ';
  188. //grantLabels[GRANT_SPECIFIED] = '特定ユーザーのみ';
  189. grantLabels[GRANT_OWNER] = '自分のみ';
  190. return grantLabels;
  191. };
  192. pageSchema.statics.normalizePath = function(path) {
  193. if (!path.match(/^\//)) {
  194. path = '/' + path;
  195. }
  196. return path;
  197. };
  198. pageSchema.statics.isCreatableName = function(name) {
  199. var forbiddenPages = [
  200. /\^|\$|\*|\+|\#/,
  201. /^\/_api\/.*/,
  202. /^\/\-\/.*/,
  203. /^\/_r\/.*/,
  204. /.+\/edit$/,
  205. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments).+/,
  206. ];
  207. var isCreatable = true;
  208. forbiddenPages.forEach(function(page) {
  209. var pageNameReg = new RegExp(page);
  210. if (name.match(pageNameReg)) {
  211. isCreatable = false;
  212. return ;
  213. }
  214. });
  215. return isCreatable;
  216. };
  217. pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
  218. this.update({_id: pageId}, {revision: revisionId}, {}, function(err, data) {
  219. cb(err, data);
  220. });
  221. };
  222. pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
  223. this
  224. .find({})
  225. .sort('updatedAt', -1)
  226. .skip(offset)
  227. .limit(limit)
  228. .exec(function(err, data) {
  229. cb(err, data);
  230. });
  231. };
  232. pageSchema.statics.findPageById = function(id) {
  233. var Page = this;
  234. return new Promise(function(resolve, reject) {
  235. Page.findOne({_id: id}, function(err, pageData) {
  236. if (err) {
  237. return reject(err);
  238. }
  239. return populatePageData(pageData, null).then(resolve);
  240. });
  241. });
  242. };
  243. pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
  244. var Page = this;
  245. return new Promise(function(resolve, reject) {
  246. Page.findPageById(id)
  247. .then(function(pageData) {
  248. if (userData && !pageData.isGrantedFor(userData)) {
  249. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  250. }
  251. return resolve(pageData);
  252. }).catch(function(err) {
  253. return reject(err);
  254. });
  255. });
  256. };
  257. // find page and check if granted user
  258. pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
  259. var self = this;
  260. return new Promise(function(resolve, reject) {
  261. self.findOne({path: path}, function(err, pageData) {
  262. if (err) {
  263. return reject(err);
  264. }
  265. if (pageData === null) {
  266. if (ignoreNotFound) {
  267. return resolve(null);
  268. }
  269. var pageNotFoundError = new Error('Page Not Found')
  270. pageNotFoundError.name = 'Crowi:Page:NotFound';
  271. return reject(pageNotFoundError);
  272. }
  273. if (!pageData.isGrantedFor(userData)) {
  274. return reject(new Error('Page is not granted for the user')); //PAGE_GRANT_ERROR, null);
  275. }
  276. populatePageData(pageData, revisionId || null).then(resolve).catch(reject);
  277. });
  278. });
  279. };
  280. pageSchema.statics.findListByPageIds = function(ids, options) {
  281. };
  282. pageSchema.statics.findListByStartWith = function(path, userData, options) {
  283. var Page = this;
  284. if (!options) {
  285. options = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  286. }
  287. var opt = {
  288. sort: options.sort || 'updatedAt',
  289. desc: options.desc || -1,
  290. offset: options.offset || 0,
  291. limit: options.limit || 50
  292. };
  293. var sortOpt = {};
  294. sortOpt[opt.sort] = opt.desc;
  295. var queryReg = new RegExp('^' + path);
  296. var sliceOption = options.revisionSlice || {$slice: 1};
  297. return new Promise(function(resolve, reject) {
  298. var q = Page.find({
  299. path: queryReg,
  300. redirectTo: null,
  301. $or: [
  302. {grant: null},
  303. {grant: GRANT_PUBLIC},
  304. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  305. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  306. {grant: GRANT_OWNER, grantedUsers: userData._id},
  307. ],
  308. })
  309. .populate('revision')
  310. .sort(sortOpt)
  311. .skip(opt.offset)
  312. .limit(opt.limit);
  313. q.exec(function(err, data) {
  314. if (err) {
  315. return reject(err);
  316. }
  317. resolve(data);
  318. });
  319. });
  320. };
  321. pageSchema.statics.updatePage = function(page, updateData, cb) {
  322. // TODO foreach して save
  323. this.update({_id: page._id}, {$set: updateData}, function(err, data) {
  324. return cb(err, data);
  325. });
  326. };
  327. pageSchema.statics.updateGrant = function(page, grant, userData) {
  328. var self = this;
  329. return new Promise(function(resolve, reject) {
  330. self.update({_id: page._id}, {$set: {grant: grant}}, function(err, data) {
  331. if (err) {
  332. return reject(err);
  333. }
  334. if (grant == GRANT_PUBLIC) {
  335. page.grantedUsers = [];
  336. } else {
  337. page.grantedUsers = [];
  338. page.grantedUsers.push(userData._id);
  339. }
  340. page.save(function(err, data) {
  341. if (err) {
  342. return reject(err);
  343. }
  344. return resolve(data);
  345. });
  346. });
  347. });
  348. };
  349. // Instance method でいいのでは
  350. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  351. return new Promise(function(resolve, reject) {
  352. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  353. page.grantedUsers = [];
  354. }
  355. page.grantedUsers.push(userData);
  356. page.save(function(err, data) {
  357. if (err) {
  358. return reject(err);
  359. }
  360. return resolve(data);
  361. });
  362. });
  363. };
  364. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  365. return new Promise(function(resolve, reject) {
  366. newRevision.save(function(err, newRevision) {
  367. if (err) {
  368. debug('Error on saving revision', err);
  369. return reject(err);
  370. }
  371. debug('Successfully saved new revision', newRevision);
  372. pageData.revision = newRevision;
  373. pageData.updatedAt = Date.now();
  374. pageData.save(function(err, data) {
  375. if (err) {
  376. // todo: remove new revision?
  377. debug('Error on save page data (after push revision)', err);
  378. return reject(err);
  379. }
  380. resolve(data);
  381. });
  382. });
  383. });
  384. };
  385. pageSchema.statics.create = function(path, body, user, options) {
  386. var Page = this
  387. , Revision = crowi.model('Revision')
  388. , format = options.format || 'markdown'
  389. , grant = options.grant || GRANT_PUBLIC
  390. , redirectTo = options.redirectTo || null;
  391. return new Promise(function(resolve, reject) {
  392. Page.findOne({path: path}, function(err, pageData) {
  393. if (pageData) {
  394. return reject(new Error('Cannot create new page to existed path'));
  395. }
  396. var newPage = new Page();
  397. newPage.path = path;
  398. newPage.creator = user;
  399. newPage.createdAt = Date.now();
  400. newPage.updatedAt = Date.now();
  401. newPage.redirectTo = redirectTo;
  402. newPage.grant = grant;
  403. newPage.grantedUsers = [];
  404. newPage.grantedUsers.push(user);
  405. newPage.save(function (err, newPage) {
  406. if (err) {
  407. return reject(err);
  408. }
  409. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  410. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  411. resolve(data);
  412. }).catch(function(err) {
  413. debug('Push Revision Error on create page', err);
  414. return reject(err);
  415. });
  416. });
  417. });
  418. });
  419. };
  420. pageSchema.statics.rename = function(pageData, newPageName, user, options, cb) {
  421. var Page = this
  422. , Revision = crowi.model('Revision')
  423. , path = pageData.path
  424. , createRedirectPage = options.createRedirectPage || 0
  425. , moveUnderTrees = options.moveUnderTrees || 0;
  426. // pageData の path を変更
  427. this.updatePage(pageData, {updatedAt: Date.now(), path: newPageName}, function(err, data) {
  428. if (err) {
  429. return cb(err, null);
  430. }
  431. // reivisions の path を変更
  432. Revision.updateRevisionListByPath(path, {path: newPageName}, {}, function(err, data) {
  433. if (err) {
  434. return cb(err, null);
  435. }
  436. pageData.path = newPageName;
  437. if (createRedirectPage) {
  438. Page.create(path, 'redirect ' + newPageName, user, {redirectTo: newPageName}, function(err, data) {
  439. // @TODO error handling
  440. return cb(err, pageData);
  441. });
  442. } else {
  443. return cb(err, pageData);
  444. }
  445. });
  446. });
  447. };
  448. pageSchema.statics.getHistories = function() {
  449. // TODO
  450. return;
  451. };
  452. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  453. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  454. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  455. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  456. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  457. return mongoose.model('Page', pageSchema);
  458. };