index.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. 'use strict';
  2. const mongoose = require('mongoose');
  3. const config = require('config');
  4. const bluebird = require('bluebird');
  5. const regex = {
  6. azAZ09_: /^[A-Za-z0-9_]+$/,
  7. az09_: /^[a-z0-9_]+$/,
  8. emailSimple: /^[\x00-\x7F]+@[a-z0-9]+\.[a-z0-9]+(\.[a-z0-9]+)?$/,
  9. password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]/,
  10. ascii: /^[\x00-\x7F]+$/
  11. };
  12. const isLength = (string, min, max) => {
  13. return !(typeof string !== 'string' || string.length < min || string.length > max);
  14. }
  15. mongoose.Promise = bluebird;
  16. let initialized = false;
  17. let lockdown = false;
  18. let lib = {
  19. connection: null,
  20. schemas: {},
  21. models: {},
  22. init: (url, errorCb, cb) => {
  23. mongoose.connect(url, {
  24. useNewUrlParser: true,
  25. useCreateIndex: true
  26. })
  27. .then(() => {
  28. lib.schemas = {
  29. song: new mongoose.Schema(require(`./schemas/song`)),
  30. queueSong: new mongoose.Schema(require(`./schemas/queueSong`)),
  31. station: new mongoose.Schema(require(`./schemas/station`)),
  32. user: new mongoose.Schema(require(`./schemas/user`)),
  33. playlist: new mongoose.Schema(require(`./schemas/playlist`)),
  34. news: new mongoose.Schema(require(`./schemas/news`)),
  35. report: new mongoose.Schema(require(`./schemas/report`)),
  36. punishment: new mongoose.Schema(require(`./schemas/punishment`))
  37. };
  38. lib.models = {
  39. song: mongoose.model('song', lib.schemas.song),
  40. queueSong: mongoose.model('queueSong', lib.schemas.queueSong),
  41. station: mongoose.model('station', lib.schemas.station),
  42. user: mongoose.model('user', lib.schemas.user),
  43. playlist: mongoose.model('playlist', lib.schemas.playlist),
  44. news: mongoose.model('news', lib.schemas.news),
  45. report: mongoose.model('report', lib.schemas.report),
  46. punishment: mongoose.model('punishment', lib.schemas.punishment)
  47. };
  48. // lib.schemas.user.path('username').validate((username) => {
  49. // return (isLength(username, 2, 32) && regex.azAZ09_.test(username));
  50. // }, 'Invalid username.');
  51. lib.schemas.user.path('email.address').validate((email) => {
  52. if (!isLength(email, 3, 254)) return false;
  53. if (email.indexOf('@') !== email.lastIndexOf('@')) return false;
  54. return regex.emailSimple.test(email);
  55. }, 'Invalid email.');
  56. lib.schemas.station.path('name').validate((id) => {
  57. return (isLength(id, 2, 16) && regex.az09_.test(id));
  58. }, 'Invalid station name.');
  59. lib.schemas.station.path('displayName').validate((displayName) => {
  60. return (isLength(displayName, 2, 32) && regex.azAZ09_.test(displayName));
  61. }, 'Invalid display name.');
  62. lib.schemas.station.path('description').validate((description) => {
  63. if (!isLength(description, 2, 200)) return false;
  64. let characters = description.split("");
  65. return characters.filter((character) => {
  66. return character.charCodeAt(0) === 21328;
  67. }).length === 0;
  68. }, 'Invalid display name.');
  69. lib.schemas.station.path('owner').validate((owner, callback) => {
  70. lib.models.station.countDocuments({ owner: owner }, (err, c) => {
  71. callback(!(err || c >= 3));
  72. });
  73. }, 'User already has 3 stations.');
  74. /*
  75. lib.schemas.station.path('queue').validate((queue, callback) => {
  76. let totalDuration = 0;
  77. queue.forEach((song) => {
  78. totalDuration += song.duration;
  79. });
  80. return callback(totalDuration <= 3600 * 3);
  81. }, 'The max length of the queue is 3 hours.');
  82. lib.schemas.station.path('queue').validate((queue, callback) => {
  83. if (queue.length === 0) return callback(true);
  84. let totalDuration = 0;
  85. const userId = queue[queue.length - 1].requestedBy;
  86. queue.forEach((song) => {
  87. if (userId === song.requestedBy) {
  88. totalDuration += song.duration;
  89. }
  90. });
  91. return callback(totalDuration <= 900);
  92. }, 'The max length of songs per user is 15 minutes.');
  93. lib.schemas.station.path('queue').validate((queue, callback) => {
  94. if (queue.length === 0) return callback(true);
  95. let totalSongs = 0;
  96. const userId = queue[queue.length - 1].requestedBy;
  97. queue.forEach((song) => {
  98. if (userId === song.requestedBy) {
  99. totalSongs++;
  100. }
  101. });
  102. if (totalSongs <= 2) return callback(true);
  103. if (totalSongs > 3) return callback(false);
  104. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId) return callback(true);
  105. return callback(false);
  106. }, 'The max amount of songs per user is 3, and only 2 in a row is allowed.');
  107. */
  108. let songTitle = (title) => {
  109. return isLength(title, 1, 100);
  110. };
  111. lib.schemas.song.path('title').validate(songTitle, 'Invalid title.');
  112. lib.schemas.queueSong.path('title').validate(songTitle, 'Invalid title.');
  113. lib.schemas.song.path('artists').validate((artists) => {
  114. return !(artists.length < 1 || artists.length > 10);
  115. }, 'Invalid artists.');
  116. lib.schemas.queueSong.path('artists').validate((artists) => {
  117. return !(artists.length < 0 || artists.length > 10);
  118. }, 'Invalid artists.');
  119. let songArtists = (artists) => {
  120. return artists.filter((artist) => {
  121. return (isLength(artist, 1, 32) && regex.ascii.test(artist) && artist !== "NONE");
  122. }).length === artists.length;
  123. };
  124. lib.schemas.song.path('artists').validate(songArtists, 'Invalid artists.');
  125. lib.schemas.queueSong.path('artists').validate(songArtists, 'Invalid artists.');
  126. let songGenres = (genres) => {
  127. return genres.filter((genre) => {
  128. return (isLength(genre, 1, 16) && regex.az09_.test(genre));
  129. }).length === genres.length;
  130. };
  131. lib.schemas.song.path('genres').validate(songGenres, 'Invalid genres.');
  132. lib.schemas.queueSong.path('genres').validate(songGenres, 'Invalid genres.');
  133. lib.schemas.song.path('thumbnail').validate((thumbnail) => {
  134. return isLength(thumbnail, 8, 256);
  135. }, 'Invalid thumbnail.');
  136. lib.schemas.queueSong.path('thumbnail').validate((thumbnail) => {
  137. return isLength(thumbnail, 0, 256);
  138. }, 'Invalid thumbnail.');
  139. lib.schemas.playlist.path('displayName').validate((displayName) => {
  140. return (isLength(displayName, 1, 16) && regex.ascii.test(displayName));
  141. }, 'Invalid display name.');
  142. lib.schemas.playlist.path('createdBy').validate((createdBy) => {
  143. lib.models.playlist.countDocuments({ createdBy: createdBy }, (err, c) => {
  144. return !(err || c >= 10);
  145. });
  146. }, 'Max 10 playlists per user.');
  147. lib.schemas.playlist.path('songs').validate((songs) => {
  148. return songs.length <= 2000;
  149. }, 'Max 2000 songs per playlist.');
  150. lib.schemas.playlist.path('songs').validate((songs) => {
  151. if (songs.length === 0) return true;
  152. return songs[0].duration <= 10800;
  153. }, 'Max 3 hours per song.');
  154. lib.schemas.report.path('description').validate((description) => {
  155. return (!description || (isLength(description, 0, 400) && regex.ascii.test(description)));
  156. }, 'Invalid description.');
  157. initialized = true;
  158. if (lockdown) return this._lockdown();
  159. cb();
  160. })
  161. .catch(err => {
  162. console.error(err);
  163. errorCb('Database connection error.', err, 'DB');
  164. });
  165. },
  166. passwordValid: (password) => {
  167. if (!isLength(password, 6, 200)) return false;
  168. return regex.password.test(password);
  169. },
  170. _lockdown: () => {
  171. lib.connection.close();
  172. lockdown = true;
  173. }
  174. };
  175. module.exports = lib;