server.js 40 KB

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