index.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. 'use strict';
  2. const coreClass = require("../../core");
  3. const mongoose = require('mongoose');
  4. const config = require('config');
  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. ascii: /^[\x00-\x7F]+$/,
  10. custom: regex => new RegExp(`^[${regex}]+$`)
  11. };
  12. const isLength = (string, min, max) => {
  13. return !(typeof string !== 'string' || string.length < min || string.length > max);
  14. }
  15. const bluebird = require('bluebird');
  16. mongoose.Promise = bluebird;
  17. module.exports = class extends coreClass {
  18. initialize() {
  19. return new Promise((resolve, reject) => {
  20. this.setStage(1);
  21. this.schemas = {};
  22. this.models = {};
  23. const mongoUrl = config.get("mongo").url;
  24. mongoose.connect(mongoUrl, {
  25. useNewUrlParser: true,
  26. useCreateIndex: true,
  27. reconnectInterval: 3000,
  28. reconnectTries: 10
  29. })
  30. .then(() => {
  31. this.schemas = {
  32. song: new mongoose.Schema(require(`./schemas/song`)),
  33. queueSong: new mongoose.Schema(require(`./schemas/queueSong`)),
  34. station: new mongoose.Schema(require(`./schemas/station`)),
  35. user: new mongoose.Schema(require(`./schemas/user`)),
  36. playlist: new mongoose.Schema(require(`./schemas/playlist`)),
  37. news: new mongoose.Schema(require(`./schemas/news`)),
  38. report: new mongoose.Schema(require(`./schemas/report`)),
  39. punishment: new mongoose.Schema(require(`./schemas/punishment`))
  40. };
  41. this.models = {
  42. song: mongoose.model('song', this.schemas.song),
  43. queueSong: mongoose.model('queueSong', this.schemas.queueSong),
  44. station: mongoose.model('station', this.schemas.station),
  45. user: mongoose.model('user', this.schemas.user),
  46. playlist: mongoose.model('playlist', this.schemas.playlist),
  47. news: mongoose.model('news', this.schemas.news),
  48. report: mongoose.model('report', this.schemas.report),
  49. punishment: mongoose.model('punishment', this.schemas.punishment)
  50. };
  51. mongoose.connection.on('error', err => {
  52. this.logger.error("DB_MODULE", err);
  53. });
  54. mongoose.connection.on('disconnected', () => {
  55. this.logger.error("DB_MODULE", "Disconnected, going to try to reconnect...");
  56. this.setState("RECONNECTING");
  57. });
  58. mongoose.connection.on('reconnected', () => {
  59. this.logger.success("DB_MODULE", "Reconnected.");
  60. this.setState("INITIALIZED");
  61. });
  62. mongoose.connection.on('reconnectFailed', () => {
  63. this.logger.error("DB_MODULE", "Reconnect failed, stopping reconnecting.");
  64. this.failed = true;
  65. this._lockdown();
  66. });
  67. // User
  68. this.schemas.user.path('username').validate((username) => {
  69. return (isLength(username, 2, 32) && regex.custom("a-zA-Z0-9_-").test(username));
  70. }, 'Invalid username.');
  71. this.schemas.user.path('email.address').validate((email) => {
  72. if (!isLength(email, 3, 254)) return false;
  73. if (email.indexOf('@') !== email.lastIndexOf('@')) return false;
  74. return regex.emailSimple.test(email) && regex.ascii.test(email);
  75. }, 'Invalid email.');
  76. // Station
  77. this.schemas.station.path('name').validate((id) => {
  78. return (isLength(id, 2, 16) && regex.az09_.test(id));
  79. }, 'Invalid station name.');
  80. this.schemas.station.path('displayName').validate((displayName) => {
  81. return (isLength(displayName, 2, 32) && regex.ascii.test(displayName));
  82. }, 'Invalid display name.');
  83. this.schemas.station.path('description').validate((description) => {
  84. if (!isLength(description, 2, 200)) return false;
  85. let characters = description.split("");
  86. return characters.filter((character) => {
  87. return character.charCodeAt(0) === 21328;
  88. }).length === 0;
  89. }, 'Invalid display name.');
  90. this.schemas.station.path('owner').validate({
  91. isAsync: true,
  92. validator: (owner, callback) => {
  93. this.models.station.countDocuments({ owner: owner }, (err, c) => {
  94. callback(!(err || c >= 3))
  95. });
  96. },
  97. message: 'User already has 3 stations.'
  98. });
  99. /*
  100. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  101. let totalDuration = 0;
  102. queue.forEach((song) => {
  103. totalDuration += song.duration;
  104. });
  105. return callback(totalDuration <= 3600 * 3);
  106. }, 'The max length of the queue is 3 hours.');
  107. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  108. if (queue.length === 0) return callback(true);
  109. let totalDuration = 0;
  110. const userId = queue[queue.length - 1].requestedBy;
  111. queue.forEach((song) => {
  112. if (userId === song.requestedBy) {
  113. totalDuration += song.duration;
  114. }
  115. });
  116. return callback(totalDuration <= 900);
  117. }, 'The max length of songs per user is 15 minutes.');
  118. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  119. if (queue.length === 0) return callback(true);
  120. let totalSongs = 0;
  121. const userId = queue[queue.length - 1].requestedBy;
  122. queue.forEach((song) => {
  123. if (userId === song.requestedBy) {
  124. totalSongs++;
  125. }
  126. });
  127. if (totalSongs <= 2) return callback(true);
  128. if (totalSongs > 3) return callback(false);
  129. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId) return callback(true);
  130. return callback(false);
  131. }, 'The max amount of songs per user is 3, and only 2 in a row is allowed.');
  132. */
  133. // Song
  134. let songTitle = (title) => {
  135. return isLength(title, 1, 100);
  136. };
  137. this.schemas.song.path('title').validate(songTitle, 'Invalid title.');
  138. this.schemas.queueSong.path('title').validate(songTitle, 'Invalid title.');
  139. this.schemas.song.path('artists').validate((artists) => {
  140. return !(artists.length < 1 || artists.length > 10);
  141. }, 'Invalid artists.');
  142. this.schemas.queueSong.path('artists').validate((artists) => {
  143. return !(artists.length < 0 || artists.length > 10);
  144. }, 'Invalid artists.');
  145. let songArtists = (artists) => {
  146. return artists.filter((artist) => {
  147. return (isLength(artist, 1, 64) && artist !== "NONE");
  148. }).length === artists.length;
  149. };
  150. this.schemas.song.path('artists').validate(songArtists, 'Invalid artists.');
  151. this.schemas.queueSong.path('artists').validate(songArtists, 'Invalid artists.');
  152. let songGenres = (genres) => {
  153. if (genres.length < 1 || genres.length > 16) return false;
  154. return genres.filter((genre) => {
  155. return (isLength(genre, 1, 32) && regex.ascii.test(genre));
  156. }).length === genres.length;
  157. };
  158. this.schemas.song.path('genres').validate(songGenres, 'Invalid genres.');
  159. this.schemas.queueSong.path('genres').validate(songGenres, 'Invalid genres.');
  160. let songThumbnail = (thumbnail) => {
  161. if (!isLength(thumbnail, 1, 256)) return false;
  162. let startWith = "https://";
  163. if (config.get("cookie.secure") === false) startWith = "http://";
  164. return thumbnail.startsWith(startWith);
  165. };
  166. this.schemas.song.path('thumbnail').validate(songThumbnail, 'Invalid thumbnail.');
  167. this.schemas.queueSong.path('thumbnail').validate(songThumbnail, 'Invalid thumbnail.');
  168. // Playlist
  169. this.schemas.playlist.path('displayName').validate((displayName) => {
  170. return (isLength(displayName, 1, 32) && regex.ascii.test(displayName));
  171. }, 'Invalid display name.');
  172. this.schemas.playlist.path('createdBy').validate((createdBy) => {
  173. this.models.playlist.countDocuments({ createdBy: createdBy }, (err, c) => {
  174. return !(err || c >= 10);
  175. });
  176. }, 'Max 10 playlists per user.');
  177. this.schemas.playlist.path('songs').validate((songs) => {
  178. return songs.length <= 5000;
  179. }, 'Max 5000 songs per playlist.');
  180. this.schemas.playlist.path('songs').validate((songs) => {
  181. if (songs.length === 0) return true;
  182. return songs[0].duration <= 10800;
  183. }, 'Max 3 hours per song.');
  184. // Report
  185. this.schemas.report.path('description').validate((description) => {
  186. return (!description || (isLength(description, 0, 400) && regex.ascii.test(description)));
  187. }, 'Invalid description.');
  188. resolve();
  189. })
  190. .catch(err => {
  191. this.logger.error("DB_MODULE", err);
  192. reject(err);
  193. });
  194. })
  195. }
  196. passwordValid(password) {
  197. return isLength(password, 6, 200);
  198. }
  199. }