page.js 16 KB

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