index.js 7.4 KB

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