server.js 62 KB

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