server.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. Meteor.startup(function () {
  2. reCAPTCHA.config({
  3. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  4. });
  5. Avatar.setOptions({
  6. fallbackType: "initials",
  7. defaultImageUrl: "http://static.boredpanda.com/blog/wp-content/uploads/2014/04/amazing-fox-photos-182.jpg",
  8. generateCSS: true,
  9. imageSizes: {
  10. 'header': 40
  11. }
  12. });
  13. var stations = [{tag: "edm", display: "EDM"}, {tag: "pop", display: "Pop"}]; //Rooms to be set on server startup
  14. for (var i in stations) {
  15. if (Rooms.find({type: stations[i]}).count() === 0) {
  16. createRoom(stations[i].display, stations[i].tag, false);
  17. }
  18. }
  19. emojione.ascii = true;
  20. Accounts.config({
  21. sendVerificationEmail: true
  22. });
  23. });
  24. var default_song = {
  25. id: "xKVcVSYmesU",
  26. mid: "ABCDEF",
  27. likes: 0,
  28. dislikes: 0,
  29. title: "Immortals",
  30. artist: "Fall Out Boy",
  31. img: "http://c.directlyrics.com/img/upload/fall-out-boy-sixth-album-cover.jpg",
  32. type: "YouTube",
  33. duration: 181,
  34. skipDuration: 0,
  35. requestedBy: "NONE",
  36. approvedBy: "NONE"
  37. };
  38. Alerts.update({active: true}, {$set: {active: false}}, {multi: true});
  39. var stations = [];
  40. var voteNum = 0;
  41. var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
  42. function createUniqueSongId() {
  43. var code = "";
  44. for (var i = 0; i < 6; i++) {
  45. code += chars[Math.floor(Math.random() * chars.length)];
  46. }
  47. if (Playlists.find({"songs.mid": code}).count() > 0) {
  48. return createUniqueSongId();
  49. } else {
  50. return code;
  51. }
  52. }
  53. function checkUsersPR() {
  54. var output = {};
  55. var connections = Meteor.server.stream_server.open_sockets;
  56. _.each(connections, function (connection) {
  57. // named subscriptions
  58. if (connection._meteorSession !== undefined && connection._meteorSession !== null) {
  59. var subs = connection._meteorSession._namedSubs;
  60. //var ip = connection.remoteAddress;
  61. var used_subs = [];
  62. for (var sub in subs) {
  63. var mySubName = subs[sub]._name;
  64. if (subs[sub]._params.length > 0) {
  65. mySubName += subs[sub]._params[0]; // assume one id parameter for now
  66. }
  67. if (used_subs.indexOf(mySubName) === -1) {
  68. used_subs.push(mySubName);
  69. if (!output[mySubName]) {
  70. output[mySubName] = 1;
  71. } else {
  72. output[mySubName] += 1;
  73. }
  74. }
  75. }
  76. }
  77. // there are also these 'universal subscriptions'
  78. //not sure what these are, i count none in my tests
  79. //var usubs = connection._meteorSession._universalSubs;
  80. });
  81. var emptyStations = [];
  82. stations.forEach(function (station) {
  83. emptyStations.push(station);
  84. });
  85. for (var key in output) {
  86. getStation(key, function (station) {
  87. emptyStations.splice(emptyStations.indexOf(station), 1);
  88. Rooms.update({type: key}, {$set: {users: output[key]}});
  89. });
  90. }
  91. emptyStations.forEach(function (emptyStation) {
  92. Rooms.update({type: emptyStation.type}, {$set: {users: 0}});
  93. });
  94. return output;
  95. }
  96. function getStation(type, cb) {
  97. stations.forEach(function (station) {
  98. if (station.type === type) {
  99. cb(station);
  100. return;
  101. }
  102. });
  103. }
  104. function createRoom(display, tag, private) {
  105. var type = tag;
  106. if (Rooms.find({type: type}).count() === 0) {
  107. Rooms.insert({
  108. display: display,
  109. type: type,
  110. users: 0,
  111. private: private,
  112. currentSong: {song: default_song, started: 0}
  113. }, function (err) {
  114. if (err) {
  115. throw err;
  116. } else {
  117. stations.push(new Station(type));
  118. }
  119. });
  120. } else {
  121. return "Room already exists";
  122. }
  123. }
  124. function Station(type) {
  125. if (Playlists.find({type: type}).count() === 0) {
  126. Playlists.insert({type: type, songs: [default_song], lastSong: 0});
  127. } else if (Playlists.findOne({type: type}).songs.length === 0) {
  128. Playlists.update({type: type}, {$push: {songs: default_song}});
  129. }
  130. Meteor.publish(type, function () {
  131. return undefined;
  132. });
  133. var self = this;
  134. var startedAt = Date.now();
  135. var playlist = Playlists.findOne({type: type});
  136. var songs = playlist.songs;
  137. var currentSong = playlist.lastSong;
  138. if (currentSong < (songs.length - 1)) {
  139. currentSong++;
  140. } else currentSong = 0;
  141. var currentTitle = songs[currentSong].title;
  142. var res = Rooms.update({type: type}, {
  143. $set: {
  144. currentSong: {song: songs[currentSong], started: startedAt},
  145. users: 0
  146. }
  147. });
  148. console.log(res);
  149. this.skipSong = function () {
  150. self.voted = [];
  151. voteNum = 0;
  152. Rooms.update({type: type}, {$set: {votes: 0}});
  153. songs = Playlists.findOne({type: type}).songs;
  154. songs.forEach(function (song, index) {
  155. if (song.title === currentTitle) {
  156. currentSong = index;
  157. }
  158. });
  159. if (currentSong < (songs.length - 1)) {
  160. currentSong++;
  161. } else currentSong = 0;
  162. if (songs);
  163. if (currentSong === 0) {
  164. this.shufflePlaylist();
  165. } else {
  166. if (songs[currentSong].mid === undefined) {
  167. var newSong = songs[currentSong];
  168. newSong.mid = createUniqueSongId();
  169. songs[currentSong].mid = newSong.mid;
  170. Playlists.update({type: type, "songs": songs[currentSong]}, {$set: {"songs.$": newSong}});
  171. }
  172. currentTitle = songs[currentSong].title;
  173. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  174. Rooms.update({type: type}, {$set: {timePaused: 0}});
  175. this.songTimer();
  176. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  177. }
  178. };
  179. this.shufflePlaylist = function () {
  180. voteNum = 0;
  181. Rooms.update({type: type}, {$set: {votes: 0}});
  182. self.voted = [];
  183. songs = Playlists.findOne({type: type}).songs;
  184. currentSong = 0;
  185. Playlists.update({type: type}, {$set: {"songs": []}});
  186. songs = shuffle(songs);
  187. songs.forEach(function (song) {
  188. if (song.mid === undefined) {
  189. song.mid = createUniqueSongId();
  190. }
  191. Playlists.update({type: type}, {$push: {"songs": song}});
  192. });
  193. currentTitle = songs[currentSong].title;
  194. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  195. Rooms.update({type: type}, {$set: {timePaused: 0}});
  196. this.songTimer();
  197. Rooms.update({type: type}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  198. };
  199. Rooms.update({type: type}, {$set: {timePaused: 0}});
  200. var timer;
  201. this.songTimer = function () {
  202. startedAt = Date.now();
  203. if (timer !== undefined) {
  204. timer.pause();
  205. }
  206. timer = new Timer(function () {
  207. self.skipSong();
  208. }, songs[currentSong].duration * 1000);
  209. };
  210. var state = Rooms.findOne({type: type}).state;
  211. this.pauseRoom = function () {
  212. if (state !== "paused") {
  213. timer.pause();
  214. Rooms.update({type: type}, {$set: {state: "paused"}});
  215. state = "paused";
  216. }
  217. };
  218. this.resumeRoom = function () {
  219. if (state !== "playing") {
  220. timer.resume();
  221. Rooms.update({type: type}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  222. state = "playing";
  223. }
  224. };
  225. this.cancelTimer = function () {
  226. timer.pause();
  227. };
  228. this.getState = function () {
  229. return state;
  230. };
  231. this.type = type;
  232. var private = Rooms.findOne({type: type}).private;
  233. if (typeof private !== "boolean") {
  234. Rooms.update({type: type}, {$set: {"private": false}});
  235. private = false;
  236. }
  237. this.private = private;
  238. this.unlock = function () {
  239. if (self.private) {
  240. self.private = false;
  241. Rooms.update({type: type}, {$set: {"private": false}});
  242. }
  243. };
  244. this.lock = function () {
  245. if (!self.private) {
  246. self.private = true;
  247. Rooms.update({type: type}, {$set: {"private": true}});
  248. }
  249. };
  250. this.songTimer();
  251. this.voted = [];
  252. }
  253. function shuffle(array) {
  254. var currentIndex = array.length, temporaryValue, randomIndex;
  255. // While there remain elements to shuffle...
  256. while (0 !== currentIndex) {
  257. // Pick a remaining element...
  258. randomIndex = Math.floor(Math.random() * currentIndex);
  259. currentIndex -= 1;
  260. // And swap it with the current element.
  261. temporaryValue = array[currentIndex];
  262. array[currentIndex] = array[randomIndex];
  263. array[randomIndex] = temporaryValue;
  264. }
  265. return array;
  266. }
  267. function Timer(callback, delay) {
  268. var timerId, start, remaining = delay;
  269. var timeWhenPaused = 0;
  270. var timePaused = new Date();
  271. this.pause = function () {
  272. Meteor.clearTimeout(timerId);
  273. remaining -= new Date() - start;
  274. timePaused = new Date();
  275. };
  276. this.resume = function () {
  277. start = new Date();
  278. Meteor.clearTimeout(timerId);
  279. timerId = Meteor.setTimeout(callback, remaining);
  280. timeWhenPaused += new Date() - timePaused;
  281. };
  282. this.timeWhenPaused = function () {
  283. return timeWhenPaused;
  284. };
  285. this.resume();
  286. }
  287. Meteor.users.deny({
  288. update: function () {
  289. return true;
  290. }
  291. });
  292. Meteor.users.deny({
  293. insert: function () {
  294. return true;
  295. }
  296. });
  297. Meteor.users.deny({
  298. remove: function () {
  299. return true;
  300. }
  301. });
  302. function getSongDuration(query, artistName) {
  303. var duration;
  304. var search = query;
  305. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  306. for (var i in res.data) {
  307. for (var j in res.data[i].items) {
  308. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  309. duration = res.data[i].items[j].duration_ms / 1000;
  310. return duration;
  311. }
  312. }
  313. }
  314. return 0;
  315. }
  316. function getSongAlbumArt(query, artistName) {
  317. var albumart;
  318. var search = query;
  319. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  320. for (var i in res.data) {
  321. for (var j in res.data[i].items) {
  322. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  323. albumart = res.data[i].items[j].album.images[1].url
  324. return albumart;
  325. }
  326. }
  327. }
  328. }
  329. //var room_types = ["edm", "nightcore"];
  330. var songsArr = [];
  331. Rooms.find({}).fetch().forEach(function (room) {
  332. var type = room.type;
  333. if (Playlists.find({type: type}).count() === 0) {
  334. Playlists.insert({type: type, songs: []});
  335. }
  336. if (Playlists.findOne({type: type}).songs.length === 0) {
  337. // Add a global video to Playlist so it can proceed
  338. } else {
  339. stations.push(new Station(type));
  340. }
  341. });
  342. Accounts.validateNewUser(function (user) {
  343. var username;
  344. if (user.services) {
  345. if (user.services.github) {
  346. username = user.services.github.username;
  347. } else if (user.services.facebook) {
  348. username = user.services.facebook.first_name;
  349. } else if (user.services.password) {
  350. username = user.username;
  351. }
  352. }
  353. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  354. throw new Meteor.Error(403, "An account with that username already exists.");
  355. } else {
  356. return true;
  357. }
  358. });
  359. Accounts.onCreateUser(function (options, user) {
  360. var username;
  361. if (user.services) {
  362. if (user.services.github) {
  363. username = user.services.github.username;
  364. } else if (user.services.facebook) {
  365. username = user.services.facebook.first_name;
  366. } else if (user.services.password) {
  367. username = user.username;
  368. }
  369. }
  370. user.profile = {
  371. username: username,
  372. usernameL: username.toLowerCase(),
  373. rank: "default",
  374. liked: [],
  375. disliked: [],
  376. settings: {showRating: false},
  377. realname: ""
  378. };
  379. return user;
  380. });
  381. Meteor.publish("alerts", function () {
  382. return Alerts.find({active: true})
  383. });
  384. Meteor.publish("userData", function (userId) {
  385. if (userId !== undefined) {
  386. return Meteor.users.find(userId, {fields: {"services.github.username": 1, "punishments": 1}})
  387. } else {
  388. return undefined;
  389. }
  390. });
  391. Meteor.publish("allAlerts", function () {
  392. return Alerts.find({active: false})
  393. });
  394. Meteor.publish("playlists", function () {
  395. return Playlists.find({})
  396. });
  397. Meteor.publish("rooms", function () {
  398. return Rooms.find({});
  399. });
  400. Meteor.publish("queues", function () {
  401. return Queues.find({});
  402. });
  403. Meteor.publish("reports", function () {
  404. return Reports.find({});
  405. });
  406. Meteor.publish("chat", function () {
  407. return Chat.find({});
  408. });
  409. Meteor.publish("userProfiles", function (username) {
  410. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  411. if (settings !== undefined && settings.profile.settings) {
  412. settings = settings.profile.settings;
  413. if (settings.showRating === true) {
  414. return Meteor.users.find({"profile.usernameL": username}, {
  415. fields: {
  416. "profile.username": 1,
  417. "profile.usernameL": 1,
  418. "profile.rank": 1,
  419. createdAt: 1,
  420. "profile.liked": 1,
  421. "profile.disliked": 1,
  422. "profile.settings": 1,
  423. "profile.realname": 1
  424. }
  425. });
  426. }
  427. }
  428. return Meteor.users.find({"profile.usernameL": username}, {
  429. fields: {
  430. "profile.username": 1,
  431. "profile.usernameL": 1,
  432. "profile.rank": 1,
  433. createdAt: 1,
  434. "profile.settings": 1,
  435. "profile.realname": 1
  436. }
  437. });
  438. });
  439. Meteor.publish("isAdmin", function () {
  440. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  441. });
  442. Meteor.publish("isModerator", function () {
  443. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  444. });
  445. Meteor.publish("feedback", function(){
  446. return Feedback.find();
  447. })
  448. function isAdmin() {
  449. var userData = Meteor.users.find(Meteor.userId());
  450. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  451. return true;
  452. } else {
  453. return false;
  454. }
  455. }
  456. function isModerator() {
  457. var userData = Meteor.users.find(Meteor.userId());
  458. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  459. return true;
  460. } else {
  461. return isAdmin();
  462. }
  463. }
  464. function isBanned() {
  465. var userData = Meteor.users.findOne(Meteor.userId());
  466. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  467. var ban = userData.punishments.ban;
  468. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  469. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  470. return false;
  471. } else {
  472. return true;
  473. }
  474. } else {
  475. return false;
  476. }
  477. }
  478. function isMuted() {
  479. var userData = Meteor.users.findOne(Meteor.userId());
  480. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.mute !== undefined) {
  481. var mute = userData.punishments.mute;
  482. if (new Date(mute.bannedUntil).getTime() <= new Date().getTime()) {
  483. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.mute": ""}});
  484. return false;
  485. } else {
  486. return true;
  487. }
  488. } else {
  489. return false;
  490. }
  491. }
  492. Meteor.methods({
  493. lockRoom: function (type) {
  494. if (isAdmin() && !isBanned()) {
  495. getStation(type, function (station) {
  496. station.lock();
  497. });
  498. } else {
  499. throw new Meteor.Error(403, "Invalid permissions.");
  500. }
  501. },
  502. unlockRoom: function (type) {
  503. if (isAdmin() && !isBanned()) {
  504. getStation(type, function (station) {
  505. station.unlock();
  506. });
  507. } else {
  508. throw new Meteor.Error(403, "Invalid permissions.");
  509. }
  510. },
  511. banUser: function (username, period, reason) {
  512. if (isAdmin() && !isBanned()) {
  513. var user = Meteor.user();
  514. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  515. var bannedUntil = (new Date).getTime() + (period * 1000);
  516. if (bannedUntil > 8640000000000000) {
  517. bannedUntil = 8640000000000000;
  518. }
  519. bannedUntil = new Date(bannedUntil);
  520. var banObject = {
  521. bannedBy: user.profile.usernameL,
  522. bannedAt: new Date(Date.now()),
  523. bannedReason: reason,
  524. bannedUntil: bannedUntil
  525. };
  526. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  527. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  528. } else {
  529. throw new Meteor.Error(403, "Invalid permissions.");
  530. }
  531. },
  532. muteUser: function (username, period) {
  533. if (isAdmin() && !isBanned()) {
  534. var user = Meteor.user();
  535. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  536. if (period === undefined || Number(period) === 0) {
  537. mutedUntil = 8640000000000000;
  538. } else {
  539. var mutedUntil = (new Date).getTime() + (period * 1000);
  540. if (mutedUntil > 8640000000000000) {
  541. mutedUntil = 8640000000000000;
  542. }
  543. }
  544. mutedUntil = new Date(mutedUntil);
  545. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  546. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  547. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  548. } else {
  549. throw new Meteor.Error(403, "Invalid permissions.");
  550. }
  551. },
  552. unbanUser: function (username) {
  553. if (isAdmin() && !isBanned()) {
  554. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  555. } else {
  556. throw new Meteor.Error(403, "Invalid permissions.");
  557. }
  558. },
  559. unsilenceUser: function (username) {
  560. if (isAdmin() && !isBanned()) {
  561. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  562. } else {
  563. throw new Meteor.Error(403, "Invalid permissions.");
  564. }
  565. },
  566. isBanned: function () {
  567. return isBanned();
  568. },
  569. isMuted: function () {
  570. return isMuted();
  571. },
  572. updateSettings: function (showRating) {
  573. if (Meteor.userId() && !isBanned()) {
  574. var user = Meteor.user();
  575. if (showRating !== true && showRating !== false) {
  576. showRating = false;
  577. }
  578. if (user.profile.settings) {
  579. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  580. } else {
  581. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  582. }
  583. } else {
  584. throw new Meteor.Error(403, "Invalid permissions.");
  585. }
  586. },
  587. resetRating: function () {
  588. if (isAdmin() && !isBanned()) {
  589. stations.forEach(function (station) {
  590. var type = station.type;
  591. var temp_songs = Playlists.findOne({type: type}).songs;
  592. Playlists.update({type: type}, {$set: {"songs": []}});
  593. temp_songs.forEach(function (song) {
  594. song.likes = 0;
  595. song.dislikes = 0;
  596. Playlists.update({type: type}, {$push: {"songs": song}});
  597. });
  598. });
  599. Meteor.users.update({}, {$set: {"profile.liked": [], "profile.disliked": []}}, {multi: true});
  600. } else {
  601. throw Meteor.Error(403, "Invalid permissions.");
  602. }
  603. },
  604. removeAlerts: function () {
  605. if (isAdmin() && !isBanned()) {
  606. Alerts.update({active: true}, {$set: {active: false}}, {multi: true});
  607. } else {
  608. throw Meteor.Error(403, "Invalid permissions.");
  609. }
  610. },
  611. addAlert: function (description, priority) {
  612. if (isAdmin()) {
  613. if (description.length > 0 && description.length < 400) {
  614. var username = Meteor.user().profile.username;
  615. if (["danger", "warning", "success", "primary"].indexOf(priority) === -1) {
  616. priority = "warning";
  617. }
  618. Alerts.insert({description: description, priority: priority, active: true, createdBy: username});
  619. return true;
  620. } else {
  621. throw Meteor.Error(403, "Invalid description length.");
  622. }
  623. } else {
  624. throw Meteor.Error(403, "Invalid permissions.");
  625. }
  626. },
  627. sendMessage: function (type, message) {
  628. if (Meteor.userId() && !isBanned() && !isMuted()) {
  629. var user = Meteor.user();
  630. var time = new Date();
  631. var rawrank = user.profile.rank;
  632. var username = user.profile.username;
  633. var profanity = false;
  634. var mentionUsername;
  635. var isCurUserMentioned;
  636. if (message.indexOf("@") !== -1) {
  637. var messageArr = message.split(" ");
  638. for (var i in messageArr) {
  639. if (messageArr[i].indexOf("@") !== -1) {
  640. var mention = messageArr[i];
  641. }
  642. }
  643. Meteor.users.find().forEach(function (user) {
  644. if (mention.indexOf(user.profile.username) !== -1) {
  645. mentionUsername = true;
  646. isCurUserMentioned = Meteor.user().profile.username === user.profile.username;
  647. }
  648. ;
  649. })
  650. }
  651. if (!message.replace(/\s/g, "").length > 0) {
  652. throw new Meteor.Error(406, "Message length cannot be 0.");
  653. }
  654. if (message.length > 300) {
  655. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  656. }
  657. else if (user.profile.rank === "admin") {
  658. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  659. if (res.content.indexOf("true") > -1) {
  660. return true;
  661. } else {
  662. Chat.insert({
  663. type: type,
  664. rawrank: rawrank,
  665. rank: "[A]",
  666. message: message,
  667. curUserMention: isCurUserMentioned,
  668. isMentioned: mentionUsername,
  669. time: time,
  670. username: username
  671. });
  672. }
  673. });
  674. return true;
  675. }
  676. else if (user.profile.rank === "moderator") {
  677. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  678. if (res.content.indexOf("true") > -1) {
  679. return true;
  680. } else {
  681. Chat.insert({
  682. type: type,
  683. rawrank: rawrank,
  684. rank: "[M]",
  685. message: message,
  686. time: time,
  687. username: username
  688. });
  689. }
  690. });
  691. return true;
  692. }
  693. else {
  694. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  695. if (res.content.indexOf("true") > -1) {
  696. return true;
  697. } else {
  698. Chat.insert({
  699. type: type,
  700. rawrank: rawrank,
  701. rank: "",
  702. message: message,
  703. time: time,
  704. username: username
  705. });
  706. }
  707. });
  708. return true;
  709. }
  710. } else {
  711. throw new Meteor.Error(403, "Invalid permissions.");
  712. }
  713. },
  714. likeSong: function (mid) {
  715. if (Meteor.userId() && !isBanned()) {
  716. var user = Meteor.user();
  717. if (user.profile.liked.indexOf(mid) === -1) {
  718. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  719. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  720. } else {
  721. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  722. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  723. }
  724. if (user.profile.disliked.indexOf(mid) !== -1) {
  725. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  726. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  727. }
  728. return true;
  729. } else {
  730. throw new Meteor.Error(403, "Invalid permissions.");
  731. }
  732. },
  733. dislikeSong: function (mid) {
  734. if (Meteor.userId() && !isBanned()) {
  735. var user = Meteor.user();
  736. if (user.profile.disliked.indexOf(mid) === -1) {
  737. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  738. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  739. } else {
  740. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  741. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  742. }
  743. if (user.profile.liked.indexOf(mid) !== -1) {
  744. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  745. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  746. }
  747. return true;
  748. } else {
  749. throw new Meteor.Error(403, "Invalid permissions.");
  750. }
  751. },
  752. voteSkip: function (type) {
  753. if (Meteor.userId() && !isBanned()) {
  754. var user = Meteor.user();
  755. getStation(type, function (station) {
  756. if (station.voted.indexOf(user.profile.username) === -1) {
  757. station.voted.push(user.profile.username);
  758. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  759. if (station.voted.length === 3) {
  760. station.skipSong();
  761. }
  762. } else {
  763. throw new Meteor.Error(401, "Already voted.");
  764. }
  765. })
  766. }
  767. },
  768. submitReport: function (room, reportData) {
  769. if (Meteor.userId() && !isBanned()) {
  770. room = room.toLowerCase();
  771. if (Rooms.find({type: room}).count() === 1) {
  772. if (Reports.find({room: room}).count() === 0) {
  773. Reports.insert({room: room, report: []});
  774. }
  775. if (reportData !== undefined) {
  776. Reports.update({room: room}, {
  777. $push: {
  778. report: {
  779. song: reportData.song,
  780. type: reportData.type,
  781. reason: reportData.reason,
  782. other: reportData.other
  783. }
  784. }
  785. });
  786. return true;
  787. } else {
  788. throw new Meteor.Error(403, "Invalid data.");
  789. }
  790. } else {
  791. throw new Meteor.Error(403, "Invalid genre.");
  792. }
  793. } else {
  794. throw new Meteor.Error(403, "Invalid permissions.");
  795. }
  796. },
  797. shufflePlaylist: function (type) {
  798. if (isAdmin() && !isBanned()) {
  799. getStation(type, function (station) {
  800. if (station === undefined) {
  801. throw new Meteor.Error(404, "Station not found.");
  802. } else {
  803. station.cancelTimer();
  804. station.shufflePlaylist();
  805. }
  806. });
  807. }
  808. },
  809. skipSong: function (type) {
  810. if (isAdmin() && !isBanned()) {
  811. getStation(type, function (station) {
  812. if (station === undefined) {
  813. throw new Meteor.Error(404, "Station not found.");
  814. } else {
  815. station.skipSong();
  816. }
  817. });
  818. }
  819. },
  820. pauseRoom: function (type) {
  821. if (isAdmin() && !isBanned()) {
  822. getStation(type, function (station) {
  823. if (station === undefined) {
  824. throw new Meteor.Error(403, "Room doesn't exist.");
  825. } else {
  826. station.pauseRoom();
  827. }
  828. });
  829. } else {
  830. throw new Meteor.Error(403, "Invalid permissions.");
  831. }
  832. },
  833. resumeRoom: function (type) {
  834. if (isAdmin() && !isBanned()) {
  835. getStation(type, function (station) {
  836. if (station === undefined) {
  837. throw new Meteor.Error(403, "Room doesn't exist.");
  838. } else {
  839. station.resumeRoom();
  840. }
  841. });
  842. } else {
  843. throw new Meteor.Error(403, "Invalid permissions.");
  844. }
  845. },
  846. createUserMethod: function (formData, captchaData) {
  847. if (!isBanned()) {
  848. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  849. if (!verifyCaptchaResponse.success) {
  850. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  851. } else {
  852. Accounts.createUser({
  853. username: formData.username,
  854. email: formData.email,
  855. password: formData.password
  856. });
  857. }
  858. return true;
  859. }
  860. },
  861. addSongToQueue: function (type, songData) {
  862. if (Meteor.userId() && !isBanned()) {
  863. type = type.toLowerCase();
  864. var userId = Meteor.userId();
  865. if (Rooms.find({type: type}).count() === 1) {
  866. if (Queues.find({type: type}).count() === 0) {
  867. Queues.insert({type: type, songs: []});
  868. }
  869. var requiredProperties = ["title", "artist", "img", "id"];
  870. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  871. for (var property in requiredProperties) {
  872. if (songData[requiredProperties[property]] === undefined) {
  873. throw new Meteor.Error(403, "Invalid data.");
  874. }
  875. }
  876. songData.duration = Number(getSongDuration(songData.title, songData.artist));
  877. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  878. songData.skipDuration = 0;
  879. songData.likes = 0;
  880. songData.dislikes = 0;
  881. var mid = createUniqueSongId();
  882. if (mid !== undefined) {
  883. songData.mid = mid;
  884. Queues.update({type: type}, {
  885. $push: {
  886. songs: {
  887. id: songData.id,
  888. mid: songData.mid,
  889. title: songData.title,
  890. artist: songData.artist,
  891. duration: songData.duration,
  892. skipDuration: songData.skipDuration,
  893. likes: songData.likes,
  894. dislikes: songData.dislikes,
  895. img: songData.img,
  896. requestedBy: userId
  897. }
  898. }
  899. });
  900. var songsRequested = (Meteor.user().profile !== undefined && Meteor.user().profile.statistics !== undefined && Meteor.user().profile.statistics.songsRequested !== undefined) ? Meteor.user().profile.statistics.songsRequested : 0;
  901. songsRequested++;
  902. Meteor.users.update(Meteor.userId(), {$set: {"profile.statistics.songsRequested": songsRequested}}); // TODO Make mongo query use $inc correctly.
  903. return true;
  904. } else {
  905. throw new Meteor.Error(500, "Am error occured.");
  906. }
  907. } else {
  908. throw new Meteor.Error(403, "Invalid data.");
  909. }
  910. } else {
  911. throw new Meteor.Error(403, "Invalid genre.");
  912. }
  913. } else {
  914. throw new Meteor.Error(403, "Invalid permissions.");
  915. }
  916. },
  917. updateQueueSong: function (genre, oldSong, newSong) {
  918. if (isModerator() && !isBanned()) {
  919. newSong.mid = oldSong.mid;
  920. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}}, function(err) {
  921. console.log(err);
  922. if (err) {
  923. throw err.sanitizedError;
  924. } else {
  925. return true;
  926. }
  927. });
  928. } else {
  929. throw new Meteor.Error(403, "Invalid permissions.");
  930. }
  931. },
  932. updatePlaylistSong: function (genre, oldSong, newSong) {
  933. if (isModerator() && !isBanned()) {
  934. newSong.mid = oldSong.mid;
  935. newSong.approvedBy = Meteor.userId();
  936. console.log(genre);
  937. console.log(oldSong);
  938. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}}, function(err) {
  939. console.log(err);
  940. if (err) {
  941. throw err.sanitizedError;
  942. } else {
  943. return true;
  944. }
  945. });
  946. return true;
  947. } else {
  948. throw new Meteor.Error(403, "Invalid permissions.");
  949. }
  950. },
  951. removeSongFromQueue: function (type, mid) {
  952. if (isModerator() && !isBanned()) {
  953. type = type.toLowerCase();
  954. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  955. } else {
  956. throw new Meteor.Error(403, "Invalid permissions.");
  957. }
  958. },
  959. removeSongFromPlaylist: function (type, mid) {
  960. if (isModerator() && !isBanned()) {
  961. type = type.toLowerCase();
  962. var songs = Playlists.findOne({type: type}).songs;
  963. var song = undefined;
  964. songs.forEach(function (curr_song) {
  965. if (mid === curr_song.mid) {
  966. song = curr_song;
  967. return;
  968. }
  969. });
  970. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  971. if (song !== undefined) {
  972. song.deletedBy = Meteor.userId();
  973. song.deletedAt = new Date(Date.now());
  974. if (Deleted.find({type: type}).count() === 0) {
  975. Deleted.insert({type: type, songs: [song]});
  976. } else {
  977. Deleted.update({type: type}, {$push: {songs: song}});
  978. }
  979. }
  980. } else {
  981. throw new Meteor.Error(403, "Invalid permissions.");
  982. }
  983. },
  984. addSongToPlaylist: function (type, songData) {
  985. console.log(songData);
  986. if (isModerator() && !isBanned()) {
  987. type = type.toLowerCase();
  988. if (Rooms.find({type: type}).count() === 1) {
  989. if (Playlists.find({type: type}).count() === 0) {
  990. Playlists.insert({type: type, songs: []});
  991. }
  992. var requiredProperties = ["mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy"];
  993. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  994. for (var property in requiredProperties) {
  995. if (songData[requiredProperties[property]] === undefined) {
  996. throw new Meteor.Error(403, "Invalid data.");
  997. }
  998. }
  999. Playlists.update({type: type}, {
  1000. $push: {
  1001. songs: {
  1002. id: songData.id,
  1003. mid: songData.mid,
  1004. title: songData.title,
  1005. artist: songData.artist,
  1006. duration: songData.duration,
  1007. skipDuration: Number(songData.skipDuration),
  1008. img: songData.img,
  1009. type: songData.type,
  1010. likes: Number(songData.likes),
  1011. dislikes: Number(songData.dislikes),
  1012. requestedBy: songData.requestedBy,
  1013. approvedBy: Meteor.userId()
  1014. }
  1015. }
  1016. });
  1017. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  1018. getStation(type, function (station) {
  1019. if (station === undefined) {
  1020. stations.push(new Station(type));
  1021. }
  1022. });
  1023. return true;
  1024. } else {
  1025. throw new Meteor.Error(403, "Invalid data.");
  1026. }
  1027. } else {
  1028. throw new Meteor.Error(403, "Invalid genre.");
  1029. }
  1030. } else {
  1031. throw new Meteor.Error(403, "Invalid permissions.");
  1032. }
  1033. },
  1034. createRoom: function (display, tag, private) {
  1035. if (isAdmin() && !isBanned()) {
  1036. createRoom(display, tag, private);
  1037. } else {
  1038. throw new Meteor.Error(403, "Invalid permissions.");
  1039. }
  1040. },
  1041. deleteRoom: function (type) {
  1042. if (isAdmin() && !isBanned()) {
  1043. Rooms.remove({type: type});
  1044. Playlists.remove({type: type});
  1045. Queues.remove({type: type});
  1046. return true;
  1047. } else {
  1048. throw new Meteor.Error(403, "Invalid permissions.");
  1049. }
  1050. },
  1051. getUserNum: function () {
  1052. if (!isBanned()) {
  1053. return Object.keys(Meteor.default_server.sessions).length;
  1054. }
  1055. },
  1056. getTotalUsers: function () {
  1057. return Meteor.users.find().count();
  1058. },
  1059. updateRealName: function (realname) {
  1060. if (Meteor.userId()) {
  1061. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  1062. Meteor.users.update(Meteor.userId(), {
  1063. $set: {"profile.realname": realname},
  1064. $push: {"profile.realnames": oldName}
  1065. });
  1066. } else {
  1067. throw new Meteor.Error(403, "Invalid permissions.");
  1068. }
  1069. },
  1070. updateUserName: function (newUserName) {
  1071. if (Meteor.userId()) {
  1072. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  1073. Meteor.users.update(Meteor.userId(), {
  1074. $set: {
  1075. "username": newUserName,
  1076. "profile.username": newUserName,
  1077. "profile.usernameL": newUserName.toLowerCase()
  1078. }, $push: {"profile.usernames": oldUsername}
  1079. });
  1080. } else {
  1081. throw new Meteor.Error(403, "Invalid permissions.");
  1082. }
  1083. },
  1084. /*updateUserRank: function(newRank){
  1085. if (Meteor.userId()) {
  1086. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  1087. } else {
  1088. throw new Meteor.Error(403, "Invalid permissions.");
  1089. }
  1090. },*/
  1091. deleteAccount: function () {
  1092. if (Meteor.userId()) {
  1093. var user = Meteor.users.findOne(Meteor.userId());
  1094. Meteor.users.remove({_id: Meteor.userId()});
  1095. } else {
  1096. throw new Meteor.Error(403, "Invalid permissions.");
  1097. }
  1098. },
  1099. sendFeedback: function(message){
  1100. if(Meteor.userId() && !isBanned()) {
  1101. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1102. if (res.content.indexOf("true") > -1) {
  1103. return true;
  1104. } else {
  1105. Feedback.insert({
  1106. "username": Meteor.user().profile.username,
  1107. "message": message,
  1108. upvotes: 0,
  1109. upvotedBy: []
  1110. })
  1111. }
  1112. });
  1113. }
  1114. },
  1115. upvoteFeedback: function(message){
  1116. if(Meteor.userId() && !isBanned()){
  1117. console.log(Feedback.findOne({"message": message}));
  1118. if(Feedback.findOne({"message": message}).upvotedBy.indexOf(Meteor.user().profile.username) === -1){
  1119. Feedback.update({"message": message}, {$inc: {"upvotes": 1}});
  1120. Feedback.update({"message": message}, {$push: {"upvotedBy": Meteor.user().profile.username}});
  1121. } else{
  1122. Feedback.update({"message": message}, {$inc: {"upvotes": -1}});
  1123. Feedback.update({"message": message}, {$pull: {"upvotedBy": Meteor.user().profile.username}});
  1124. }
  1125. }
  1126. },
  1127. deleteFeedback: function(message){
  1128. if(isAdmin() && !isBanned()){
  1129. Feedback.remove({"message": message});
  1130. } else {
  1131. throw new Meteor.Error(403, "Invalid permissions.");
  1132. }
  1133. },
  1134. updateFeedback: function(oldMessage, newMessage){
  1135. if(isAdmin() && !isBanned()){
  1136. Feedback.update({"message": oldMessage}, {$set: {"message": newMessage}});
  1137. } else {
  1138. throw new Meteor.Error(403, "Invalid permissions.");
  1139. }
  1140. },
  1141. editRoomDesc: function(type, description){
  1142. if(isAdmin() && !isBanned()){
  1143. Rooms.update({type: type}, {$set: {"roomDesc": description}});
  1144. } else {
  1145. throw new Meteor.Error(403, "Invalid permissions.");
  1146. }
  1147. }
  1148. });
  1149. Meteor.setInterval(function () {
  1150. checkUsersPR();
  1151. }, 10000);
  1152. Meteor.users.after.insert(function (err, user) {
  1153. Accounts.sendVerificationEmail(user._id);
  1154. });