page.js 19 KB

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