2
0

server.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  1. Meteor.startup(function () {
  2. reCAPTCHA.config({
  3. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  4. });
  5. Avatar.setOptions({
  6. fallbackType: "initials",
  7. defaultImageUrl: "/notes.png",
  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, "Room description goes here.");
  17. }
  18. }
  19. emojione.ascii = true;
  20. Accounts.config({
  21. sendVerificationEmail: true
  22. });
  23. if (Songs.find().count() === 0 || Songs.find({mid: default_song.mid}).count() === 0) {
  24. Songs.insert(default_song);
  25. }
  26. });
  27. var default_song = {
  28. id: "xKVcVSYmesU",
  29. mid: "ABCDEF",
  30. likes: 0,
  31. dislikes: 0,
  32. title: "Immortals",
  33. artist: "Fall Out Boy",
  34. img: "http://c.directlyrics.com/img/upload/fall-out-boy-sixth-album-cover.jpg",
  35. type: "YouTube",
  36. duration: 181,
  37. skipDuration: 0,
  38. requestedBy: "NONE",
  39. approvedBy: "GOD",
  40. genres: ["edm", "pop"]
  41. };
  42. var default_private_playlist = {
  43. name: "default",
  44. displayName: "Default Playlist",
  45. songs: [{id: "60ItHLz5WEA", duration: 213, title: "Alan Walker - Faded"}],
  46. owner: "NONE"
  47. };
  48. Alerts.update({active: true}, {$set: {active: false}}, {multi: true});
  49. var stations = [];
  50. var privateStations = [];
  51. var voteNum = 0;
  52. var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
  53. function createUniqueSongId() {
  54. var code = "";
  55. for (var i = 0; i < 6; i++) {
  56. code += chars[Math.floor(Math.random() * chars.length)];
  57. }
  58. if (Playlists.find({"songs.mid": code}).count() > 0) {
  59. return createUniqueSongId();
  60. } else {
  61. return code;
  62. }
  63. }
  64. function checkUsersPR() {
  65. var output = {};
  66. var connections = Meteor.server.stream_server.open_sockets;
  67. _.each(connections, function (connection) {
  68. // named subscriptions
  69. if (connection._meteorSession !== undefined && connection._meteorSession !== null) {
  70. var subs = connection._meteorSession._namedSubs;
  71. //var ip = connection.remoteAddress;
  72. var used_subs = [];
  73. for (var sub in subs) {
  74. var mySubName = subs[sub]._name;
  75. if (subs[sub]._params.length > 0) {
  76. mySubName += subs[sub]._params[0]; // assume one id parameter for now
  77. }
  78. if (used_subs.indexOf(mySubName) === -1) {
  79. used_subs.push(mySubName);
  80. if (!output[mySubName]) {
  81. output[mySubName] = 1;
  82. } else {
  83. output[mySubName] += 1;
  84. }
  85. }
  86. }
  87. }
  88. // there are also these 'universal subscriptions'
  89. //not sure what these are, i count none in my tests
  90. //var usubs = connection._meteorSession._universalSubs;
  91. });
  92. var emptyStations = [];
  93. stations.forEach(function (station) {
  94. emptyStations.push(station);
  95. });
  96. for (var key in output) {
  97. getStation(key, function (station) {
  98. emptyStations.splice(emptyStations.indexOf(station), 1);
  99. Rooms.update({type: key}, {$set: {users: output[key]}});
  100. });
  101. }
  102. emptyStations.forEach(function (emptyStation) {
  103. Rooms.update({type: emptyStation.type}, {$set: {users: 0}});
  104. });
  105. return output;
  106. }
  107. function getStation(type, cb) {
  108. stations.forEach(function (station) {
  109. if (station.type === type) {
  110. cb(station);
  111. return;
  112. }
  113. });
  114. }
  115. function getPrivateStation(name, cb) {
  116. privateStations.forEach(function (station) {
  117. if (station.name === name) {
  118. cb(station);
  119. return;
  120. }
  121. });
  122. }
  123. function createRoom(display, tag, private, desc) {
  124. var type = tag;
  125. if (Rooms.find({type: type}).count() === 0) {
  126. Rooms.insert({
  127. display: display,
  128. type: type,
  129. users: 0,
  130. private: private,
  131. currentSong: {song: default_song, started: 0},
  132. roomDesc: desc
  133. }, function (err) {
  134. if (err) {
  135. throw err;
  136. } else {
  137. stations.push(new Station(type));
  138. }
  139. });
  140. } else {
  141. return "Room already exists";
  142. }
  143. }
  144. function createPrivateRoom(name, display, private, desc, owner) {
  145. if (PrivateRooms.find({name: name}).count() === 0) {
  146. PrivateRooms.insert({
  147. name: name,
  148. displayName: display,
  149. private: private,
  150. roomDesc: desc,
  151. owner: owner,
  152. }, function (err) {
  153. if (err) {
  154. throw err;
  155. } else {
  156. privateStations.push(new PrivateStation(name));
  157. }
  158. });
  159. } else {
  160. return "Private room with that name already exists";
  161. }
  162. }
  163. function Station(type) {
  164. if (Playlists.find({type: type}).count() === 0) {
  165. Playlists.insert({type: type, songs: [default_song.mid], lastSong: 0});
  166. }
  167. if (Songs.find({genres: type}).count() > 0) {
  168. var list = Songs.find({genres: type}).fetch();
  169. list.forEach(function(song){
  170. if (Playlists.findOne({type: type, songs: song.mid}) === undefined) {
  171. Playlists.update({type: type}, {$push: {songs: song.mid}});
  172. }
  173. });
  174. }
  175. if (Playlists.findOne({type: type}).songs.length === 0) {
  176. Playlists.update({type: type}, {$push: {songs: default_song.mid}});
  177. }
  178. var usersObj = {};
  179. Rooms.update({type: type}, {$set: {userList: []}});
  180. Meteor.publish(type, function () {
  181. var user = Meteor.users.findOne(this.userId);
  182. if (this.userId !== undefined && user !== undefined && user.profile !== undefined && user.profile.username !== undefined) {
  183. var username = user.profile.username;
  184. if (usersObj[username] === undefined) {
  185. usersObj[username] = 1;
  186. } else {
  187. usersObj[username]++;
  188. }
  189. Rooms.update({type: type}, {$push: {userList: username}});
  190. this.onStop(function() {
  191. usersObj[username]--;
  192. var list = Rooms.findOne({type: type}).userList;
  193. var index = list.indexOf(username);
  194. if (index >= 0) {
  195. list.splice(index, 1);
  196. Rooms.update({type: type}, {$set: {userList: list}});
  197. }
  198. });
  199. }
  200. return undefined;
  201. });
  202. var self = this;
  203. var startedAt = Date.now();
  204. var playlist = Playlists.findOne({type: type});
  205. var songs = playlist.songs;
  206. var currentSong = playlist.lastSong;
  207. if (currentSong < (songs.length - 1)) {
  208. currentSong++;
  209. } else currentSong = 0;
  210. var currentMid = songs[currentSong];
  211. var song = Songs.findOne({mid: currentMid});
  212. if (song === undefined) {
  213. Playlists.remove({}, {$pull: {songs: currentMid}});
  214. song = default_song;
  215. }
  216. var res = Rooms.update({type: type}, {
  217. $set: {
  218. currentSong: {song: song, started: startedAt},
  219. users: 0
  220. }
  221. });
  222. this.skipSong = function () {
  223. self.voted = [];
  224. voteNum = 0;
  225. Rooms.update({type: type}, {$set: {votes: 0}});
  226. songs = Playlists.findOne({type: type}).songs;
  227. songs.forEach(function (mid, index) {
  228. if (mid === currentMid) {
  229. currentSong = index;
  230. }
  231. });
  232. if (currentSong < (songs.length - 1)) {
  233. currentSong++;
  234. } else currentSong = 0;
  235. if (songs);
  236. if (currentSong === 0) {
  237. this.shufflePlaylist();
  238. } else {
  239. currentMid = songs[currentSong];
  240. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  241. Rooms.update({type: type}, {$set: {timePaused: 0}});
  242. this.songTimer();
  243. Rooms.update({type: type}, {$set: {currentSong: {song: Songs.findOne({mid: songs[currentSong]}), started: startedAt}}});
  244. }
  245. };
  246. this.shufflePlaylist = function () {
  247. voteNum = 0;
  248. Rooms.update({type: type}, {$set: {votes: 0}});
  249. self.voted = [];
  250. songs = Playlists.findOne({type: type}).songs;
  251. currentSong = 0;
  252. Playlists.update({type: type}, {$set: {"songs": []}});
  253. songs = shuffle(songs);
  254. songs.forEach(function (song) {
  255. Playlists.update({type: type}, {$push: {"songs": song}});
  256. });
  257. currentMid = songs[currentSong];
  258. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  259. Rooms.update({type: type}, {$set: {timePaused: 0}});
  260. this.songTimer();
  261. Rooms.update({type: type}, {$set: {currentSong: {song: Songs.findOne({mid: songs[currentSong]}), started: startedAt}}});
  262. };
  263. Rooms.update({type: type}, {$set: {timePaused: 0}});
  264. var timer;
  265. var timerInitialised = false;
  266. this.songTimer = function () {
  267. if (state !== "paused") {
  268. startedAt = Date.now();
  269. if (timer !== undefined) {
  270. timer.pause();
  271. }
  272. timerInitialised = true;
  273. timer = new Timer(function () {
  274. self.skipSong();
  275. }, Songs.findOne({mid: songs[currentSong]}).duration * 1000);
  276. }
  277. };
  278. var state = Rooms.findOne({type: type}).state;
  279. this.pauseRoom = function () {
  280. if (state !== "paused") {
  281. timer.pause();
  282. Rooms.update({type: type}, {$set: {state: "paused"}});
  283. state = "paused";
  284. }
  285. };
  286. this.resumeRoom = function () {
  287. if (state !== "playing") {
  288. if (!timerInitialised) {
  289. timer = new Timer(function () {
  290. self.skipSong();
  291. }, Songs.findOne({mid: songs[currentSong]}).duration * 1000);
  292. }
  293. timer.resume();
  294. Rooms.update({type: type}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  295. state = "playing";
  296. }
  297. };
  298. this.cancelTimer = function () {
  299. timer.pause();
  300. };
  301. this.getState = function () {
  302. return state;
  303. };
  304. this.type = type;
  305. var private = Rooms.findOne({type: type}).private;
  306. if (typeof private !== "boolean") {
  307. Rooms.update({type: type}, {$set: {"private": false}});
  308. private = false;
  309. }
  310. this.private = private;
  311. this.unlock = function () {
  312. if (self.private) {
  313. self.private = false;
  314. Rooms.update({type: type}, {$set: {"private": false}});
  315. }
  316. };
  317. this.lock = function () {
  318. if (!self.private) {
  319. self.private = true;
  320. Rooms.update({type: type}, {$set: {"private": true}});
  321. }
  322. };
  323. /* This function fetches all songs with the genre of this room that isn't in the playlist yet, and then puts it in the playlist */
  324. this.fetchSongs = function() {
  325. var genreSongs = Songs.find({genres: type}).fetch();
  326. genreSongs.forEach(function(song) {
  327. if (songs.indexOf(song.mid) === -1) {
  328. Playlists.update({type: type}, {$push: {songs: song.mid}});
  329. }
  330. });
  331. };
  332. /* This function removes all songs that are in the playlist but do not have the type of the playlist in their genre */
  333. this.removeSongs = function() {
  334. songs.forEach(function(mid) {
  335. var song = Songs.findOne({mid: mid});
  336. if (song === undefined || song.genres.indexOf(type) === -1) {
  337. Playlists.update({type: type}, {$pull: {songs: mid}});
  338. }
  339. });
  340. };
  341. this.removeSongs();
  342. this.fetchSongs();
  343. this.skipSong();
  344. this.voted = [];
  345. }
  346. function PrivateStation(name) {
  347. var usersObj = {};
  348. PrivateRooms.update({name: name}, {$set: {userList: []}});
  349. Meteor.publish("pr_" + name, function () {
  350. var user = Meteor.users.findOne(this.userId);
  351. if (this.userId !== undefined && user !== undefined && user.profile !== undefined && user.profile.username !== undefined) {
  352. var username = user.profile.username;
  353. if (usersObj[username] === undefined) {
  354. usersObj[username] = 1;
  355. } else {
  356. usersObj[username]++;
  357. }
  358. PrivateRooms.update({name: name}, {$push: {userList: username}});
  359. this.onStop(function() {
  360. usersObj[username]--;
  361. var list = PrivateRooms.findOne({name: name}).userList;
  362. var index = list.indexOf(username);
  363. if (index >= 0) {
  364. list.splice(index, 1);
  365. PrivateRooms.update({name: name}, {$set: {userList: list}});
  366. }
  367. });
  368. }
  369. return undefined;
  370. });
  371. var self = this;
  372. var startedAt = Date.now();
  373. var _room = PrivateRooms.findOne({name: name});
  374. var playlist = PrivatePlaylists.findOne({name: _room.playlist, owner: _room.owner});
  375. if (playlist === undefined) {
  376. playlist = default_private_playlist;
  377. }
  378. var songs = playlist.songs;
  379. var currentSong = 0;
  380. if (currentSong < (songs.length - 1)) {
  381. currentSong++;
  382. } else currentSong = 0;
  383. var currentId = songs[currentSong];
  384. var song = songs[songs.indexOf(currentId)];
  385. if (song === undefined) {
  386. song = {song: {id: "60ItHLz5WEA", duration: 213, title: "Alan Walker - Faded"}, started: 0};
  387. }
  388. var res = PrivateRooms.update({name: name}, {
  389. $set: {
  390. currentSong: {song: song, started: startedAt},
  391. users: 0
  392. }
  393. });
  394. this.skipSong = function () {
  395. self.voted = [];
  396. voteNum = 0;
  397. PrivateRooms.update({name: name}, {$set: {votes: 0}});
  398. playlist = PrivatePlaylists.findOne({name: _room.playlist, owner: _room.owner});
  399. if (playlist === undefined) {
  400. playlist = default_private_playlist;
  401. }
  402. songs = playlist.songs;
  403. songs.forEach(function (id, index) {
  404. if (id === currentId) {
  405. currentSong = index;
  406. }
  407. });
  408. if (currentSong < (songs.length - 1)) {
  409. currentSong++;
  410. } else currentSong = 0;
  411. currentId = songs[currentSong];
  412. PrivateRooms.update({name: name}, {$set: {timePaused: 0}});
  413. this.songTimer();
  414. PrivateRooms.update({name: name}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  415. };
  416. PrivateRooms.update({name: name}, {$set: {timePaused: 0}});
  417. var timer;
  418. var timerInitialised = false;
  419. this.songTimer = function () {
  420. if (state !== "paused") {
  421. startedAt = Date.now();
  422. if (timer !== undefined) {
  423. timer.pause();
  424. }
  425. timerInitialised = true;
  426. timer = new Timer(function () {
  427. self.skipSong();
  428. }, songs[currentSong].duration * 1000);
  429. }
  430. };
  431. var state = PrivateRooms.findOne({name: name}).state;
  432. this.pauseRoom = function () {
  433. if (state !== "paused") {
  434. timer.pause();
  435. PrivateRooms.update({name: name}, {$set: {state: "paused"}});
  436. state = "paused";
  437. }
  438. };
  439. this.resumeRoom = function () {
  440. if (state !== "playing") {
  441. if (!timerInitialised) {
  442. timer = new Timer(function () {
  443. self.skipSong();
  444. }, songs[currentSong] * 1000);
  445. }
  446. timer.resume();
  447. PrivateRooms.update({name: name}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  448. state = "playing";
  449. }
  450. };
  451. this.cancelTimer = function () {
  452. timer.pause();
  453. };
  454. this.getState = function () {
  455. return state;
  456. };
  457. this.name = name;
  458. var private = PrivateRooms.findOne({name: name}).private;
  459. if (typeof private !== "boolean") {
  460. PrivateRooms.update({name: name}, {$set: {"private": false}});
  461. private = false;
  462. }
  463. this.private = private;
  464. this.unlock = function () {
  465. if (self.private) {
  466. self.private = false;
  467. PrivateRooms.update({name: name}, {$set: {"private": false}});
  468. }
  469. };
  470. this.lock = function () {
  471. if (!self.private) {
  472. self.private = true;
  473. PrivateRooms.update({name: name}, {$set: {"private": true}});
  474. }
  475. };
  476. this.setPlaylist = function (plName) {
  477. if (PrivatePlaylists.findOne({name: plName, owner: _room.owner}) !== undefined) {
  478. PrivateRooms.update({name: name}, {$set: {"playlist": plName}});
  479. _room.playlist = plName;
  480. playlist = PrivatePlaylists.findOne({name: plName, owner: _room.owner});
  481. songs = playlist.songs;
  482. currentSong = 0;
  483. }
  484. };
  485. this.addAllowed = function (allowed) {
  486. if (_room.allowed.indexOf(allowed) === -1 && _room.owner !== allowed) {
  487. PrivateRooms.update({name: name}, {$push: {allowed: allowed}});
  488. _room = PrivateRooms.findOne({name: name});
  489. }
  490. };
  491. this.removeAllowed = function (allowed) {
  492. if (_room.allowed.indexOf(allowed) !== -1) {
  493. PrivateRooms.update({name: name}, {$pull: {allowed: allowed}});
  494. _room = PrivateRooms.findOne({name: name});
  495. }
  496. };
  497. this.skipSong();
  498. this.voted = [];
  499. }
  500. function shuffle(array) {
  501. var currentIndex = array.length, temporaryValue, randomIndex;
  502. // While there remain elements to shuffle...
  503. while (0 !== currentIndex) {
  504. // Pick a remaining element...
  505. randomIndex = Math.floor(Math.random() * currentIndex);
  506. currentIndex -= 1;
  507. // And swap it with the current element.
  508. temporaryValue = array[currentIndex];
  509. array[currentIndex] = array[randomIndex];
  510. array[randomIndex] = temporaryValue;
  511. }
  512. return array;
  513. }
  514. function Timer(callback, delay) {
  515. var timerId, start, remaining = delay;
  516. var timeWhenPaused = 0;
  517. var timePaused = new Date();
  518. this.pause = function () {
  519. Meteor.clearTimeout(timerId);
  520. remaining -= new Date() - start;
  521. timePaused = new Date();
  522. };
  523. this.resume = function () {
  524. start = new Date();
  525. Meteor.clearTimeout(timerId);
  526. timerId = Meteor.setTimeout(callback, remaining);
  527. timeWhenPaused += new Date() - timePaused;
  528. };
  529. this.timeWhenPaused = function () {
  530. return timeWhenPaused;
  531. };
  532. this.resume();
  533. }
  534. Meteor.users.deny({
  535. update: function () {
  536. return true;
  537. }
  538. });
  539. Meteor.users.deny({
  540. insert: function () {
  541. return true;
  542. }
  543. });
  544. Meteor.users.deny({
  545. remove: function () {
  546. return true;
  547. }
  548. });
  549. function getSongDuration(query, artistName) {
  550. var duration;
  551. var search = query;
  552. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  553. for (var i in res.data) {
  554. for (var j in res.data[i].items) {
  555. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  556. duration = res.data[i].items[j].duration_ms / 1000;
  557. return duration;
  558. }
  559. }
  560. }
  561. return 0;
  562. }
  563. function getSongDataYT(id) {
  564. var res = Meteor.http.get('https://www.googleapis.com/youtube/v3/videos?id=' + encodeURIComponent(id) + '&part=snippet,contentDetails&key=AIzaSyAgBdacEWrHCHVPPM4k-AFM7uXg-Q__YXY');
  565. if (res.data !== undefined && res.data.items.length !== 0) {
  566. var dur = res.data.items[0].contentDetails.duration;
  567. dur = dur.replace("PT", "");
  568. var durInSec = 0;
  569. dur = dur.replace(/([\d]*)M/, function(v, v2) {
  570. v2 = Number(v2);
  571. durInSec = (v2 * 60)
  572. return "";
  573. });
  574. dur = dur.replace(/([\d]*)S/, function(v, v2) {
  575. v2 = Number(v2);
  576. durInSec += v2;
  577. return "";
  578. });
  579. return {duration: durInSec, title: res.data.items[0].snippet.title};
  580. } else {
  581. return 0;
  582. }
  583. }
  584. function getSongAlbumArt(query, artistName) {
  585. var albumart;
  586. var search = query;
  587. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + encodeURIComponent(query) + '&type=track');
  588. for (var i in res.data) {
  589. for (var j in res.data[i].items) {
  590. if (search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1) {
  591. albumart = res.data[i].items[j].album.images[1].url
  592. return albumart;
  593. }
  594. }
  595. }
  596. }
  597. //var room_types = ["edm", "nightcore"];
  598. var songsArr = [];
  599. Rooms.find({}).fetch().forEach(function (room) {
  600. var type = room.type;
  601. if (Playlists.find({type: type}).count() === 0) {
  602. Playlists.insert({type: type, songs: []});
  603. }
  604. if (Playlists.findOne({type: type}).songs.length === 0) {
  605. Playlists.update({type: type}, {$push: {songs: default_song.mid}}, function() {
  606. stations.push(new Station(type));
  607. });
  608. } else {
  609. stations.push(new Station(type));
  610. }
  611. });
  612. PrivateRooms.find({}).fetch().forEach(function (room) {
  613. var name = room.name;
  614. privateStations.push(new PrivateStation(name));
  615. });
  616. Accounts.validateNewUser(function (user) {
  617. var username;
  618. if (user.services) {
  619. if (user.services.github) {
  620. username = user.services.github.username;
  621. } else if (user.services.facebook) {
  622. username = user.services.facebook.first_name;
  623. } else if (user.services.password) {
  624. username = user.username;
  625. }
  626. }
  627. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() !== 0) {
  628. throw new Meteor.Error(403, "An account with that username already exists.");
  629. } else {
  630. return true;
  631. }
  632. });
  633. Accounts.onCreateUser(function (options, user) {
  634. var username;
  635. if (user.services) {
  636. if (user.services.github) {
  637. username = user.services.github.username;
  638. } else if (user.services.facebook) {
  639. username = user.services.facebook.first_name;
  640. } else if (user.services.password) {
  641. username = user.username;
  642. }
  643. }
  644. user.profile = {
  645. username: username,
  646. usernameL: username.toLowerCase(),
  647. rank: "default",
  648. liked: [],
  649. disliked: [],
  650. settings: {showRating: true},
  651. realname: ""
  652. };
  653. return user;
  654. });
  655. Meteor.publish("alerts", function () {
  656. return Alerts.find({active: true})
  657. });
  658. Meteor.publish("allAlerts", function () {
  659. return Alerts.find({})
  660. });
  661. Meteor.publish("news", function () {
  662. return News.find({})
  663. });
  664. Meteor.publish("userData", function (userId) {
  665. if (userId !== undefined) {
  666. return Meteor.users.find(userId, {fields: {"services.github.username": 1, "punishments": 1}});
  667. } else {
  668. return undefined;
  669. }
  670. });
  671. Meteor.publish("usernames", function () {
  672. return Meteor.users.find({}, {fields: {"profile.username": 1}})
  673. });
  674. Meteor.publish("playlists", function () {
  675. return Playlists.find({})
  676. });
  677. Meteor.publish("rooms", function () {
  678. return Rooms.find({});
  679. });
  680. Meteor.publish("private_rooms", function () {
  681. return PrivateRooms.find({});
  682. });
  683. Meteor.publish("private_playlists", function () {
  684. if (this.userId !== undefined) {
  685. return PrivatePlaylists.find({owner: this.userId});
  686. } else {
  687. return null;
  688. }
  689. });
  690. Meteor.publish("songs", function () {
  691. return Songs.find({});
  692. });
  693. Meteor.publish("queues", function () {
  694. return Queues.find({});
  695. });
  696. Meteor.publish("reports", function () {
  697. return Reports.find({});
  698. });
  699. Meteor.publish("chat", function () {
  700. return Chat.find({});
  701. });
  702. Meteor.publish("userProfiles", function (username) {
  703. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  704. if (settings !== undefined && settings.profile.settings) {
  705. settings = settings.profile.settings;
  706. if (settings.showRating === true) {
  707. return Meteor.users.find({"profile.usernameL": username}, {
  708. fields: {
  709. "profile.username": 1,
  710. "profile.usernameL": 1,
  711. "profile.rank": 1,
  712. createdAt: 1,
  713. "profile.liked": 1,
  714. "profile.disliked": 1,
  715. "profile.settings": 1,
  716. "profile.realname": 1
  717. }
  718. });
  719. }
  720. }
  721. return Meteor.users.find({"profile.usernameL": username}, {
  722. fields: {
  723. "profile.username": 1,
  724. "profile.usernameL": 1,
  725. "profile.rank": 1,
  726. createdAt: 1,
  727. "profile.settings": 1,
  728. "profile.realname": 1
  729. }
  730. });
  731. });
  732. Meteor.publish("isAdmin", function () {
  733. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  734. });
  735. Meteor.publish("isModerator", function () {
  736. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  737. });
  738. Meteor.publish("feedback", function(){
  739. return Feedback.find();
  740. })
  741. function isPrivateRoomOwner(name) {
  742. var room = PrivateRooms.findOne({name: name});
  743. if (Meteor.userId() && room !== undefined && Meteor.userId() === room.owner) {
  744. return true;
  745. } else {
  746. return false;
  747. }
  748. }
  749. function isAdmin() {
  750. var userData = Meteor.users.find(Meteor.userId());
  751. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  752. return true;
  753. } else {
  754. return false;
  755. }
  756. }
  757. function isModerator() {
  758. var userData = Meteor.users.find(Meteor.userId());
  759. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  760. return true;
  761. } else {
  762. return isAdmin();
  763. }
  764. }
  765. function isBanned() {
  766. var userData = Meteor.users.findOne(Meteor.userId());
  767. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  768. var ban = userData.punishments.ban;
  769. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  770. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  771. return false;
  772. } else {
  773. return true;
  774. }
  775. } else {
  776. return false;
  777. }
  778. }
  779. function isMuted() {
  780. var userData = Meteor.users.findOne(Meteor.userId());
  781. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.mute !== undefined) {
  782. var mute = userData.punishments.mute;
  783. if (new Date(mute.bannedUntil).getTime() <= new Date().getTime()) {
  784. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.mute": ""}});
  785. return false;
  786. } else {
  787. return true;
  788. }
  789. } else {
  790. return false;
  791. }
  792. }
  793. Meteor.methods({
  794. addVideoToPrivatePlaylist: function(name, id) {
  795. if (Meteor.userId() && !isBanned()) {
  796. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  797. if (pl !== undefined) {
  798. var copy = false;
  799. pl.songs.forEach(function(song) {
  800. if (song.id === id) {
  801. copy = true;
  802. }
  803. });
  804. if (!copy) {
  805. console.log(getSongDataYT(id));
  806. var data = getSongDataYT(id);
  807. data.id = id;
  808. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$push: {songs: data}});
  809. } else {
  810. throw new Meteor.Error(500, "Video is already in playlist.");
  811. }
  812. } else {
  813. throw new Meteor.Error(404, "Playlist not found.");
  814. }
  815. } else {
  816. throw new Meteor.Error(403, "Invalid permissions.");
  817. }
  818. },
  819. removeVideoFromPrivatePlaylist: function(name, id) {
  820. if (Meteor.userId() && !isBanned()) {
  821. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  822. if (pl !== undefined) {
  823. var copy = false;
  824. var data;
  825. pl.songs.forEach(function(song) {
  826. if (song.id === id) {
  827. data = song;
  828. copy = true;
  829. }
  830. });
  831. if (copy) {
  832. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$pull: {songs: data}});
  833. } else {
  834. throw new Meteor.Error(500, "Video is not in playlist.");
  835. }
  836. } else {
  837. throw new Meteor.Error(404, "Playlist not found.");
  838. }
  839. } else {
  840. throw new Meteor.Error(403, "Invalid permissions.");
  841. }
  842. },
  843. deletePrivatePlaylist: function(name) {
  844. if (Meteor.userId() && !isBanned()) {
  845. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  846. if (pl !== undefined) {
  847. PrivatePlaylists.remove({owner: Meteor.userId(), name: name});
  848. Deleted.insert({type: "PrivatePlaylist", data: pl});
  849. } else {
  850. throw new Meteor.Error(404, "Playlist not found.");
  851. }
  852. } else {
  853. throw new Meteor.Error(403, "Invalid permissions.");
  854. }
  855. },
  856. activateAlert: function(id) {
  857. if (isAdmin() && !isBanned()) {
  858. Alerts.update(id, {$set: {active: true}});
  859. } else {
  860. throw new Meteor.Error(403, "Invalid permissions.");
  861. }
  862. },
  863. deactivateAlert: function(id) {
  864. if (isAdmin() && !isBanned()) {
  865. Alerts.update(id, {$set: {active: false}});
  866. } else {
  867. throw new Meteor.Error(403, "Invalid permissions.");
  868. }
  869. },
  870. deleteAlert: function(id) {
  871. if (isAdmin() && !isBanned()) {
  872. Alerts.remove(id);
  873. } else {
  874. throw new Meteor.Error(403, "Invalid permissions.");
  875. }
  876. },
  877. fetchSong: function(type) {
  878. if (isAdmin() && !isBanned()) {
  879. getStation(type, function (station) {
  880. station.fetchSongs();
  881. });
  882. } else {
  883. throw new Meteor.Error(403, "Invalid permissions.");
  884. }
  885. },
  886. removeSongs: function(type) {
  887. if (isAdmin() && !isBanned()) {
  888. getStation(type, function (station) {
  889. station.removeSongs();
  890. });
  891. } else {
  892. throw new Meteor.Error(403, "Invalid permissions.");
  893. }
  894. },
  895. lockRoom: function (type) {
  896. if (isAdmin() && !isBanned()) {
  897. getStation(type, function (station) {
  898. station.lock();
  899. });
  900. } else {
  901. throw new Meteor.Error(403, "Invalid permissions.");
  902. }
  903. },
  904. unlockRoom: function (type) {
  905. if (isAdmin() && !isBanned()) {
  906. getStation(type, function (station) {
  907. station.unlock();
  908. });
  909. } else {
  910. throw new Meteor.Error(403, "Invalid permissions.");
  911. }
  912. },
  913. lockPrivateRoom: function (name) {
  914. if ((isAdmin() || isPrivateRoomOwner(name)) && !isBanned()) {
  915. getPrivateStation(name, function (station) {
  916. station.lock();
  917. });
  918. } else {
  919. throw new Meteor.Error(403, "Invalid permissions.");
  920. }
  921. },
  922. unlockPrivateRoom: function (name) {
  923. if ((isAdmin() || isPrivateRoomOwner(name)) && !isBanned()) {
  924. getPrivateStation(name, function (station) {
  925. station.unlock();
  926. });
  927. } else {
  928. throw new Meteor.Error(403, "Invalid permissions.");
  929. }
  930. },
  931. banUser: function (username, period, reason) {
  932. if (isAdmin() && !isBanned()) {
  933. var user = Meteor.user();
  934. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  935. var bannedUntil = (new Date).getTime() + (period * 1000);
  936. if (bannedUntil > 8640000000000000) {
  937. bannedUntil = 8640000000000000;
  938. }
  939. bannedUntil = new Date(bannedUntil);
  940. var banObject = {
  941. bannedBy: user.profile.usernameL,
  942. bannedAt: new Date(Date.now()),
  943. bannedReason: reason,
  944. bannedUntil: bannedUntil
  945. };
  946. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  947. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  948. } else {
  949. throw new Meteor.Error(403, "Invalid permissions.");
  950. }
  951. },
  952. muteUser: function (username, period) {
  953. if (isAdmin() && !isBanned()) {
  954. var user = Meteor.user();
  955. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  956. if (period === undefined || Number(period) === 0) {
  957. mutedUntil = 8640000000000000;
  958. } else {
  959. var mutedUntil = (new Date).getTime() + (period * 1000);
  960. if (mutedUntil > 8640000000000000) {
  961. mutedUntil = 8640000000000000;
  962. }
  963. }
  964. mutedUntil = new Date(mutedUntil);
  965. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  966. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  967. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  968. } else {
  969. throw new Meteor.Error(403, "Invalid permissions.");
  970. }
  971. },
  972. unbanUser: function (username) {
  973. if (isAdmin() && !isBanned()) {
  974. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  975. } else {
  976. throw new Meteor.Error(403, "Invalid permissions.");
  977. }
  978. },
  979. unsilenceUser: function (username) {
  980. if (isAdmin() && !isBanned()) {
  981. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  982. } else {
  983. throw new Meteor.Error(403, "Invalid permissions.");
  984. }
  985. },
  986. isBanned: function () {
  987. return isBanned();
  988. },
  989. isMuted: function () {
  990. return isMuted();
  991. },
  992. updateSettings: function (showRating) {
  993. if (Meteor.userId() && !isBanned()) {
  994. var user = Meteor.user();
  995. if (showRating !== true && showRating !== false) {
  996. showRating = true;
  997. }
  998. if (user.profile.settings) {
  999. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  1000. } else {
  1001. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  1002. }
  1003. } else {
  1004. throw new Meteor.Error(403, "Invalid permissions.");
  1005. }
  1006. },
  1007. addAlert: function (description) {
  1008. if (isAdmin()) {
  1009. var username = Meteor.user().profile.username;
  1010. Alerts.insert({description: description, active: true, createdBy: username});
  1011. return true;
  1012. } else {
  1013. throw Meteor.Error(403, "Invalid permissions.");
  1014. }
  1015. },
  1016. sendMessage: function (type, message) {
  1017. if (Meteor.userId() && !isBanned() && !isMuted()) {
  1018. var user = Meteor.user();
  1019. var time = new Date();
  1020. var rawrank = user.profile.rank;
  1021. var username = user.profile.username;
  1022. var profanity = false
  1023. if (!message.replace(/\s/g, "").length > 0) {
  1024. throw new Meteor.Error(406, "Message length cannot be 0.");
  1025. }
  1026. if (message.length > 300) {
  1027. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  1028. }
  1029. else if (user.profile.rank === "admin") {
  1030. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1031. if (res.content.indexOf("true") > -1) {
  1032. return true;
  1033. } else {*/
  1034. Chat.insert({
  1035. type: type,
  1036. rawrank: rawrank,
  1037. rank: "[A]",
  1038. message: message,
  1039. time: time,
  1040. username: username
  1041. });
  1042. /*}
  1043. });*/
  1044. return true;
  1045. }
  1046. else if (user.profile.rank === "moderator") {
  1047. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1048. if (res.content.indexOf("true") > -1) {
  1049. return true;
  1050. } else {*/
  1051. Chat.insert({
  1052. type: type,
  1053. rawrank: rawrank,
  1054. rank: "[M]",
  1055. message: message,
  1056. time: time,
  1057. username: username
  1058. });
  1059. /*}
  1060. });*/
  1061. return true;
  1062. }
  1063. else {
  1064. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1065. if (res.content.indexOf("true") > -1) {
  1066. return true;
  1067. } else {*/
  1068. Chat.insert({
  1069. type: type,
  1070. rawrank: rawrank,
  1071. rank: "",
  1072. message: message,
  1073. time: time,
  1074. username: username
  1075. });
  1076. /*}
  1077. });*/
  1078. return true;
  1079. }
  1080. } else {
  1081. throw new Meteor.Error(403, "Invalid permissions.");
  1082. }
  1083. },
  1084. likeSong: function (mid) {
  1085. if (Meteor.userId() && !isBanned()) {
  1086. var user = Meteor.user();
  1087. if (user.profile.liked.indexOf(mid) === -1) {
  1088. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  1089. Songs.update({mid: mid}, {$inc: {"likes": 1}})
  1090. } else {
  1091. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  1092. Songs.update({mid: mid}, {$inc: {likes: -1}})
  1093. }
  1094. if (user.profile.disliked.indexOf(mid) !== -1) {
  1095. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  1096. Songs.update({mid: mid}, {$inc: {dislikes: -1}})
  1097. }
  1098. return true;
  1099. } else {
  1100. throw new Meteor.Error(403, "Invalid permissions.");
  1101. }
  1102. },
  1103. dislikeSong: function (mid) {
  1104. if (Meteor.userId() && !isBanned()) {
  1105. var user = Meteor.user();
  1106. if (user.profile.disliked.indexOf(mid) === -1) {
  1107. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  1108. Songs.update({mid: mid}, {$inc: {dislikes: 1}});
  1109. } else {
  1110. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  1111. Songs.update({mid: mid}, {$inc: {dislikes: -1}});
  1112. }
  1113. if (user.profile.liked.indexOf(mid) !== -1) {
  1114. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  1115. Songs.update({mid: mid}, {$inc: {likes: -1}});
  1116. }
  1117. return true;
  1118. } else {
  1119. throw new Meteor.Error(403, "Invalid permissions.");
  1120. }
  1121. },
  1122. voteSkip: function (type) {
  1123. if (Meteor.userId() && !isBanned()) {
  1124. var user = Meteor.user();
  1125. getStation(type, function (station) {
  1126. if (station.voted.indexOf(user.profile.username) === -1) {
  1127. station.voted.push(user.profile.username);
  1128. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  1129. if (station.voted.length === 3) {
  1130. station.skipSong();
  1131. }
  1132. } else {
  1133. throw new Meteor.Error(401, "Already voted.");
  1134. }
  1135. })
  1136. }
  1137. },
  1138. votePrivateSkip: function (name) {
  1139. if (Meteor.userId() && !isBanned()) {
  1140. var user = Meteor.user();
  1141. getPrivateStation(name, function (station) {
  1142. if (station.voted.indexOf(user.profile.username) === -1) {
  1143. station.voted.push(user.profile.username);
  1144. PrivateRooms.update({name: name}, {$set: {votes: station.voted.length}});
  1145. if (station.voted.length === 3) {
  1146. station.skipSong();
  1147. }
  1148. } else {
  1149. throw new Meteor.Error(401, "Already voted.");
  1150. }
  1151. })
  1152. }
  1153. },
  1154. submitReport: function (room, reportData) {
  1155. if (Meteor.userId() && !isBanned()) {
  1156. room = room.toLowerCase();
  1157. if (Rooms.find({type: room}).count() === 1) {
  1158. if (Reports.find({room: room}).count() === 0) {
  1159. Reports.insert({room: room, report: []});
  1160. }
  1161. if (reportData !== undefined) {
  1162. Reports.update({room: room}, {
  1163. $push: {
  1164. report: {
  1165. song: reportData.song,
  1166. type: reportData.type,
  1167. reason: reportData.reason,
  1168. other: reportData.other
  1169. }
  1170. }
  1171. });
  1172. return true;
  1173. } else {
  1174. throw new Meteor.Error(403, "Invalid data.");
  1175. }
  1176. } else {
  1177. throw new Meteor.Error(403, "Invalid genre.");
  1178. }
  1179. } else {
  1180. throw new Meteor.Error(403, "Invalid permissions.");
  1181. }
  1182. },
  1183. shufflePlaylist: function (type) {
  1184. if (isAdmin() && !isBanned()) {
  1185. getStation(type, function (station) {
  1186. if (station === undefined) {
  1187. throw new Meteor.Error(404, "Station not found.");
  1188. } else {
  1189. station.cancelTimer();
  1190. station.shufflePlaylist();
  1191. }
  1192. });
  1193. }
  1194. },
  1195. skipSong: function (type) {
  1196. if (isAdmin() && !isBanned()) {
  1197. getStation(type, function (station) {
  1198. if (station === undefined) {
  1199. throw new Meteor.Error(404, "Station not found.");
  1200. } else {
  1201. station.skipSong();
  1202. }
  1203. });
  1204. }
  1205. },
  1206. pauseRoom: function (type) {
  1207. if (isAdmin() && !isBanned()) {
  1208. getStation(type, function (station) {
  1209. if (station === undefined) {
  1210. throw new Meteor.Error(403, "Room doesn't exist.");
  1211. } else {
  1212. station.pauseRoom();
  1213. }
  1214. });
  1215. } else {
  1216. throw new Meteor.Error(403, "Invalid permissions.");
  1217. }
  1218. },
  1219. resumeRoom: function (type) {
  1220. if (isAdmin() && !isBanned()) {
  1221. getStation(type, function (station) {
  1222. if (station === undefined) {
  1223. throw new Meteor.Error(403, "Room doesn't exist.");
  1224. } else {
  1225. station.resumeRoom();
  1226. }
  1227. });
  1228. } else {
  1229. throw new Meteor.Error(403, "Invalid permissions.");
  1230. }
  1231. },
  1232. skipPrivateSong: function (name) {
  1233. if ((isAdmin() || isPrivateRoomOwner(name)) && !isBanned()) {
  1234. getPrivateStation(name, function (station) {
  1235. if (station === undefined) {
  1236. throw new Meteor.Error(404, "Station not found.");
  1237. } else {
  1238. station.skipSong();
  1239. }
  1240. });
  1241. }
  1242. },
  1243. pausePrivateRoom: function (name) {
  1244. if ((isAdmin() || isPrivateRoomOwner(name)) && !isBanned()) {
  1245. getPrivateStation(name, function (station) {
  1246. if (station === undefined) {
  1247. throw new Meteor.Error(403, "Room doesn't exist.");
  1248. } else {
  1249. station.pauseRoom();
  1250. }
  1251. });
  1252. } else {
  1253. throw new Meteor.Error(403, "Invalid permissions.");
  1254. }
  1255. },
  1256. resumePrivateRoom: function (name) {
  1257. if ((isAdmin() || isPrivateRoomOwner(name)) && !isBanned()) {
  1258. getPrivateStation(name, function (station) {
  1259. if (station === undefined) {
  1260. throw new Meteor.Error(403, "Room doesn't exist.");
  1261. } else {
  1262. station.resumeRoom();
  1263. }
  1264. });
  1265. } else {
  1266. throw new Meteor.Error(403, "Invalid permissions.");
  1267. }
  1268. },
  1269. addAllowedToPrivateRoom: function (name, allowed) {
  1270. if (isPrivateRoomOwner(name) && !isBanned()) {
  1271. getPrivateStation(name, function (station) {
  1272. if (station === undefined) {
  1273. throw new Meteor.Error(403, "Room doesn't exist.");
  1274. } else {
  1275. allowed = allowed.toLowerCase();
  1276. allowed = Meteor.users.findOne({"profile.usernameL": allowed})._id;
  1277. station.addAllowed(allowed);
  1278. }
  1279. });
  1280. } else {
  1281. throw new Meteor.Error(403, "Invalid permissions.");
  1282. }
  1283. },
  1284. removeAllowedFromPrivateRoom: function (name, allowed) {
  1285. if (isPrivateRoomOwner(name) && !isBanned()) {
  1286. getPrivateStation(name, function (station) {
  1287. if (station === undefined) {
  1288. throw new Meteor.Error(403, "Room doesn't exist.");
  1289. } else {
  1290. station.removeAllowed(allowed);
  1291. }
  1292. });
  1293. } else {
  1294. throw new Meteor.Error(403, "Invalid permissions.");
  1295. }
  1296. },
  1297. setPlaylistForPrivateRoom: function (name, playlist) {
  1298. if ((isPrivateRoomOwner(name)) && !isBanned()) {
  1299. getPrivateStation(name, function (station) {
  1300. if (station === undefined) {
  1301. throw new Meteor.Error(403, "Room doesn't exist.");
  1302. } else {
  1303. station.setPlaylist(playlist);
  1304. }
  1305. });
  1306. } else {
  1307. throw new Meteor.Error(403, "Invalid permissions.");
  1308. }
  1309. },
  1310. createUserMethod: function (formData, captchaData) {
  1311. if (!isBanned()) {
  1312. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  1313. if (!verifyCaptchaResponse.success) {
  1314. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  1315. } else {
  1316. Accounts.createUser({
  1317. username: formData.username,
  1318. email: formData.email,
  1319. password: formData.password
  1320. });
  1321. }
  1322. return true;
  1323. }
  1324. },
  1325. createArticle: function(data) {
  1326. if (!isBanned() && isModerator()) {
  1327. var userId = Meteor.userId();
  1328. var requiredProperties = ["title", "content", "anonymous"];
  1329. if (data !== undefined && Object.keys(data).length === requiredProperties.length) {
  1330. for (var property in requiredProperties) {
  1331. if (data[requiredProperties[property]] === undefined) {
  1332. throw new Meteor.Error(403, "Invalid data.");
  1333. }
  1334. }
  1335. if (data.anonymous === false) {
  1336. data.author = Meteor.user().profile.username
  1337. } else {
  1338. data.author = "A Musare Admin";
  1339. }
  1340. delete data.anonymous;
  1341. data.time = new Date();
  1342. News.insert(data, function(err, res) {
  1343. if (err) {
  1344. console.log(err);
  1345. throw err.sanitizedError;
  1346. } else {
  1347. return true;
  1348. }
  1349. });
  1350. } else {
  1351. throw new Meteor.Error(403, "Invalid data.");
  1352. }
  1353. } else {
  1354. throw new Meteor.Error(403, "Invalid permissions.");
  1355. }
  1356. },
  1357. addSongToQueue: function (songData) {
  1358. if (Meteor.userId() && !isBanned()) {
  1359. var userId = Meteor.userId();
  1360. var requiredProperties = ["title", "artist", "id", "genres"];
  1361. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  1362. for (var property in requiredProperties) {
  1363. if (songData[requiredProperties[property]] === undefined) {
  1364. throw new Meteor.Error(403, "Invalid data.");
  1365. }
  1366. }
  1367. songData.duration = Number(getSongDuration(songData.title, songData.artist));
  1368. songData.img = getSongAlbumArt(songData.title, songData.artist) | "";
  1369. songData.skipDuration = 0;
  1370. songData.likes = 0;
  1371. songData.dislikes = 0;
  1372. songData.requestedBy = userId;
  1373. var mid = createUniqueSongId();
  1374. if (mid !== undefined) {
  1375. songData.mid = mid;
  1376. Queues.insert(songData, function(err, res) {
  1377. if (err) {
  1378. console.log(err);
  1379. throw err.sanitizedError;
  1380. } else {
  1381. var songsRequested = (Meteor.user().profile !== undefined && Meteor.user().profile.statistics !== undefined && Meteor.user().profile.statistics.songsRequested !== undefined) ? Meteor.user().profile.statistics.songsRequested : 0;
  1382. songsRequested++;
  1383. Meteor.users.update(Meteor.userId(), {$set: {"profile.statistics.songsRequested": songsRequested}}); // TODO Make mongo query use $inc correctly.
  1384. return true;
  1385. }
  1386. });
  1387. } else {
  1388. throw new Meteor.Error(500, "Am error occured.");
  1389. }
  1390. } else {
  1391. throw new Meteor.Error(403, "Invalid data.");
  1392. }
  1393. } else {
  1394. throw new Meteor.Error(403, "Invalid permissions.");
  1395. }
  1396. },
  1397. updateQueueSong: function (mid, newSong) {
  1398. if (isModerator() && !isBanned()) {
  1399. Queues.update({mid: mid}, {$set: {
  1400. "title": newSong.title,
  1401. "artist": newSong.artist,
  1402. "id": newSong.id,
  1403. "img": newSong.img,
  1404. "duration" : newSong.duration,
  1405. "skipDuration" : newSong.skipDuration,
  1406. "genres": newSong.genres
  1407. }}, function(err) {
  1408. console.log(err);
  1409. if (err) {
  1410. throw err.sanitizedError;
  1411. } else {
  1412. return true;
  1413. }
  1414. });
  1415. } else {
  1416. throw new Meteor.Error(403, "Invalid permissions.");
  1417. }
  1418. },
  1419. updatePlaylistSong: function (mid, newSong) {
  1420. if (isModerator() && !isBanned()) {
  1421. Songs.update({mid: mid}, {$set: {
  1422. "title": newSong.title,
  1423. "artist": newSong.artist,
  1424. "id": newSong.id,
  1425. "img": newSong.img,
  1426. "duration": newSong.duration,
  1427. "skipDuration": newSong.skipDuration,
  1428. "approvedBy": Meteor.userId(),
  1429. "genres": newSong.genres
  1430. }}, function(err) {
  1431. console.log(err);
  1432. if (err) {
  1433. throw err.sanitizedError;
  1434. } else {
  1435. return true;
  1436. }
  1437. });
  1438. return true;
  1439. } else {
  1440. throw new Meteor.Error(403, "Invalid permissions.");
  1441. }
  1442. },
  1443. removeSongFromQueue: function (mid) {
  1444. if (isModerator() && !isBanned()) {
  1445. Queues.remove({mid: mid});
  1446. } else {
  1447. throw new Meteor.Error(403, "Invalid permissions.");
  1448. }
  1449. },
  1450. removeSongFromPlaylist: function (type, mid) {
  1451. if (isModerator() && !isBanned()) {
  1452. Playlists.update({type: type}, {$pull: {songs: mid}});
  1453. } else {
  1454. throw new Meteor.Error(403, "Invalid permissions.");
  1455. }
  1456. },
  1457. deleteSong: function (mid) {
  1458. if (isModerator() && !isBanned()) {
  1459. Songs.remove({mid: mid})
  1460. } else {
  1461. throw new Meteor.Error(403, "Invalid permissions.");
  1462. }
  1463. },
  1464. deleteSong: function (mid) {
  1465. if (isModerator() && !isBanned()) {
  1466. Songs.remove({mid: mid})
  1467. } else {
  1468. throw new Meteor.Error(403, "Invalid permissions.");
  1469. }
  1470. },
  1471. addSongToPlaylist: function (songData) {
  1472. if (isModerator() && !isBanned()) {
  1473. var requiredProperties = ["_id", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy", "genres"];
  1474. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  1475. for (var property in requiredProperties) {
  1476. if (songData[requiredProperties[property]] === undefined) {
  1477. throw new Meteor.Error(403, "Invalid data.");
  1478. }
  1479. }
  1480. delete songData._id;
  1481. songData.approvedBy = Meteor.userId();
  1482. Songs.insert(songData);
  1483. Queues.remove({mid: songData.mid});
  1484. songData.genres.forEach(function(genre) {
  1485. genre = genre.toLowerCase();
  1486. if (Playlists.findOne({type: genre}) === undefined) {
  1487. Playlists.insert({type: genre, songs: [songData.mid]});
  1488. } else {
  1489. Playlists.update({type: genre}, {$push: {songs: songData.mid}});
  1490. }
  1491. });
  1492. return true;
  1493. } else {
  1494. throw new Meteor.Error(403, "Invalid data.");
  1495. }
  1496. } else {
  1497. throw new Meteor.Error(403, "Invalid permissions.");
  1498. }
  1499. },
  1500. createRoom: function (display, tag, private, desc) {
  1501. if (isAdmin() && !isBanned()) {
  1502. createRoom(display, tag, private, desc);
  1503. } else {
  1504. throw new Meteor.Error(403, "Invalid permissions.");
  1505. }
  1506. },
  1507. createPrivateRoom: function (name, display, private, desc) {
  1508. if (Meteor.userId() && !isBanned()) {
  1509. name = name.toLowerCase();
  1510. createPrivateRoom(name, display, private, desc, Meteor.userId());
  1511. } else {
  1512. throw new Meteor.Error(403, "Invalid permissions.");
  1513. }
  1514. },
  1515. createPrivatePlaylist: function (name, display) {
  1516. if (Meteor.userId() && !isBanned()) {
  1517. name = name.toLowerCase();
  1518. if (PrivatePlaylists.findOne({name: name, owner: Meteor.userId()}) === undefined) {
  1519. PrivatePlaylists.insert({name: name, displayName: display, songs: [{id: "60ItHLz5WEA", duration: 213, title: "Alan Walker - Faded"}], owner: Meteor.userId()});
  1520. }
  1521. } else {
  1522. throw new Meteor.Error(403, "Invalid permissions.");
  1523. }
  1524. },
  1525. deleteRoom: function (type) {
  1526. if (isAdmin() && !isBanned()) {
  1527. Rooms.remove({type: type});
  1528. return true;
  1529. } else {
  1530. throw new Meteor.Error(403, "Invalid permissions.");
  1531. }
  1532. },
  1533. getUserNum: function () {
  1534. if (!isBanned()) {
  1535. return Object.keys(Meteor.default_server.sessions).length;
  1536. }
  1537. },
  1538. getTotalUsers: function () {
  1539. return Meteor.users.find().count();
  1540. },
  1541. updateRealName: function (realname) {
  1542. if (Meteor.userId()) {
  1543. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  1544. Meteor.users.update(Meteor.userId(), {
  1545. $set: {"profile.realname": realname},
  1546. $push: {"profile.realnames": oldName}
  1547. });
  1548. } else {
  1549. throw new Meteor.Error(403, "Invalid permissions.");
  1550. }
  1551. },
  1552. updateUserName: function (newUserName) {
  1553. if (Meteor.userId()) {
  1554. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  1555. Meteor.users.update(Meteor.userId(), {
  1556. $set: {
  1557. "username": newUserName,
  1558. "profile.username": newUserName,
  1559. "profile.usernameL": newUserName.toLowerCase()
  1560. }, $push: {"profile.usernames": oldUsername}
  1561. });
  1562. } else {
  1563. throw new Meteor.Error(403, "Invalid permissions.");
  1564. }
  1565. },
  1566. /*updateUserRank: function(newRank){
  1567. if (Meteor.userId()) {
  1568. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  1569. } else {
  1570. throw new Meteor.Error(403, "Invalid permissions.");
  1571. }
  1572. },*/
  1573. deleteAccount: function () {
  1574. if (Meteor.userId()) {
  1575. var user = Meteor.users.findOne(Meteor.userId());
  1576. Meteor.users.remove({_id: Meteor.userId()});
  1577. } else {
  1578. throw new Meteor.Error(403, "Invalid permissions.");
  1579. }
  1580. },
  1581. sendFeedback: function(message){
  1582. if(Meteor.userId() && !isBanned()) {
  1583. HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1584. if (res.content.indexOf("true") > -1) {
  1585. return true;
  1586. } else {
  1587. Feedback.insert({
  1588. "username": Meteor.user().profile.username,
  1589. "message": message,
  1590. "upvotes": 0,
  1591. "upvotedBy": []
  1592. })
  1593. }
  1594. });
  1595. }
  1596. },
  1597. upvoteFeedback: function(message){
  1598. if(Meteor.userId() && !isBanned()){
  1599. console.log(Feedback.findOne({"message": message}));
  1600. if(Feedback.findOne({"message": message}).upvotedBy.indexOf(Meteor.user().profile.username) === -1){
  1601. Feedback.update({"message": message}, {$inc: {"upvotes": 1}});
  1602. Feedback.update({"message": message}, {$push: {"upvotedBy": Meteor.user().profile.username}});
  1603. } else{
  1604. Feedback.update({"message": message}, {$inc: {"upvotes": -1}});
  1605. Feedback.update({"message": message}, {$pull: {"upvotedBy": Meteor.user().profile.username}});
  1606. }
  1607. }
  1608. },
  1609. deleteFeedback: function(message){
  1610. if(isAdmin() && !isBanned()){
  1611. Feedback.remove({"message": message});
  1612. } else {
  1613. throw new Meteor.Error(403, "Invalid permissions.");
  1614. }
  1615. },
  1616. updateFeedback: function(oldMessage, newMessage){
  1617. if(isAdmin() && !isBanned()){
  1618. Feedback.update({"message": oldMessage}, {$set: {"message": newMessage}});
  1619. } else {
  1620. throw new Meteor.Error(403, "Invalid permissions.");
  1621. }
  1622. },
  1623. editRoomDesc: function(type, description){
  1624. if(isAdmin() && !isBanned()){
  1625. Rooms.update({type: type}, {$set: {"roomDesc": description}});
  1626. } else {
  1627. throw new Meteor.Error(403, "Invalid permissions.");
  1628. }
  1629. },
  1630. removeReport: function(query, obj){
  1631. if(isAdmin() && !isBanned()){
  1632. Reports.update(query, {$pull: {"report": obj}});
  1633. } else {
  1634. throw new Meteor.Error(403, "Invalid permissions.");
  1635. }
  1636. }
  1637. });
  1638. Meteor.setInterval(function () {
  1639. checkUsersPR();
  1640. }, 10000);
  1641. Meteor.users.after.insert(function (err, user) {
  1642. Accounts.sendVerificationEmail(user._id);
  1643. });