page.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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('revision')
  387. .exec(function(err, pages) {
  388. if (err) {
  389. return reject(err);
  390. }
  391. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}, function(err, data) {
  392. if (err) {
  393. return reject(err);
  394. }
  395. return resolve(data);
  396. });
  397. });
  398. });
  399. };
  400. /**
  401. * とりあえず、公開ページであり、redirectTo が無いものだけを出すためだけのAPI
  402. */
  403. pageSchema.statics.findListByCreator = function(user, option) {
  404. var Page = this;
  405. var User = crowi.model('User');
  406. var limit = option.limit || 50;
  407. var offset = option.offset || 0;
  408. return new Promise(function(resolve, reject) {
  409. Page
  410. .find({ creator: user._id, grant: GRANT_PUBLIC, redirectTo: null })
  411. .sort({createdAt: -1})
  412. .skip(offset)
  413. .limit(limit)
  414. .populate('revision')
  415. .exec()
  416. .then(function(pages) {
  417. return Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS}).then(resolve);
  418. });
  419. });
  420. };
  421. /**
  422. * findListByStartWith
  423. *
  424. * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
  425. * If `path` doesn't have `/` at the end, returns '{path}*'
  426. * e.g.
  427. */
  428. pageSchema.statics.findListByStartWith = function(path, userData, option) {
  429. var Page = this;
  430. var User = crowi.model('User');
  431. var pathCondition = [];
  432. if (!option) {
  433. option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
  434. }
  435. var opt = {
  436. sort: option.sort || 'updatedAt',
  437. desc: option.desc || -1,
  438. offset: option.offset || 0,
  439. limit: option.limit || 50
  440. };
  441. var sortOpt = {};
  442. sortOpt[opt.sort] = opt.desc;
  443. var queryReg = new RegExp('^' + path);
  444. var sliceOption = option.revisionSlice || {$slice: 1};
  445. pathCondition.push({path: queryReg});
  446. if (path.match(/\/$/)) {
  447. debug('Page list by ending with /, so find also upper level page');
  448. pathCondition.push({path: path.substr(0, path.length -1)});
  449. }
  450. return new Promise(function(resolve, reject) {
  451. // FIXME: might be heavy
  452. var q = Page.find({
  453. redirectTo: null,
  454. $or: [
  455. {grant: null},
  456. {grant: GRANT_PUBLIC},
  457. {grant: GRANT_RESTRICTED, grantedUsers: userData._id},
  458. {grant: GRANT_SPECIFIED, grantedUsers: userData._id},
  459. {grant: GRANT_OWNER, grantedUsers: userData._id},
  460. ],})
  461. .populate('revision')
  462. .and({
  463. $or: pathCondition
  464. })
  465. .sort(sortOpt)
  466. .skip(opt.offset)
  467. .limit(opt.limit);
  468. q.exec()
  469. .then(function(pages) {
  470. Page.populate(pages, {path: 'revision.author', model: 'User', select: User.USER_PUBLIC_FIELDS})
  471. .then(resolve)
  472. .catch(reject);
  473. })
  474. });
  475. };
  476. pageSchema.statics.updatePage = function(page, updateData) {
  477. var Page = this;
  478. return new Promise(function(resolve, reject) {
  479. // TODO foreach して save
  480. Page.update({_id: page._id}, {$set: updateData}, function(err, data) {
  481. if (err) {
  482. return reject(err);
  483. }
  484. return resolve(data);
  485. });
  486. });
  487. };
  488. pageSchema.statics.updateGrant = function(page, grant, userData) {
  489. var self = this;
  490. return new Promise(function(resolve, reject) {
  491. self.update({_id: page._id}, {$set: {grant: grant}}, function(err, data) {
  492. if (err) {
  493. return reject(err);
  494. }
  495. if (grant == GRANT_PUBLIC) {
  496. page.grantedUsers = [];
  497. } else {
  498. page.grantedUsers = [];
  499. page.grantedUsers.push(userData._id);
  500. }
  501. page.save(function(err, data) {
  502. if (err) {
  503. return reject(err);
  504. }
  505. return resolve(data);
  506. });
  507. });
  508. });
  509. };
  510. // Instance method でいいのでは
  511. pageSchema.statics.pushToGrantedUsers = function(page, userData) {
  512. return new Promise(function(resolve, reject) {
  513. if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
  514. page.grantedUsers = [];
  515. }
  516. page.grantedUsers.push(userData);
  517. page.save(function(err, data) {
  518. if (err) {
  519. return reject(err);
  520. }
  521. return resolve(data);
  522. });
  523. });
  524. };
  525. pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
  526. return new Promise(function(resolve, reject) {
  527. newRevision.save(function(err, newRevision) {
  528. if (err) {
  529. debug('Error on saving revision', err);
  530. return reject(err);
  531. }
  532. debug('Successfully saved new revision', newRevision);
  533. pageData.revision = newRevision;
  534. pageData.updatedAt = Date.now();
  535. pageData.save(function(err, data) {
  536. if (err) {
  537. // todo: remove new revision?
  538. debug('Error on save page data (after push revision)', err);
  539. return reject(err);
  540. }
  541. resolve(data);
  542. pageEvent.emit('update', data, user);
  543. });
  544. });
  545. });
  546. };
  547. pageSchema.statics.create = function(path, body, user, options) {
  548. var Page = this
  549. , Revision = crowi.model('Revision')
  550. , format = options.format || 'markdown'
  551. , grant = options.grant || GRANT_PUBLIC
  552. , redirectTo = options.redirectTo || null;
  553. // force public
  554. if (isPortalPath(path)) {
  555. grant = GRANT_PUBLIC;
  556. }
  557. return new Promise(function(resolve, reject) {
  558. Page.findOne({path: path}, function(err, pageData) {
  559. if (pageData) {
  560. return reject(new Error('Cannot create new page to existed path'));
  561. }
  562. var newPage = new Page();
  563. newPage.path = path;
  564. newPage.creator = user;
  565. newPage.createdAt = Date.now();
  566. newPage.updatedAt = Date.now();
  567. newPage.redirectTo = redirectTo;
  568. newPage.grant = grant;
  569. newPage.grantedUsers = [];
  570. newPage.grantedUsers.push(user);
  571. newPage.save(function (err, newPage) {
  572. if (err) {
  573. return reject(err);
  574. }
  575. var newRevision = Revision.prepareRevision(newPage, body, user, {format: format});
  576. Page.pushRevision(newPage, newRevision, user).then(function(data) {
  577. resolve(data);
  578. pageEvent.emit('create', data, user);
  579. }).catch(function(err) {
  580. debug('Push Revision Error on create page', err);
  581. return reject(err);
  582. });
  583. });
  584. });
  585. });
  586. };
  587. pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
  588. var Page = this
  589. , Revision = crowi.model('Revision')
  590. , path = pageData.path
  591. , createRedirectPage = options.createRedirectPage || 0
  592. , moveUnderTrees = options.moveUnderTrees || 0;
  593. return new Promise(function(resolve, reject) {
  594. // pageData の path を変更
  595. Page.updatePage(pageData, {updatedAt: Date.now(), path: newPagePath})
  596. .then(function(data) {
  597. debug('Before ', pageData);
  598. // reivisions の path を変更
  599. return Revision.updateRevisionListByPath(path, {path: newPagePath}, {})
  600. }).then(function(data) {
  601. debug('After ', pageData);
  602. pageData.path = newPagePath;
  603. if (createRedirectPage) {
  604. var body = 'redirect ' + newPagePath;
  605. return Page.create(path, body, user, {redirectTo: newPagePath}).then(resolve).catch(reject);
  606. } else {
  607. return resolve(data);
  608. }
  609. });
  610. });
  611. };
  612. pageSchema.statics.getHistories = function() {
  613. // TODO
  614. return;
  615. };
  616. pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC;
  617. pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED;
  618. pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED;
  619. pageSchema.statics.GRANT_OWNER = GRANT_OWNER;
  620. pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR;
  621. return mongoose.model('Page', pageSchema);
  622. };