server.js 41 KB

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