2
0

server.js 39 KB

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