server.js 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  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 communityStations = [];
  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 getCommunityStation(name, cb) {
  116. communityStations.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 createCommunityStation(name, display, private, desc, owner) {
  145. if (CommunityStations.find({name: name}).count() === 0) {
  146. CommunityStations.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. communityStations.push(new CommunityStation(name));
  157. }
  158. });
  159. } else {
  160. return "Community 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 CommunityStation(name) {
  347. var usersObj = {};
  348. CommunityStations.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. CommunityStations.update({name: name}, {$push: {userList: username}});
  359. this.onStop(function () {
  360. usersObj[username]--;
  361. var room = CommunityStations.findOne({name: name});
  362. if (room !== undefined) {
  363. var list = room.userList;
  364. var index = list.indexOf(username);
  365. if (index >= 0) {
  366. list.splice(index, 1);
  367. CommunityStations.update({name: name}, {$set: {userList: list}});
  368. }
  369. }
  370. });
  371. }
  372. return undefined;
  373. });
  374. var self = this;
  375. var startedAt = Date.now();
  376. var _room = CommunityStations.findOne({name: name});
  377. var playlist;
  378. if (_room !== undefined) {
  379. playlist = PrivatePlaylists.findOne({name: _room.playlist, owner: _room.owner});
  380. }
  381. if (playlist === undefined) {
  382. playlist = default_private_playlist;
  383. }
  384. var songs = playlist.songs;
  385. var currentSong = 0;
  386. if (currentSong < (songs.length - 1)) {
  387. currentSong++;
  388. } else currentSong = 0;
  389. var currentId = songs[currentSong];
  390. var song = songs[songs.indexOf(currentId)];
  391. if (song === undefined) {
  392. song = {id: "60ItHLz5WEA", duration: 213, title: "Alan Walker - Faded"};
  393. }
  394. var res = CommunityStations.update({name: name}, {
  395. $set: {
  396. currentSong: {song: song, started: startedAt},
  397. users: 0
  398. }
  399. });
  400. this.skipSong = function () {
  401. self.voted = [];
  402. voteNum = 0;
  403. CommunityStations.update({name: name}, {$set: {votes: 0}});
  404. playlist = PrivatePlaylists.findOne({name: _room.playlist, owner: _room.owner});
  405. if (playlist === undefined) {
  406. playlist = default_private_playlist;
  407. }
  408. if (playlist !== undefined && playlist.songs.length === 0) {
  409. CommunityStations.update({name: name}, {$unset: {"playlist": 1}});
  410. playlist = default_private_playlist;
  411. }
  412. songs = playlist.songs;
  413. songs.forEach(function (id, index) {
  414. if (id === currentId) {
  415. currentSong = index;
  416. }
  417. });
  418. if (currentSong < (songs.length - 1)) {
  419. currentSong++;
  420. } else currentSong = 0;
  421. currentId = songs[currentSong];
  422. CommunityStations.update({name: name}, {$set: {timePaused: 0}});
  423. this.songTimer();
  424. CommunityStations.update({name: name}, {$set: {currentSong: {song: songs[currentSong], started: startedAt}}});
  425. };
  426. CommunityStations.update({name: name}, {$set: {timePaused: 0}});
  427. var timer;
  428. var timerInitialised = false;
  429. this.songTimer = function () {
  430. if (state !== "paused") {
  431. startedAt = Date.now();
  432. if (timer !== undefined) {
  433. timer.pause();
  434. }
  435. timerInitialised = true;
  436. timer = new Timer(function () {
  437. self.skipSong();
  438. }, songs[currentSong].duration * 1000);
  439. }
  440. };
  441. var state = CommunityStations.findOne({name: name}).state;
  442. this.pauseRoom = function () {
  443. if (state !== "paused") {
  444. timer.pause();
  445. CommunityStations.update({name: name}, {$set: {state: "paused"}});
  446. state = "paused";
  447. }
  448. };
  449. this.resumeRoom = function () {
  450. if (state !== "playing") {
  451. if (!timerInitialised) {
  452. timer = new Timer(function () {
  453. self.skipSong();
  454. }, songs[currentSong] * 1000);
  455. }
  456. timer.resume();
  457. CommunityStations.update({name: name}, {$set: {state: "playing", timePaused: timer.timeWhenPaused()}});
  458. state = "playing";
  459. }
  460. };
  461. this.cancelTimer = function () {
  462. timer.pause();
  463. };
  464. this.getState = function () {
  465. return state;
  466. };
  467. this.name = name;
  468. var privacy = CommunityStations.findOne({name: name}).privacy;
  469. this.privacy = privacy;
  470. this.setPrivacy = function (privacy) {
  471. if (self.privacy !== privacy) {
  472. self.privacy = privacy;
  473. return CommunityStations.update({name: name}, {$set: {"privacy": privacy}});
  474. }
  475. };
  476. this.setPlaylist = function (plName) {
  477. if (PrivatePlaylists.findOne({name: plName, owner: _room.owner}) !== undefined) {
  478. CommunityStations.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. CommunityStations.update({name: name}, {$push: {allowed: allowed}});
  488. _room = CommunityStations.findOne({name: name});
  489. }
  490. };
  491. this.removeAllowed = function (allowed) {
  492. if (_room.allowed.indexOf(allowed) !== -1) {
  493. CommunityStations.update({name: name}, {$pull: {allowed: allowed}});
  494. _room = CommunityStations.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. CommunityStations.find({}).fetch().forEach(function (room) {
  613. var name = room.name;
  614. communityStations.push(new CommunityStation(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, "profile.usernameL": 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("community_stations", function () {
  681. var userId = this.userId;
  682. if (userId) {
  683. var user = Meteor.users.findOne(userId);
  684. if (user.profile.rank === "admin" || user.profile.rank === "moderator") {
  685. return CommunityStations.find({});
  686. } else {
  687. return CommunityStations.find({$or: [{owner: userId}, {privacy: "public"}]});
  688. }
  689. } else {
  690. return CommunityStations.find({privacy: "public"});
  691. }
  692. });
  693. Meteor.publish("community_station", function (name) {
  694. var userId = this.userId;
  695. if (userId) {
  696. var user = Meteor.users.findOne(userId);
  697. if (user.profile.rank === "admin" || user.profile.rank === "moderator") {
  698. return CommunityStations.find({name: name});
  699. } else {
  700. return CommunityStations.find({name: name, $or: [{owner: userId}, {privacy: "public"}]});
  701. }
  702. } else {
  703. return CommunityStations.find({name: name, $or: [{privacy: "public"}, {privacy: "unlisted"}]});
  704. }
  705. });
  706. Meteor.publish("private_playlists", function () {
  707. if (this.userId !== undefined) {
  708. return PrivatePlaylists.find({owner: this.userId});
  709. } else {
  710. return null;
  711. }
  712. });
  713. Meteor.publish("songsType", function (type) {
  714. return Songs.find({genres: type});
  715. });
  716. Meteor.publish("songs", function () {
  717. return Songs.find();
  718. });
  719. Meteor.publish("queues", function () {
  720. return Queues.find({});
  721. });
  722. Meteor.publish("reports", function () {
  723. return Reports.find({});
  724. });
  725. Meteor.publish("chat", function () {
  726. return Chat.find({});
  727. });
  728. Meteor.publish("userProfiles", function (username) {
  729. username = username.toLowerCase();
  730. console.log(username);
  731. console.log(Meteor.users.find({"profile.usernameL": username}, {
  732. fields: {
  733. "profile.username": 1,
  734. "profile.usernameL": 1,
  735. "profile.rank": 1,
  736. createdAt: 1,
  737. "profile.liked": 1,
  738. "profile.disliked": 1,
  739. "profile.settings": 1,
  740. "profile.realname": 1
  741. }
  742. }).fetch());
  743. var settings = Meteor.users.findOne({"profile.usernameL": username}, {fields: {"profile.settings": 1}});
  744. if (settings !== undefined && settings.profile.settings) {
  745. settings = settings.profile.settings;
  746. if (settings.showRating === true) {
  747. return Meteor.users.find({"profile.usernameL": username}, {
  748. fields: {
  749. "profile.username": 1,
  750. "profile.usernameL": 1,
  751. "profile.rank": 1,
  752. createdAt: 1,
  753. "profile.liked": 1,
  754. "profile.disliked": 1,
  755. "profile.settings": 1,
  756. "profile.realname": 1
  757. }
  758. });
  759. }
  760. }
  761. return Meteor.users.find({"profile.usernameL": username}, {
  762. fields: {
  763. "profile.username": 1,
  764. "profile.usernameL": 1,
  765. "profile.rank": 1,
  766. createdAt: 1,
  767. "profile.settings": 1,
  768. "profile.realname": 1
  769. }
  770. });
  771. });
  772. Meteor.publish("isAdmin", function () {
  773. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  774. });
  775. Meteor.publish("isModerator", function () {
  776. return Meteor.users.find({_id: this.userId, "profile.rank": "moderator"});
  777. });
  778. Meteor.publish("feedback", function(){
  779. return Feedback.find();
  780. })
  781. function isCommunityStationOwner(name) {
  782. var room = CommunityStations.findOne({name: name});
  783. if (Meteor.userId() && room !== undefined && Meteor.userId() === room.owner) {
  784. return true;
  785. } else {
  786. return false;
  787. }
  788. }
  789. function isAdmin() {
  790. var userData = Meteor.users.find(Meteor.userId());
  791. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  792. return true;
  793. } else {
  794. return false;
  795. }
  796. }
  797. function isModerator() {
  798. var userData = Meteor.users.find(Meteor.userId());
  799. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "moderator") {
  800. return true;
  801. } else {
  802. return isAdmin();
  803. }
  804. }
  805. function isBanned() {
  806. var userData = Meteor.users.findOne(Meteor.userId());
  807. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  808. var ban = userData.punishments.ban;
  809. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  810. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.ban": ""}});
  811. return false;
  812. } else {
  813. return true;
  814. }
  815. } else {
  816. return false;
  817. }
  818. }
  819. function isMuted() {
  820. var userData = Meteor.users.findOne(Meteor.userId());
  821. if (Meteor.userId() && userData !== undefined && userData.punishments !== undefined && userData.punishments.mute !== undefined) {
  822. var mute = userData.punishments.mute;
  823. if (new Date(mute.bannedUntil).getTime() <= new Date().getTime()) {
  824. Meteor.users.update(Meteor.userId(), {$unset: {"punishments.mute": ""}});
  825. return false;
  826. } else {
  827. return true;
  828. }
  829. } else {
  830. return false;
  831. }
  832. }
  833. Meteor.updatedMethods({
  834. deleteCommunityStation: function(roomName) {
  835. if ((isAdmin() || isCommunityStationOwner(roomName)) && !isBanned()) {
  836. CommunityStations.remove({name: roomName});
  837. getCommunityStation(roomName, function(room) {
  838. room.cancelTimer();
  839. delete communityStations[communityStations.indexOf(room)];
  840. });
  841. } else {
  842. throw new Meteor.Error(403, "Invalid permissions.");
  843. }
  844. },
  845. changeCommunityStationDescription: function(roomName, newDescription) {
  846. if ((isAdmin() || isCommunityStationOwner(roomName)) && !isBanned()) {
  847. CommunityStations.update({name: roomName}, {$set: {roomDesc: newDescription}});
  848. } else {
  849. throw new Meteor.Error(403, "Invalid permissions.");
  850. }
  851. },
  852. changeCommunityStationDisplayName: function(roomName, newDisplayName) {
  853. if ((isAdmin() || isCommunityStationOwner(roomName)) && !isBanned()) {
  854. CommunityStations.update({name: roomName}, {$set: {displayName: newDisplayName}});
  855. } else {
  856. throw new Meteor.Error(403, "Invalid permissions.");
  857. }
  858. },
  859. changeCommunityStationPrivacy: function(roomName, newPrivacy) {
  860. if ((isAdmin() || isCommunityStationOwner(roomName)) && !isBanned()) {
  861. CommunityStations.update({name: roomName}, {$set: {privacy: newPrivacy}});
  862. } else {
  863. throw new Meteor.Error(403, "Invalid permissions.");
  864. }
  865. },
  866. addVideoToPrivatePlaylist: {
  867. code: function(name, id) {
  868. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  869. if (pl !== undefined) {
  870. var copy = false;
  871. pl.songs.forEach(function(song) {
  872. if (song.id === id) {
  873. copy = true;
  874. }
  875. });
  876. if (!copy) {
  877. console.log(getSongDataYT(id));
  878. var data = getSongDataYT(id);
  879. data.id = id;
  880. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$push: {songs: data}});
  881. } else {
  882. throw new Meteor.Error(500, "Video is already in playlist.");
  883. }
  884. } else {
  885. throw new Meteor.Error(404, "Playlist not found.");
  886. }
  887. },
  888. requirements: ["login"]
  889. },
  890. removeVideoFromPrivatePlaylist: {
  891. code: function(name, id) {
  892. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  893. if (pl !== undefined) {
  894. var copy = false;
  895. var data;
  896. pl.songs.forEach(function(song) {
  897. if (song.id === id) {
  898. data = song;
  899. copy = true;
  900. }
  901. });
  902. if (copy) {
  903. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$pull: {songs: data}});
  904. } else {
  905. throw new Meteor.Error(500, "Video is not in playlist.");
  906. }
  907. } else {
  908. throw new Meteor.Error(404, "Playlist not found.");
  909. }
  910. },
  911. requirements: ["login"]
  912. },
  913. deletePrivatePlaylist: {
  914. code: function(name) {
  915. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  916. if (pl !== undefined) {
  917. PrivatePlaylists.remove({owner: Meteor.userId(), name: name});
  918. Deleted.insert({type: "PrivatePlaylist", data: pl});
  919. } else {
  920. throw new Meteor.Error(404, "Playlist not found.");
  921. }
  922. },
  923. requirements: ["login"]
  924. },
  925. activateAlert: {
  926. code: function(id) {
  927. Alerts.update(id, {$set: {active: true}});
  928. },
  929. requirements: ["admin"]
  930. },
  931. deactivateAlert: {
  932. code: function(id) {
  933. Alerts.update(id, {$set: {active: false}});
  934. },
  935. requirements: ["admin"]
  936. },
  937. deleteAlert: {
  938. code: function(id) {
  939. Alerts.remove(id);
  940. },
  941. requirements: ["admin"]
  942. },
  943. fetchSong: {
  944. code: function(type) {
  945. getStation(type, function (station) {
  946. station.fetchSongs();
  947. });
  948. },
  949. requirements: ["admin"]
  950. },
  951. removeSongs: {
  952. code: function(type) {
  953. getStation(type, function (station) {
  954. station.removeSongs();
  955. });
  956. },
  957. requirements: ["admin"]
  958. },
  959. lockRoom: {
  960. code: function (type) {
  961. getStation(type, function (station) {
  962. station.lock();
  963. });
  964. },
  965. requirements: ["admin"]
  966. },
  967. unlockRoom: {
  968. code: function (type) {
  969. getStation(type, function (station) {
  970. station.unlock();
  971. });
  972. },
  973. requirements: ["admin"]
  974. },
  975. banUser: {
  976. code: function (username, period, reason) {
  977. var user = Meteor.user();
  978. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  979. var bannedUntil = (new Date).getTime() + (period * 1000);
  980. if (bannedUntil > 8640000000000000) {
  981. bannedUntil = 8640000000000000;
  982. }
  983. bannedUntil = new Date(bannedUntil);
  984. var banObject = {
  985. bannedBy: user.profile.usernameL,
  986. bannedAt: new Date(Date.now()),
  987. bannedReason: reason,
  988. bannedUntil: bannedUntil
  989. };
  990. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  991. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  992. },
  993. requirements: ["admin"]
  994. },
  995. muteUser: {
  996. code: function (username, period) {
  997. var user = Meteor.user();
  998. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  999. if (period === undefined || Number(period) === 0) {
  1000. mutedUntil = 8640000000000000;
  1001. } else {
  1002. var mutedUntil = (new Date).getTime() + (period * 1000);
  1003. if (mutedUntil > 8640000000000000) {
  1004. mutedUntil = 8640000000000000;
  1005. }
  1006. }
  1007. mutedUntil = new Date(mutedUntil);
  1008. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  1009. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  1010. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  1011. },
  1012. requirements: ["admin"]
  1013. },
  1014. unbanUser: {
  1015. code: function (username) {
  1016. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  1017. },
  1018. requirements: ["admin"]
  1019. },
  1020. unsilenceUser: {
  1021. code: function (username) {
  1022. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  1023. },
  1024. requirements: ["admin"]
  1025. },
  1026. isBanned: function () {
  1027. return Meteor.isBanned();
  1028. },
  1029. isMuted: function () {
  1030. return isMuted();
  1031. },
  1032. updateSettings: {
  1033. code: function (showRating) {
  1034. var user = Meteor.user();
  1035. if (showRating !== true && showRating !== false) {
  1036. showRating = true;
  1037. }
  1038. if (user.profile.settings) {
  1039. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  1040. } else {
  1041. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  1042. }
  1043. },
  1044. requirements: ["login"]
  1045. },
  1046. addAlert: {
  1047. code: function (description) {
  1048. var username = Meteor.user().profile.username;
  1049. description = htmlEntities(description);
  1050. Alerts.insert({description: description, active: true, createdBy: username});
  1051. return true;
  1052. },
  1053. requirements: ["admin"]
  1054. },
  1055. sendMessage: {
  1056. code: function (type, message) {
  1057. var user = Meteor.user();
  1058. var time = new Date();
  1059. var rawrank = user.profile.rank;
  1060. var username = user.profile.username;
  1061. var profanity = false;
  1062. message = htmlEntities(message);
  1063. if (!message.replace(/\s/g, "").length > 0) {
  1064. throw new Meteor.Error(406, "Message length cannot be 0.");
  1065. }
  1066. if (message.length > 300) {
  1067. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  1068. }
  1069. else if (user.profile.rank === "admin") {
  1070. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1071. if (res.content.indexOf("true") > -1) {
  1072. return true;
  1073. } else {*/
  1074. Chat.insert({
  1075. type: type,
  1076. rawrank: rawrank,
  1077. rank: "[A]",
  1078. message: message,
  1079. time: time,
  1080. username: username
  1081. });
  1082. /*}
  1083. });*/
  1084. return true;
  1085. }
  1086. else if (user.profile.rank === "moderator") {
  1087. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1088. if (res.content.indexOf("true") > -1) {
  1089. return true;
  1090. } else {*/
  1091. Chat.insert({
  1092. type: type,
  1093. rawrank: rawrank,
  1094. rank: "[M]",
  1095. message: message,
  1096. time: time,
  1097. username: username
  1098. });
  1099. /*}
  1100. });*/
  1101. return true;
  1102. }
  1103. else {
  1104. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1105. if (res.content.indexOf("true") > -1) {
  1106. return true;
  1107. } else {*/
  1108. Chat.insert({
  1109. type: type,
  1110. rawrank: rawrank,
  1111. rank: "",
  1112. message: message,
  1113. time: time,
  1114. username: username
  1115. });
  1116. /*}
  1117. });*/
  1118. return true;
  1119. }
  1120. },
  1121. requirements: ["login", "noMute"]
  1122. },
  1123. likeSong: {
  1124. code: function (mid) {
  1125. var user = Meteor.user();
  1126. if (user.profile.liked.indexOf(mid) === -1) {
  1127. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  1128. Songs.update({mid: mid}, {$inc: {"likes": 1}})
  1129. } else {
  1130. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  1131. Songs.update({mid: mid}, {$inc: {likes: -1}})
  1132. }
  1133. if (user.profile.disliked.indexOf(mid) !== -1) {
  1134. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  1135. Songs.update({mid: mid}, {$inc: {dislikes: -1}})
  1136. }
  1137. return true;
  1138. },
  1139. requirements: ["login"]
  1140. },
  1141. dislikeSong: {
  1142. code: function (mid) {
  1143. var user = Meteor.user();
  1144. if (user.profile.disliked.indexOf(mid) === -1) {
  1145. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  1146. Songs.update({mid: mid}, {$inc: {dislikes: 1}});
  1147. } else {
  1148. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  1149. Songs.update({mid: mid}, {$inc: {dislikes: -1}});
  1150. }
  1151. if (user.profile.liked.indexOf(mid) !== -1) {
  1152. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  1153. Songs.update({mid: mid}, {$inc: {likes: -1}});
  1154. }
  1155. return true;
  1156. },
  1157. requirements: ["login"]
  1158. },
  1159. voteSkip: {
  1160. code: function (type) {
  1161. var user = Meteor.user();
  1162. getStation(type, function (station) {
  1163. if (station.voted.indexOf(user.profile.username) === -1) {
  1164. station.voted.push(user.profile.username);
  1165. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  1166. if (station.voted.length === 3) {
  1167. station.skipSong();
  1168. }
  1169. } else {
  1170. throw new Meteor.Error(401, "Already voted.");
  1171. }
  1172. });
  1173. },
  1174. requirements: ["login"]
  1175. },
  1176. votePrivateSkip: {
  1177. code: function (name) {
  1178. var user = Meteor.user();
  1179. getCommunityStation(name, function (station) {
  1180. if (station.voted.indexOf(user.profile.username) === -1) {
  1181. station.voted.push(user.profile.username);
  1182. CommunityStations.update({name: name}, {$set: {votes: station.voted.length}});
  1183. if (station.voted.length === 3) {
  1184. station.skipSong();
  1185. }
  1186. } else {
  1187. throw new Meteor.Error(401, "Already voted.");
  1188. }
  1189. });
  1190. },
  1191. requirements: ["login"]
  1192. },
  1193. submitReport: {
  1194. code: function (room, reportData) {
  1195. room = room.toLowerCase();
  1196. if (Rooms.find({type: room}).count() === 1) {
  1197. if (Reports.find({room: room}).count() === 0) {
  1198. Reports.insert({room: room, report: []});
  1199. }
  1200. if (reportData !== undefined) {
  1201. Reports.update({room: room}, {
  1202. $push: {
  1203. report: {
  1204. song: reportData.song,
  1205. type: reportData.type,
  1206. reason: reportData.reason,
  1207. other: reportData.other
  1208. }
  1209. }
  1210. });
  1211. return true;
  1212. } else {
  1213. throw new Meteor.Error(403, "Invalid data.");
  1214. }
  1215. } else {
  1216. throw new Meteor.Error(403, "Invalid genre.");
  1217. }
  1218. },
  1219. requirements: ["login"]
  1220. },
  1221. shufflePlaylist: {
  1222. code: function (type) {
  1223. getStation(type, function (station) {
  1224. if (station === undefined) {
  1225. throw new Meteor.Error(404, "Station not found.");
  1226. } else {
  1227. station.cancelTimer();
  1228. station.shufflePlaylist();
  1229. }
  1230. });
  1231. },
  1232. requirements: ["admin"]
  1233. },
  1234. skipSong: {
  1235. code: function (type) {
  1236. getStation(type, function (station) {
  1237. if (station === undefined) {
  1238. throw new Meteor.Error(404, "Station not found.");
  1239. } else {
  1240. station.skipSong();
  1241. }
  1242. });
  1243. },
  1244. requirements: ["admin"]
  1245. },
  1246. pauseRoom: {
  1247. code: function (type) {
  1248. getStation(type, function (station) {
  1249. if (station === undefined) {
  1250. throw new Meteor.Error(403, "Room doesn't exist.");
  1251. } else {
  1252. station.pauseRoom();
  1253. }
  1254. });
  1255. },
  1256. requirements: ["admin"]
  1257. },
  1258. resumeRoom: {
  1259. code: function (type) {
  1260. getStation(type, function (station) {
  1261. if (station === undefined) {
  1262. throw new Meteor.Error(403, "Room doesn't exist.");
  1263. } else {
  1264. station.resumeRoom();
  1265. }
  1266. });
  1267. },
  1268. requirements: ["admin"]
  1269. },
  1270. skipPrivateSong: function (name) {
  1271. if ((isAdmin() || isCommunityStationOwner(name)) && !isBanned()) {
  1272. getCommunityStation(name, function (station) {
  1273. if (station === undefined) {
  1274. throw new Meteor.Error(404, "Station not found.");
  1275. } else {
  1276. station.skipSong();
  1277. }
  1278. });
  1279. }
  1280. },
  1281. pauseCommunityStation: function (name) {
  1282. if ((isAdmin() || isCommunityStationOwner(name)) && !isBanned()) {
  1283. getCommunityStation(name, function (station) {
  1284. if (station === undefined) {
  1285. throw new Meteor.Error(403, "Room doesn't exist.");
  1286. } else {
  1287. station.pauseRoom();
  1288. }
  1289. });
  1290. } else {
  1291. throw new Meteor.Error(403, "Invalid permissions.");
  1292. }
  1293. },
  1294. resumeCommunityStation: function (name) {
  1295. if ((isAdmin() || isCommunityStationOwner(name)) && !isBanned()) {
  1296. getCommunityStation(name, function (station) {
  1297. if (station === undefined) {
  1298. throw new Meteor.Error(403, "Room doesn't exist.");
  1299. } else {
  1300. station.resumeRoom();
  1301. }
  1302. });
  1303. } else {
  1304. throw new Meteor.Error(403, "Invalid permissions.");
  1305. }
  1306. },
  1307. addAllowedToCommunityStation: function (name, allowed) {
  1308. if (isCommunityStationOwner(name) && !isBanned()) {
  1309. getCommunityStation(name, function (station) {
  1310. if (station === undefined) {
  1311. throw new Meteor.Error(403, "Room doesn't exist.");
  1312. } else {
  1313. allowed = allowed.toLowerCase();
  1314. allowed = Meteor.users.findOne({"profile.usernameL": allowed})._id;
  1315. station.addAllowed(allowed);
  1316. }
  1317. });
  1318. } else {
  1319. throw new Meteor.Error(403, "Invalid permissions.");
  1320. }
  1321. },
  1322. removeAllowedFromCommunityStation: function (name, allowed) {
  1323. if (isCommunityStationOwner(name) && !isBanned()) {
  1324. getCommunityStation(name, function (station) {
  1325. if (station === undefined) {
  1326. throw new Meteor.Error(403, "Room doesn't exist.");
  1327. } else {
  1328. station.removeAllowed(allowed);
  1329. }
  1330. });
  1331. } else {
  1332. throw new Meteor.Error(403, "Invalid permissions.");
  1333. }
  1334. },
  1335. setPlaylistForCommunityStation: function (name, playlist) {
  1336. if ((isCommunityStationOwner(name)) && !isBanned()) {
  1337. getCommunityStation(name, function (station) {
  1338. if (station === undefined) {
  1339. throw new Meteor.Error(403, "Room doesn't exist.");
  1340. } else {
  1341. station.setPlaylist(playlist);
  1342. }
  1343. });
  1344. } else {
  1345. throw new Meteor.Error(403, "Invalid permissions.");
  1346. }
  1347. },
  1348. createUserMethod: {
  1349. code: function (formData, captchaData) {
  1350. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  1351. if (!verifyCaptchaResponse.success) {
  1352. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  1353. } else {
  1354. Accounts.createUser({
  1355. username: formData.username,
  1356. email: formData.email,
  1357. password: formData.password
  1358. });
  1359. }
  1360. return true;
  1361. },
  1362. requirements: []
  1363. },
  1364. createArticle: {
  1365. code: function(data) {
  1366. var userId = Meteor.userId();
  1367. var requiredProperties = ["title", "content", "anonymous"];
  1368. if (data !== undefined && Object.keys(data).length === requiredProperties.length) {
  1369. for (var property in requiredProperties) {
  1370. if (data[requiredProperties[property]] === undefined) {
  1371. throw new Meteor.Error(403, "Invalid data.");
  1372. }
  1373. }
  1374. if (data.anonymous === false) {
  1375. data.author = Meteor.user().profile.username
  1376. } else {
  1377. data.author = "A Musare Admin";
  1378. }
  1379. delete data.anonymous;
  1380. data.time = new Date();
  1381. data.content = htmlEntities(data.content);
  1382. News.insert(data, function(err, res) {
  1383. if (err) {
  1384. console.log(err);
  1385. throw err.sanitizedError;
  1386. } else {
  1387. return true;
  1388. }
  1389. });
  1390. } else {
  1391. throw new Meteor.Error(403, "Invalid data.");
  1392. }
  1393. },
  1394. requirements: ["moderator"]
  1395. },
  1396. addSongToQueue: {
  1397. code: function (songData) {
  1398. var userId = Meteor.userId();
  1399. var requiredProperties = ["title", "artist", "id", "genres"];
  1400. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  1401. for (var property in requiredProperties) {
  1402. if (songData[requiredProperties[property]] === undefined) {
  1403. throw new Meteor.Error(403, "Invalid data.");
  1404. }
  1405. }
  1406. songData.duration = Number(getSongDuration(songData.title, songData.artist));
  1407. songData.img = getSongAlbumArt(songData.title, songData.artist) | "";
  1408. songData.skipDuration = 0;
  1409. songData.likes = 0;
  1410. songData.dislikes = 0;
  1411. songData.requestedBy = userId;
  1412. var mid = createUniqueSongId();
  1413. if (mid !== undefined) {
  1414. songData.mid = mid;
  1415. Queues.insert(songData, function(err, res) {
  1416. if (err) {
  1417. console.log(err);
  1418. throw err.sanitizedError;
  1419. } else {
  1420. var songsRequested = (Meteor.user().profile !== undefined && Meteor.user().profile.statistics !== undefined && Meteor.user().profile.statistics.songsRequested !== undefined) ? Meteor.user().profile.statistics.songsRequested : 0;
  1421. songsRequested++;
  1422. Meteor.users.update(Meteor.userId(), {$set: {"profile.statistics.songsRequested": songsRequested}}); // TODO Make mongo query use $inc correctly.
  1423. return true;
  1424. }
  1425. });
  1426. } else {
  1427. throw new Meteor.Error(500, "Am error occured.");
  1428. }
  1429. } else {
  1430. throw new Meteor.Error(403, "Invalid data.");
  1431. }
  1432. },
  1433. requirements: ["login"]
  1434. },
  1435. updateQueueSong: {
  1436. code: function (mid, newSong) {
  1437. Queues.update({mid: mid}, {$set: {
  1438. "title": newSong.title,
  1439. "artist": newSong.artist,
  1440. "id": newSong.id,
  1441. "img": newSong.img,
  1442. "duration" : newSong.duration,
  1443. "skipDuration" : newSong.skipDuration,
  1444. "genres": newSong.genres
  1445. }}, function(err) {
  1446. console.log(err);
  1447. if (err) {
  1448. throw err.sanitizedError;
  1449. } else {
  1450. return true;
  1451. }
  1452. });
  1453. },
  1454. requirements: ["moderator"]
  1455. },
  1456. updatePlaylistSong: {
  1457. code: function (mid, newSong) {
  1458. Songs.update({mid: mid}, {$set: {
  1459. "title": newSong.title,
  1460. "artist": newSong.artist,
  1461. "id": newSong.id,
  1462. "img": newSong.img,
  1463. "duration": newSong.duration,
  1464. "skipDuration": newSong.skipDuration,
  1465. "approvedBy": Meteor.userId(),
  1466. "genres": newSong.genres
  1467. }}, function(err) {
  1468. console.log(err);
  1469. if (err) {
  1470. throw err.sanitizedError;
  1471. } else {
  1472. return true;
  1473. }
  1474. });
  1475. return true;
  1476. },
  1477. requirements: ["moderator"]
  1478. },
  1479. removeSongFromQueue: {
  1480. code: function (mid) {
  1481. Queues.remove({mid: mid});
  1482. },
  1483. requirements: ["moderator"]
  1484. },
  1485. removeSongFromPlaylist: {
  1486. code: function (type, mid) {
  1487. Playlists.update({type: type}, {$pull: {songs: mid}});
  1488. },
  1489. requirements: ["moderator"]
  1490. },
  1491. deleteSong: {
  1492. code: function (mid) {
  1493. Songs.remove({mid: mid})
  1494. },
  1495. requirements: ["moderator"]
  1496. },
  1497. addSongToPlaylist: {
  1498. code: function (songData) {
  1499. var requiredProperties = ["_id", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy", "genres"];
  1500. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  1501. for (var property in requiredProperties) {
  1502. if (songData[requiredProperties[property]] === undefined) {
  1503. throw new Meteor.Error(403, "Invalid data.");
  1504. }
  1505. }
  1506. delete songData._id;
  1507. songData.approvedBy = Meteor.userId();
  1508. Songs.insert(songData);
  1509. Queues.remove({mid: songData.mid});
  1510. songData.genres.forEach(function(genre) {
  1511. genre = genre.toLowerCase();
  1512. if (Playlists.findOne({type: genre}) === undefined) {
  1513. Playlists.insert({type: genre, songs: [songData.mid]});
  1514. } else {
  1515. Playlists.update({type: genre}, {$push: {songs: songData.mid}});
  1516. }
  1517. });
  1518. return true;
  1519. } else {
  1520. throw new Meteor.Error(403, "Invalid data.");
  1521. }
  1522. },
  1523. requirements: ["moderator"]
  1524. },
  1525. createRoom: {
  1526. code: function (display, tag, private, desc) {
  1527. createRoom(display, tag, private, desc);
  1528. },
  1529. requirements: ["admin"]
  1530. },
  1531. createCommunityStation: {
  1532. code: function (name, display, private, desc) {
  1533. name = name.toLowerCase();
  1534. createCommunityStation(name, display, private, desc, Meteor.userId());
  1535. },
  1536. requirements: ["login"]
  1537. },
  1538. createPrivatePlaylist: {
  1539. code: function (name, display) {
  1540. name = name.toLowerCase();
  1541. if (PrivatePlaylists.findOne({name: name, owner: Meteor.userId()}) === undefined) {
  1542. PrivatePlaylists.insert({name: name, displayName: display, songs: [{id: "60ItHLz5WEA", duration: 213, title: "Alan Walker - Faded"}], owner: Meteor.userId()});
  1543. }
  1544. },
  1545. requirements: ["login"]
  1546. },
  1547. deleteRoom: {
  1548. code: function (type) {
  1549. Rooms.remove({type: type});
  1550. return true;
  1551. },
  1552. requirements: ["admin"]
  1553. },
  1554. getUserNum: {
  1555. code: function () {
  1556. return Object.keys(Meteor.default_server.sessions).length;
  1557. },
  1558. requirements: []
  1559. },
  1560. getTotalUsers: function () {
  1561. return Meteor.users.find().count();
  1562. },
  1563. updateRealName: {
  1564. code: function (realname) {
  1565. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  1566. Meteor.users.update(Meteor.userId(), {
  1567. $set: {"profile.realname": realname},
  1568. $push: {"profile.realnames": oldName}
  1569. });
  1570. },
  1571. requirements: ["login"]
  1572. },
  1573. updateUserName: {
  1574. code: function (newUserName) {
  1575. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  1576. Meteor.users.update(Meteor.userId(), {
  1577. $set: {
  1578. "username": newUserName,
  1579. "profile.username": newUserName,
  1580. "profile.usernameL": newUserName.toLowerCase()
  1581. }, $push: {"profile.usernames": oldUsername}
  1582. });
  1583. },
  1584. requirements: ["login"]
  1585. },
  1586. /*updateUserRank: function(newRank){
  1587. if (Meteor.userId()) {
  1588. Meteor.users.update(Meteor.userId(), {$set: {"profile.rank": newRank}});
  1589. } else {
  1590. throw new Meteor.Error(403, "Invalid permissions.");
  1591. }
  1592. },*/
  1593. deleteAccount: {
  1594. code: function () {
  1595. var user = Meteor.users.findOne(Meteor.userId());
  1596. Meteor.users.remove({_id: Meteor.userId()});
  1597. },
  1598. requirements: ["login"]
  1599. },
  1600. sendFeedback: {
  1601. code: function(message){
  1602. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1603. if (res.content.indexOf("true") > -1) {
  1604. return true;
  1605. } else {*/
  1606. Feedback.insert({
  1607. "username": Meteor.user().profile.username,
  1608. "message": message,
  1609. "upvotes": 0,
  1610. "upvotedBy": []
  1611. })
  1612. /*}
  1613. });*/
  1614. },
  1615. requirements: ["login"]
  1616. },
  1617. upvoteFeedback: {
  1618. code: function(message){
  1619. //TODO Fix feedback upvoting to use Id's
  1620. if(Feedback.findOne({"message": message}).upvotedBy.indexOf(Meteor.user().profile.username) === -1){
  1621. Feedback.update({"message": message}, {$inc: {"upvotes": 1}});
  1622. Feedback.update({"message": message}, {$push: {"upvotedBy": Meteor.user().profile.username}});
  1623. } else{
  1624. Feedback.update({"message": message}, {$inc: {"upvotes": -1}});
  1625. Feedback.update({"message": message}, {$pull: {"upvotedBy": Meteor.user().profile.username}});
  1626. }
  1627. },
  1628. requirements: ["login"]
  1629. },
  1630. deleteFeedback: {
  1631. code: function(message){
  1632. Feedback.remove({"message": message});
  1633. },
  1634. requirements: ["admin"]
  1635. },
  1636. updateFeedback: {
  1637. code: function(oldMessage, newMessage){
  1638. Feedback.update({"message": oldMessage}, {$set: {"message": newMessage}});
  1639. },
  1640. requirements: ["admin"]
  1641. },
  1642. editRoomDesc: {
  1643. code: function(type, description){
  1644. Rooms.update({type: type}, {$set: {"roomDesc": description}});
  1645. },
  1646. requirements: ["admin"]
  1647. },
  1648. removeReport: {
  1649. code: function(query, obj){
  1650. Reports.update(query, {$pull: {"report": obj}});
  1651. },
  1652. requirements: ["admin"]
  1653. }
  1654. });
  1655. Meteor.setInterval(function () {
  1656. checkUsersPR();
  1657. }, 10000);
  1658. Meteor.users.after.insert(function (err, user) {
  1659. Accounts.sendVerificationEmail(user._id);
  1660. });
  1661. function htmlEntities(str) {
  1662. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  1663. }