index.js 15 KB

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