page.js 20 KB

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