index.js 8.9 KB

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