server.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  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. var mentionUsername;
  603. var isCurUserMentioned;
  604. if(message.indexOf("@") !== -1) {
  605. var messageArr = message.split(" ");
  606. for (var i in messageArr) {
  607. if (messageArr[i].indexOf("@") !== -1) {
  608. var mention = messageArr[i];
  609. }
  610. }
  611. Meteor.users.find().forEach(function(user){
  612. if(mention.indexOf(user.profile.username) !== -1){
  613. mentionUsername = true;
  614. isCurUserMentioned = Meteor.user().profile.username === user.profile.username;
  615. };
  616. })
  617. }
  618. if (!message.replace(/\s/g, "").length > 0) {
  619. throw new Meteor.Error(406, "Message length cannot be 0.");
  620. }
  621. if (message.length > 300) {
  622. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  623. }
  624. else if (user.profile.rank === "admin") {
  625. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function(err,res){
  626. if(res.content.indexOf("true") > -1){
  627. return true;
  628. } else{
  629. Chat.insert({type: type, rawrank: rawrank, rank: "[A]", message: message, curUserMention: isCurUserMentioned, isMentioned: mentionUsername, time: time, username: username});
  630. }
  631. });
  632. return true;
  633. }
  634. else if (user.profile.rank === "moderator") {
  635. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function(err,res){
  636. if(res.content.indexOf("true") > -1){
  637. return true;
  638. } else{
  639. Chat.insert({type: type, rawrank: rawrank, rank: "[M]", message: message, time: time, username: username});
  640. }
  641. });
  642. return true;
  643. }
  644. else {
  645. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function(err,res){
  646. if(res.content.indexOf("true") > -1){
  647. return true;
  648. } else{
  649. Chat.insert({type: type, rawrank: rawrank, rank: "", message: message, time: time, username: username});
  650. }
  651. });
  652. return true;
  653. }
  654. } else {
  655. throw new Meteor.Error(403, "Invalid permissions.");
  656. }
  657. },
  658. likeSong: function(mid) {
  659. if (Meteor.userId() && !isBanned()) {
  660. var user = Meteor.user();
  661. if (user.profile.liked.indexOf(mid) === -1) {
  662. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  663. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": 1}})
  664. } else {
  665. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  666. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}})
  667. }
  668. if (user.profile.disliked.indexOf(mid) !== -1) {
  669. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  670. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}})
  671. }
  672. return true;
  673. } else {
  674. throw new Meteor.Error(403, "Invalid permissions.");
  675. }
  676. },
  677. dislikeSong: function(mid) {
  678. if (Meteor.userId() && !isBanned()) {
  679. var user = Meteor.user();
  680. if (user.profile.disliked.indexOf(mid) === -1) {
  681. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  682. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": 1}});
  683. } else {
  684. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  685. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.dislikes": -1}});
  686. }
  687. if (user.profile.liked.indexOf(mid) !== -1) {
  688. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  689. Playlists.update({"songs.mid": mid}, {$inc: {"songs.$.likes": -1}});
  690. }
  691. return true;
  692. } else {
  693. throw new Meteor.Error(403, "Invalid permissions.");
  694. }
  695. },
  696. voteSkip: function(type){
  697. if(Meteor.userId() && !isBanned()){
  698. var user = Meteor.user();
  699. getStation(type, function(station){
  700. if(station.voted.indexOf(user.profile.username) === -1){
  701. station.voted.push(user.profile.username);
  702. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  703. if(station.voted.length === 3){
  704. station.skipSong();
  705. }
  706. } else{
  707. throw new Meteor.Error(401, "Already voted.");
  708. }
  709. })
  710. }
  711. },
  712. submitReport: function(room, reportData) {
  713. if (Meteor.userId() && !isBanned()) {
  714. room = room.toLowerCase();
  715. if (Rooms.find({type: room}).count() === 1) {
  716. if (Reports.find({room: room}).count() === 0) {
  717. Reports.insert({room: room, report: []});
  718. }
  719. if (reportData !== undefined) {
  720. Reports.update({room: room}, {
  721. $push: {
  722. report: {
  723. song: reportData.song,
  724. type: reportData.type,
  725. reason: reportData.reason,
  726. other: reportData.other
  727. }
  728. }
  729. });
  730. return true;
  731. } else {
  732. throw new Meteor.Error(403, "Invalid data.");
  733. }
  734. } else {
  735. throw new Meteor.Error(403, "Invalid genre.");
  736. }
  737. } else {
  738. throw new Meteor.Error(403, "Invalid permissions.");
  739. }
  740. },
  741. shufflePlaylist: function(type) {
  742. if (isAdmin() && !isBanned()) {
  743. getStation(type, function(station) {
  744. if (station === undefined) {
  745. throw new Meteor.Error(404, "Station not found.");
  746. } else {
  747. station.cancelTimer();
  748. station.shufflePlaylist();
  749. }
  750. });
  751. }
  752. },
  753. skipSong: function(type) {
  754. if (isAdmin() && !isBanned()) {
  755. getStation(type, function(station) {
  756. if (station === undefined) {
  757. throw new Meteor.Error(404, "Station not found.");
  758. } else {
  759. station.skipSong();
  760. }
  761. });
  762. }
  763. },
  764. pauseRoom: function(type) {
  765. if (isAdmin() && !isBanned()) {
  766. getStation(type, function(station) {
  767. if (station === undefined) {
  768. throw new Meteor.Error(403, "Room doesn't exist.");
  769. } else {
  770. station.pauseRoom();
  771. }
  772. });
  773. } else {
  774. throw new Meteor.Error(403, "Invalid permissions.");
  775. }
  776. },
  777. resumeRoom: function(type) {
  778. if (isAdmin() && !isBanned()) {
  779. getStation(type, function(station) {
  780. if (station === undefined) {
  781. throw new Meteor.Error(403, "Room doesn't exist.");
  782. } else {
  783. station.resumeRoom();
  784. }
  785. });
  786. } else {
  787. throw new Meteor.Error(403, "Invalid permissions.");
  788. }
  789. },
  790. createUserMethod: function(formData, captchaData) {
  791. if (!isBanned()) {
  792. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  793. if (!verifyCaptchaResponse.success) {
  794. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  795. } else {
  796. Accounts.createUser({
  797. username: formData.username,
  798. email: formData.email,
  799. password: formData.password
  800. });
  801. }
  802. return true;
  803. }
  804. },
  805. addSongToQueue: function(type, songData) {
  806. if (Meteor.userId() && !isBanned()) {
  807. type = type.toLowerCase();
  808. var userId = Meteor.userId();
  809. if (Rooms.find({type: type}).count() === 1) {
  810. if (Queues.find({type: type}).count() === 0) {
  811. Queues.insert({type: type, songs: []});
  812. }
  813. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  814. songData.duration = getSongDuration(songData.title, songData.artist) || 0;
  815. songData.img = getSongAlbumArt(songData.title, songData.artist) || "";
  816. songData.skipDuration = 0;
  817. songData.likes = 0;
  818. songData.dislikes = 0;
  819. var mid = createUniqueSongId();
  820. if (mid !== undefined) {
  821. songData.mid = mid;
  822. Queues.update({type: type}, {
  823. $push: {
  824. songs: {
  825. id: songData.id,
  826. mid: songData.mid,
  827. title: songData.title,
  828. artist: songData.artist,
  829. duration: songData.duration,
  830. skipDuration: songData.skipDuration,
  831. likes: songData.likes,
  832. dislikes: songData.dislikes,
  833. img: songData.img,
  834. type: songData.type,
  835. requestedBy: userId
  836. }
  837. }
  838. });
  839. var songsRequested = (Meteor.user().profile !== undefined && Meteor.user().profile.statistics !== undefined && Meteor.user().profile.statistics.songsRequested !== undefined) ? Meteor.user().profile.statistics.songsRequested : 0;
  840. songsRequested++;
  841. Meteor.users.update(Meteor.userId(), {$set: {"profile.statistics.songsRequested": songsRequested}}); // TODO Make mongo query use $inc correctly.
  842. return true;
  843. } else {
  844. throw new Meteor.Error(500, "Am error occured.");
  845. }
  846. } else {
  847. throw new Meteor.Error(403, "Invalid data.");
  848. }
  849. } else {
  850. throw new Meteor.Error(403, "Invalid genre.");
  851. }
  852. } else {
  853. throw new Meteor.Error(403, "Invalid permissions.");
  854. }
  855. },
  856. updateQueueSong: function(genre, oldSong, newSong) {
  857. if (isModerator() && !isBanned()) {
  858. newSong.mid = oldSong.mid;
  859. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  860. return true;
  861. } else {
  862. throw new Meteor.Error(403, "Invalid permissions.");
  863. }
  864. },
  865. updatePlaylistSong: function(genre, oldSong, newSong) {
  866. if (isModerator() && !isBanned()) {
  867. newSong.mid = oldSong.mid;
  868. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  869. return true;
  870. } else {
  871. throw new Meteor.Error(403, "Invalid permissions.");
  872. }
  873. },
  874. removeSongFromQueue: function(type, mid) {
  875. if (isModerator() && !isBanned()) {
  876. type = type.toLowerCase();
  877. Queues.update({type: type}, {$pull: {songs: {mid: mid}}});
  878. } else {
  879. throw new Meteor.Error(403, "Invalid permissions.");
  880. }
  881. },
  882. removeSongFromPlaylist: function(type, mid) {
  883. if (isModerator() && !isBanned()) {
  884. type = type.toLowerCase();
  885. var songs = Playlists.findOne({type: type}).songs;
  886. var song = undefined;
  887. songs.forEach(function(curr_song) {
  888. if (mid === curr_song.mid) {
  889. song = curr_song;
  890. return;
  891. }
  892. });
  893. Playlists.update({type: type}, {$pull: {songs: {mid: mid}}});
  894. if (song !== undefined) {
  895. song.deletedBy = Meteor.userId();
  896. song.deletedAt = new Date(Date.now());
  897. if (Deleted.find({type: type}).count() === 0) {
  898. Deleted.insert({type: type, songs: [song]});
  899. } else {
  900. Deleted.update({type: type}, {$push: {songs: song}});
  901. }
  902. }
  903. } else {
  904. throw new Meteor.Error(403, "Invalid permissions.");
  905. }
  906. },
  907. addSongToPlaylist: function(type, songData) {
  908. if (isModerator() && !isBanned()) {
  909. type = type.toLowerCase();
  910. if (Rooms.find({type: type}).count() === 1) {
  911. if (Playlists.find({type: type}).count() === 0) {
  912. Playlists.insert({type: type, songs: []});
  913. }
  914. var requiredProperties = ["type", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy"];
  915. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  916. for (var property in requiredProperties) {
  917. if (songData[requiredProperties[property]] === undefined) {
  918. throw new Meteor.Error(403, "Invalid data.");
  919. }
  920. }
  921. Playlists.update({type: type}, {
  922. $push: {
  923. songs: {
  924. id: songData.id,
  925. mid: songData.mid,
  926. title: songData.title,
  927. artist: songData.artist,
  928. duration: songData.duration,
  929. skipDuration: Number(songData.skipDuration),
  930. img: songData.img,
  931. type: songData.type,
  932. likes: Number(songData.likes),
  933. dislikes: Number(songData.dislikes),
  934. requesedBy: songData.requestedBy,
  935. approvedBy: Meteor.userId()
  936. }
  937. }
  938. });
  939. Queues.update({type: type}, {$pull: {songs: {mid: songData.mid}}});
  940. return true;
  941. } else {
  942. throw new Meteor.Error(403, "Invalid data.");
  943. }
  944. } else {
  945. throw new Meteor.Error(403, "Invalid genre.");
  946. }
  947. } else {
  948. throw new Meteor.Error(403, "Invalid permissions.");
  949. }
  950. },
  951. createRoom: function(display, tag, private) {
  952. if (isAdmin() && !isBanned()) {
  953. createRoom(display, tag, private);
  954. } else {
  955. throw new Meteor.Error(403, "Invalid permissions.");
  956. }
  957. },
  958. deleteRoom: function(type){
  959. if (isAdmin() && !isBanned()) {
  960. Rooms.remove({type: type});
  961. Playlists.remove({type: type});
  962. Queues.remove({type: type});
  963. return true;
  964. } else {
  965. throw new Meteor.Error(403, "Invalid permissions.");
  966. }
  967. },
  968. getUserNum: function(){
  969. if (!isBanned()) {
  970. return Object.keys(Meteor.default_server.sessions).length;
  971. }
  972. },
  973. getTotalUsers: function(){
  974. return Meteor.users.find().count();
  975. },
  976. updateRealName: function(realname){
  977. if (Meteor.userId()) {
  978. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  979. Meteor.users.update(Meteor.userId(), {$set: {"profile.realname": realname}, $push: {"profile.realnames": oldName}});
  980. } else {
  981. throw new Meteor.Error(403, "Invalid permissions.");
  982. }
  983. },
  984. updateUserName: function(newUserName){
  985. if (Meteor.userId()) {
  986. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  987. Meteor.users.update(Meteor.userId(), {$set: {"username": newUserName, "profile.username": newUserName, "profile.usernameL": newUserName.toLowerCase()}, $push: {"profile.usernames": oldUsername}});
  988. } else {
  989. throw new Meteor.Error(403, "Invalid permissions.");
  990. }
  991. },
  992. /*updateUserRank: function(newRank){
  993. if (Meteor.userId()) {
  994. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  995. } else {
  996. throw new Meteor.Error(403, "Invalid permissions.");
  997. }
  998. },*/
  999. deleteAccount: function() {
  1000. if (Meteor.userId()) {
  1001. var user = Meteor.users.findOne(Meteor.userId());
  1002. Deleted.insert({type: "account", user: user, deletedAt: Date.now()});
  1003. Meteor.users.remove({_id: Meteor.userId()});
  1004. } else {
  1005. throw new Meteor.Error(403, "Invalid permissions.");
  1006. }
  1007. }
  1008. });
  1009. Meteor.setInterval(function() {
  1010. checkUsersPR();
  1011. }, 10000);