index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. const CoreClass = require("../../core.js");
  2. const mongoose = require("mongoose");
  3. const config = require("config");
  4. const regex = {
  5. azAZ09_: /^[A-Za-z0-9_]+$/,
  6. az09_: /^[a-z0-9_]+$/,
  7. emailSimple: /^[\x00-\x7F]+@[a-z0-9]+\.[a-z0-9]+(\.[a-z0-9]+)?$/,
  8. ascii: /^[\x00-\x7F]+$/,
  9. custom: (regex) => new RegExp(`^[${regex}]+$`),
  10. };
  11. const isLength = (string, min, max) => {
  12. return !(
  13. typeof string !== "string" ||
  14. string.length < min ||
  15. string.length > max
  16. );
  17. };
  18. const bluebird = require("bluebird");
  19. mongoose.Promise = bluebird;
  20. class DBModule extends CoreClass {
  21. constructor() {
  22. super("db");
  23. }
  24. initialize() {
  25. return new Promise((resolve, reject) => {
  26. this.schemas = {};
  27. this.models = {};
  28. const mongoUrl = config.get("mongo").url;
  29. mongoose
  30. .connect(mongoUrl, {
  31. useNewUrlParser: true,
  32. useUnifiedTopology: true,
  33. useCreateIndex: true
  34. })
  35. .then(() => {
  36. this.schemas = {
  37. song: new mongoose.Schema(require(`./schemas/song`)),
  38. queueSong: new mongoose.Schema(
  39. require(`./schemas/queueSong`)
  40. ),
  41. station: new mongoose.Schema(
  42. require(`./schemas/station`)
  43. ),
  44. user: new mongoose.Schema(require(`./schemas/user`)),
  45. activity: new mongoose.Schema(
  46. require(`./schemas/activity`)
  47. ),
  48. playlist: new mongoose.Schema(
  49. require(`./schemas/playlist`)
  50. ),
  51. news: new mongoose.Schema(require(`./schemas/news`)),
  52. report: new mongoose.Schema(
  53. require(`./schemas/report`)
  54. ),
  55. punishment: new mongoose.Schema(
  56. require(`./schemas/punishment`)
  57. ),
  58. };
  59. this.models = {
  60. song: mongoose.model("song", this.schemas.song),
  61. queueSong: mongoose.model(
  62. "queueSong",
  63. this.schemas.queueSong
  64. ),
  65. station: mongoose.model(
  66. "station",
  67. this.schemas.station
  68. ),
  69. user: mongoose.model("user", this.schemas.user),
  70. activity: mongoose.model(
  71. "activity",
  72. this.schemas.activity
  73. ),
  74. playlist: mongoose.model(
  75. "playlist",
  76. this.schemas.playlist
  77. ),
  78. news: mongoose.model("news", this.schemas.news),
  79. report: mongoose.model("report", this.schemas.report),
  80. punishment: mongoose.model(
  81. "punishment",
  82. this.schemas.punishment
  83. ),
  84. };
  85. mongoose.connection.on("error", (err) => {
  86. this.log("ERROR", err);
  87. });
  88. mongoose.connection.on("disconnected", () => {
  89. this.log(
  90. "ERROR",
  91. "Disconnected, going to try to reconnect..."
  92. );
  93. this.setStatus("RECONNECTING");
  94. });
  95. mongoose.connection.on("reconnected", () => {
  96. this.log("INFO", "Reconnected.");
  97. this.setStatus("READY");
  98. });
  99. mongoose.connection.on("reconnectFailed", () => {
  100. this.log(
  101. "INFO",
  102. "Reconnect failed, stopping reconnecting."
  103. );
  104. // this.failed = true;
  105. // this._lockdown();
  106. this.setStatus("FAILED");
  107. });
  108. // User
  109. this.schemas.user.path("username").validate((username) => {
  110. return (
  111. isLength(username, 2, 32) &&
  112. regex.custom("a-zA-Z0-9_-").test(username)
  113. );
  114. }, "Invalid username.");
  115. this.schemas.user
  116. .path("email.address")
  117. .validate((email) => {
  118. if (!isLength(email, 3, 254)) return false;
  119. if (email.indexOf("@") !== email.lastIndexOf("@"))
  120. return false;
  121. return (
  122. regex.emailSimple.test(email) &&
  123. regex.ascii.test(email)
  124. );
  125. }, "Invalid email.");
  126. // Station
  127. this.schemas.station.path("name").validate((id) => {
  128. return isLength(id, 2, 16) && regex.az09_.test(id);
  129. }, "Invalid station name.");
  130. this.schemas.station
  131. .path("displayName")
  132. .validate((displayName) => {
  133. return (
  134. isLength(displayName, 2, 32) &&
  135. regex.ascii.test(displayName)
  136. );
  137. }, "Invalid display name.");
  138. this.schemas.station
  139. .path("description")
  140. .validate((description) => {
  141. if (!isLength(description, 2, 200)) return false;
  142. let characters = description.split("");
  143. return (
  144. characters.filter((character) => {
  145. return character.charCodeAt(0) === 21328;
  146. }).length === 0
  147. );
  148. }, "Invalid display name.");
  149. this.schemas.station.path("owner").validate({
  150. validator: (owner) => {
  151. return new Promise((resolve, reject) => {
  152. this.models.station.countDocuments(
  153. { owner: owner },
  154. (err, c) => {
  155. if (err)
  156. reject(
  157. new Error(
  158. "A mongo error happened."
  159. )
  160. );
  161. else if (c >= 3)
  162. reject(
  163. new Error(
  164. "User already has 3 stations."
  165. )
  166. );
  167. else resolve();
  168. }
  169. );
  170. });
  171. },
  172. message: "User already has 3 stations.",
  173. });
  174. /*
  175. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  176. let totalDuration = 0;
  177. queue.forEach((song) => {
  178. totalDuration += song.duration;
  179. });
  180. return callback(totalDuration <= 3600 * 3);
  181. }, 'The max length of the queue is 3 hours.');
  182. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  183. if (queue.length === 0) return callback(true);
  184. let totalDuration = 0;
  185. const userId = queue[queue.length - 1].requestedBy;
  186. queue.forEach((song) => {
  187. if (userId === song.requestedBy) {
  188. totalDuration += song.duration;
  189. }
  190. });
  191. return callback(totalDuration <= 900);
  192. }, 'The max length of songs per user is 15 minutes.');
  193. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  194. if (queue.length === 0) return callback(true);
  195. let totalSongs = 0;
  196. const userId = queue[queue.length - 1].requestedBy;
  197. queue.forEach((song) => {
  198. if (userId === song.requestedBy) {
  199. totalSongs++;
  200. }
  201. });
  202. if (totalSongs <= 2) return callback(true);
  203. if (totalSongs > 3) return callback(false);
  204. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId) return callback(true);
  205. return callback(false);
  206. }, 'The max amount of songs per user is 3, and only 2 in a row is allowed.');
  207. */
  208. // Song
  209. let songTitle = (title) => {
  210. return isLength(title, 1, 100);
  211. };
  212. this.schemas.song
  213. .path("title")
  214. .validate(songTitle, "Invalid title.");
  215. this.schemas.queueSong
  216. .path("title")
  217. .validate(songTitle, "Invalid title.");
  218. this.schemas.song.path("artists").validate((artists) => {
  219. return !(artists.length < 1 || artists.length > 10);
  220. }, "Invalid artists.");
  221. this.schemas.queueSong
  222. .path("artists")
  223. .validate((artists) => {
  224. return !(artists.length < 0 || artists.length > 10);
  225. }, "Invalid artists.");
  226. let songArtists = (artists) => {
  227. return (
  228. artists.filter((artist) => {
  229. return (
  230. isLength(artist, 1, 64) && artist !== "NONE"
  231. );
  232. }).length === artists.length
  233. );
  234. };
  235. this.schemas.song
  236. .path("artists")
  237. .validate(songArtists, "Invalid artists.");
  238. this.schemas.queueSong
  239. .path("artists")
  240. .validate(songArtists, "Invalid artists.");
  241. let songGenres = (genres) => {
  242. if (genres.length < 1 || genres.length > 16)
  243. return false;
  244. return (
  245. genres.filter((genre) => {
  246. return (
  247. isLength(genre, 1, 32) &&
  248. regex.ascii.test(genre)
  249. );
  250. }).length === genres.length
  251. );
  252. };
  253. this.schemas.song
  254. .path("genres")
  255. .validate(songGenres, "Invalid genres.");
  256. this.schemas.queueSong
  257. .path("genres")
  258. .validate(songGenres, "Invalid genres.");
  259. let songThumbnail = (thumbnail) => {
  260. if (!isLength(thumbnail, 1, 256)) return false;
  261. if (config.get("cookie.secure") === true)
  262. return thumbnail.startsWith("https://");
  263. else
  264. return (
  265. thumbnail.startsWith("http://") ||
  266. thumbnail.startsWith("https://")
  267. );
  268. };
  269. this.schemas.song
  270. .path("thumbnail")
  271. .validate(songThumbnail, "Invalid thumbnail.");
  272. this.schemas.queueSong
  273. .path("thumbnail")
  274. .validate(songThumbnail, "Invalid thumbnail.");
  275. // Playlist
  276. this.schemas.playlist
  277. .path("displayName")
  278. .validate((displayName) => {
  279. return (
  280. isLength(displayName, 1, 32) &&
  281. regex.ascii.test(displayName)
  282. );
  283. }, "Invalid display name.");
  284. this.schemas.playlist
  285. .path("createdBy")
  286. .validate((createdBy) => {
  287. this.models.playlist.countDocuments(
  288. { createdBy: createdBy },
  289. (err, c) => {
  290. return !(err || c >= 10);
  291. }
  292. );
  293. }, "Max 10 playlists per user.");
  294. this.schemas.playlist.path("songs").validate((songs) => {
  295. return songs.length <= 5000;
  296. }, "Max 5000 songs per playlist.");
  297. this.schemas.playlist.path("songs").validate((songs) => {
  298. if (songs.length === 0) return true;
  299. return songs[0].duration <= 10800;
  300. }, "Max 3 hours per song.");
  301. // Report
  302. this.schemas.report
  303. .path("description")
  304. .validate((description) => {
  305. return (
  306. !description ||
  307. (isLength(description, 0, 400) &&
  308. regex.ascii.test(description))
  309. );
  310. }, "Invalid description.");
  311. resolve();
  312. })
  313. .catch((err) => {
  314. this.log("ERROR", err);
  315. reject(err);
  316. });
  317. });
  318. }
  319. GET_MODEL(payload) {
  320. return new Promise((resolve, reject) => {
  321. resolve(this.models[payload.modelName]);
  322. });
  323. }
  324. GET_SCHEMA(payload) {
  325. return new Promise((resolve, reject) => {
  326. resolve(this.schemas[payload.schemaName]);
  327. });
  328. }
  329. passwordValid(password) {
  330. return isLength(password, 6, 200);
  331. }
  332. }
  333. module.exports = new DBModule();