page.js 19 KB

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