index.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. validator: (owner) => {
  92. return new Promise((resolve, reject) => {
  93. this.models.station.countDocuments({ owner: owner }, (err, c) => {
  94. if (err) reject(new Error("A mongo error happened."));
  95. else if (c >= 3) reject(new Error("User already has 3 stations."));
  96. else resolve();
  97. });
  98. });
  99. },
  100. message: 'User already has 3 stations.'
  101. });
  102. /*
  103. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  104. let totalDuration = 0;
  105. queue.forEach((song) => {
  106. totalDuration += song.duration;
  107. });
  108. return callback(totalDuration <= 3600 * 3);
  109. }, 'The max length of the queue is 3 hours.');
  110. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  111. if (queue.length === 0) return callback(true);
  112. let totalDuration = 0;
  113. const userId = queue[queue.length - 1].requestedBy;
  114. queue.forEach((song) => {
  115. if (userId === song.requestedBy) {
  116. totalDuration += song.duration;
  117. }
  118. });
  119. return callback(totalDuration <= 900);
  120. }, 'The max length of songs per user is 15 minutes.');
  121. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  122. if (queue.length === 0) return callback(true);
  123. let totalSongs = 0;
  124. const userId = queue[queue.length - 1].requestedBy;
  125. queue.forEach((song) => {
  126. if (userId === song.requestedBy) {
  127. totalSongs++;
  128. }
  129. });
  130. if (totalSongs <= 2) return callback(true);
  131. if (totalSongs > 3) return callback(false);
  132. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId) return callback(true);
  133. return callback(false);
  134. }, 'The max amount of songs per user is 3, and only 2 in a row is allowed.');
  135. */
  136. // Song
  137. let songTitle = (title) => {
  138. return isLength(title, 1, 100);
  139. };
  140. this.schemas.song.path('title').validate(songTitle, 'Invalid title.');
  141. this.schemas.queueSong.path('title').validate(songTitle, 'Invalid title.');
  142. this.schemas.song.path('artists').validate((artists) => {
  143. return !(artists.length < 1 || artists.length > 10);
  144. }, 'Invalid artists.');
  145. this.schemas.queueSong.path('artists').validate((artists) => {
  146. return !(artists.length < 0 || artists.length > 10);
  147. }, 'Invalid artists.');
  148. let songArtists = (artists) => {
  149. return artists.filter((artist) => {
  150. return (isLength(artist, 1, 64) && artist !== "NONE");
  151. }).length === artists.length;
  152. };
  153. this.schemas.song.path('artists').validate(songArtists, 'Invalid artists.');
  154. this.schemas.queueSong.path('artists').validate(songArtists, 'Invalid artists.');
  155. let songGenres = (genres) => {
  156. if (genres.length < 1 || genres.length > 16) return false;
  157. return genres.filter((genre) => {
  158. return (isLength(genre, 1, 32) && regex.ascii.test(genre));
  159. }).length === genres.length;
  160. };
  161. this.schemas.song.path('genres').validate(songGenres, 'Invalid genres.');
  162. this.schemas.queueSong.path('genres').validate(songGenres, 'Invalid genres.');
  163. let songThumbnail = (thumbnail) => {
  164. if (!isLength(thumbnail, 1, 256)) return false;
  165. if (config.get("cookie.secure") === true) return thumbnail.startsWith("https://");
  166. else return thumbnail.startsWith("http://") || thumbnail.startsWith("https://");
  167. };
  168. this.schemas.song.path('thumbnail').validate(songThumbnail, 'Invalid thumbnail.');
  169. this.schemas.queueSong.path('thumbnail').validate(songThumbnail, 'Invalid thumbnail.');
  170. // Playlist
  171. this.schemas.playlist.path('displayName').validate((displayName) => {
  172. return (isLength(displayName, 1, 32) && regex.ascii.test(displayName));
  173. }, 'Invalid display name.');
  174. this.schemas.playlist.path('createdBy').validate((createdBy) => {
  175. this.models.playlist.countDocuments({ createdBy: createdBy }, (err, c) => {
  176. return !(err || c >= 10);
  177. });
  178. }, 'Max 10 playlists per user.');
  179. this.schemas.playlist.path('songs').validate((songs) => {
  180. return songs.length <= 5000;
  181. }, 'Max 5000 songs per playlist.');
  182. this.schemas.playlist.path('songs').validate((songs) => {
  183. if (songs.length === 0) return true;
  184. return songs[0].duration <= 10800;
  185. }, 'Max 3 hours per song.');
  186. // Report
  187. this.schemas.report.path('description').validate((description) => {
  188. return (!description || (isLength(description, 0, 400) && regex.ascii.test(description)));
  189. }, 'Invalid description.');
  190. resolve();
  191. })
  192. .catch(err => {
  193. this.logger.error("DB_MODULE", err);
  194. reject(err);
  195. });
  196. })
  197. }
  198. passwordValid(password) {
  199. return isLength(password, 6, 200);
  200. }
  201. }