index.js 8.9 KB

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