server.js 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877
  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. var data = getSongDataYT(id);
  878. data.id = id;
  879. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$push: {songs: data}});
  880. } else {
  881. throw new Meteor.Error(500, "Video is already in playlist.");
  882. }
  883. } else {
  884. throw new Meteor.Error(404, "Playlist not found.");
  885. }
  886. },
  887. requirements: ["login"]
  888. },
  889. removeVideoFromPrivatePlaylist: {
  890. code: function(name, id) {
  891. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  892. if (pl !== undefined) {
  893. var copy = false;
  894. var data;
  895. pl.songs.forEach(function(song) {
  896. if (song.id === id) {
  897. data = song;
  898. copy = true;
  899. }
  900. });
  901. if (copy) {
  902. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$pull: {songs: data}});
  903. } else {
  904. throw new Meteor.Error(500, "Video is not in playlist.");
  905. }
  906. } else {
  907. throw new Meteor.Error(404, "Playlist not found.");
  908. }
  909. },
  910. requirements: ["login"]
  911. },
  912. moveVideoToTopOfPrivatePlaylist: {
  913. code: function(name, id) {
  914. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  915. if (pl !== undefined) {
  916. var songs = pl.songs;
  917. var song;
  918. songs.forEach(function(currentSong) {
  919. if (id === currentSong.id) {
  920. song = currentSong;
  921. }
  922. });
  923. console.log(song);
  924. if (song !== undefined) {
  925. var index = songs.indexOf(song);
  926. console.log(index);
  927. console.log(songs.length - 1);
  928. if (index > 0 && songs.length > 1) {
  929. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$pull: {songs: song}});
  930. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$push: {
  931. songs: {
  932. $each: [song],
  933. $position: 0
  934. }
  935. }});
  936. return true;
  937. } else {
  938. return false;
  939. }
  940. } else {
  941. throw new Meteor.Error(404, "Song not found.");
  942. }
  943. } else {
  944. throw new Meteor.Error(404, "Playlist not found.");
  945. }
  946. },
  947. requirements: ["login"]
  948. },
  949. moveVideoToBottomOfPrivatePlaylist: {
  950. code: function(name, id) {
  951. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  952. if (pl !== undefined) {
  953. var songs = pl.songs;
  954. var song;
  955. songs.forEach(function(currentSong) {
  956. if (id === currentSong.id) {
  957. song = currentSong;
  958. }
  959. });
  960. if (song !== undefined) {
  961. var index = songs.indexOf(song);
  962. if (index < (songs.length - 1) && index !== -1) {
  963. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$pull: {songs: song}});
  964. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$push: {songs: song}});
  965. return true;
  966. }
  967. } else {
  968. throw new Meteor.Error(404, "Song not found.");
  969. }
  970. } else {
  971. throw new Meteor.Error(404, "Playlist not found.");
  972. }
  973. },
  974. requirements: ["login"]
  975. },
  976. deletePrivatePlaylist: {
  977. code: function(name) {
  978. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  979. if (pl !== undefined) {
  980. PrivatePlaylists.remove({owner: Meteor.userId(), name: name});
  981. Deleted.insert({type: "PrivatePlaylist", data: pl});
  982. } else {
  983. throw new Meteor.Error(404, "Playlist not found.");
  984. }
  985. },
  986. requirements: ["login"]
  987. },
  988. renamePrivatePlaylistDisplayName: {
  989. code: function(name, newDisplayName) {
  990. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  991. if (pl !== undefined) {
  992. if (PrivatePlaylists.findOne({owner: Meteor.userId(), displayName: newDisplayName}) === undefined) {
  993. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$set: {displayName: newDisplayName}});
  994. } else {
  995. throw new Meteor.Error(500, "A playlist with that display name already exists.");
  996. }
  997. } else {
  998. throw new Meteor.Error(404, "Playlist not found.");
  999. }
  1000. },
  1001. requirements: ["login"]
  1002. },
  1003. renamePrivatePlaylistName: {
  1004. code: function(name, newName) {
  1005. var pl = PrivatePlaylists.findOne({owner: Meteor.userId(), name: name});
  1006. if (pl !== undefined) {
  1007. if (PrivatePlaylists.findOne({owner: Meteor.userId(), name: newName}) === undefined) {
  1008. PrivatePlaylists.update({owner: Meteor.userId(), name: name}, {$set: {name: newName}});
  1009. } else {
  1010. throw new Meteor.Error(500, "A playlist with that name already exists.");
  1011. }
  1012. } else {
  1013. throw new Meteor.Error(404, "Playlist not found.");
  1014. }
  1015. },
  1016. requirements: ["login"]
  1017. },
  1018. activateAlert: {
  1019. code: function(id) {
  1020. Alerts.update(id, {$set: {active: true}});
  1021. },
  1022. requirements: ["admin"]
  1023. },
  1024. deactivateAlert: {
  1025. code: function(id) {
  1026. Alerts.update(id, {$set: {active: false}});
  1027. },
  1028. requirements: ["admin"]
  1029. },
  1030. deleteAlert: {
  1031. code: function(id) {
  1032. Alerts.remove(id);
  1033. },
  1034. requirements: ["admin"]
  1035. },
  1036. fetchSong: {
  1037. code: function(type) {
  1038. getStation(type, function (station) {
  1039. station.fetchSongs();
  1040. });
  1041. },
  1042. requirements: ["admin"]
  1043. },
  1044. removeSongs: {
  1045. code: function(type) {
  1046. getStation(type, function (station) {
  1047. station.removeSongs();
  1048. });
  1049. },
  1050. requirements: ["admin"]
  1051. },
  1052. lockRoom: {
  1053. code: function (type) {
  1054. getStation(type, function (station) {
  1055. station.lock();
  1056. });
  1057. },
  1058. requirements: ["admin"]
  1059. },
  1060. unlockRoom: {
  1061. code: function (type) {
  1062. getStation(type, function (station) {
  1063. station.unlock();
  1064. });
  1065. },
  1066. requirements: ["admin"]
  1067. },
  1068. banUser: {
  1069. code: function (username, period, reason) {
  1070. var user = Meteor.user();
  1071. var bannedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  1072. var bannedUntil = (new Date).getTime() + (period * 1000);
  1073. if (bannedUntil > 8640000000000000) {
  1074. bannedUntil = 8640000000000000;
  1075. }
  1076. bannedUntil = new Date(bannedUntil);
  1077. var banObject = {
  1078. bannedBy: user.profile.usernameL,
  1079. bannedAt: new Date(Date.now()),
  1080. bannedReason: reason,
  1081. bannedUntil: bannedUntil
  1082. };
  1083. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$set: {"punishments.ban": banObject}});
  1084. Meteor.users.update({"profile.usernameL": bannedUser.profile.usernameL}, {$push: {"punishments.bans": banObject}});
  1085. },
  1086. requirements: ["admin"]
  1087. },
  1088. muteUser: {
  1089. code: function (username, period) {
  1090. var user = Meteor.user();
  1091. var mutedUser = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  1092. if (period === undefined || Number(period) === 0) {
  1093. mutedUntil = 8640000000000000;
  1094. } else {
  1095. var mutedUntil = (new Date).getTime() + (period * 1000);
  1096. if (mutedUntil > 8640000000000000) {
  1097. mutedUntil = 8640000000000000;
  1098. }
  1099. }
  1100. mutedUntil = new Date(mutedUntil);
  1101. var muteObject = {mutedBy: user.profile.usernameL, mutedAt: new Date(Date.now()), mutedUntil: mutedUntil};
  1102. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$set: {"punishments.mute": muteObject}});
  1103. Meteor.users.update({"profile.usernameL": mutedUser.profile.usernameL}, {$push: {"punishments.mutes": muteObject}});
  1104. },
  1105. requirements: ["admin"]
  1106. },
  1107. unbanUser: {
  1108. code: function (username) {
  1109. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.ban"});
  1110. },
  1111. requirements: ["admin"]
  1112. },
  1113. unsilenceUser: {
  1114. code: function (username) {
  1115. Meteor.users.update({"profile.usernameL": username.toLowerCase()}, {$unset: "punishments.mute"});
  1116. },
  1117. requirements: ["admin"]
  1118. },
  1119. isBanned: function () {
  1120. return Meteor.isBanned();
  1121. },
  1122. isMuted: function () {
  1123. return isMuted();
  1124. },
  1125. updateSettings: {
  1126. code: function (showRating) {
  1127. var user = Meteor.user();
  1128. if (showRating !== true && showRating !== false) {
  1129. showRating = true;
  1130. }
  1131. if (user.profile.settings) {
  1132. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings.showRating": showRating}});
  1133. } else {
  1134. Meteor.users.update({"profile.username": user.profile.username}, {$set: {"profile.settings": {showRating: showRating}}});
  1135. }
  1136. },
  1137. requirements: ["login"]
  1138. },
  1139. addAlert: {
  1140. code: function (description) {
  1141. var username = Meteor.user().profile.username;
  1142. description = htmlEntities(description);
  1143. Alerts.insert({description: description, active: true, createdBy: username});
  1144. return true;
  1145. },
  1146. requirements: ["admin"]
  1147. },
  1148. sendMessage: {
  1149. code: function (type, message) {
  1150. var user = Meteor.user();
  1151. var time = new Date();
  1152. var rawrank = user.profile.rank;
  1153. var username = user.profile.username;
  1154. var profanity = false;
  1155. message = htmlEntities(message);
  1156. if (!message.replace(/\s/g, "").length > 0) {
  1157. throw new Meteor.Error(406, "Message length cannot be 0.");
  1158. }
  1159. if (message.length > 300) {
  1160. throw new Meteor.Error(406, "Message length cannot be more than 300 characters long..");
  1161. }
  1162. else if (user.profile.rank === "admin") {
  1163. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1164. if (res.content.indexOf("true") > -1) {
  1165. return true;
  1166. } else {*/
  1167. Chat.insert({
  1168. type: type,
  1169. rawrank: rawrank,
  1170. rank: "[A]",
  1171. message: message,
  1172. time: time,
  1173. username: username
  1174. });
  1175. /*}
  1176. });*/
  1177. return true;
  1178. }
  1179. else if (user.profile.rank === "moderator") {
  1180. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1181. if (res.content.indexOf("true") > -1) {
  1182. return true;
  1183. } else {*/
  1184. Chat.insert({
  1185. type: type,
  1186. rawrank: rawrank,
  1187. rank: "[M]",
  1188. message: message,
  1189. time: time,
  1190. username: username
  1191. });
  1192. /*}
  1193. });*/
  1194. return true;
  1195. }
  1196. else {
  1197. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1198. if (res.content.indexOf("true") > -1) {
  1199. return true;
  1200. } else {*/
  1201. Chat.insert({
  1202. type: type,
  1203. rawrank: rawrank,
  1204. rank: "",
  1205. message: message,
  1206. time: time,
  1207. username: username
  1208. });
  1209. /*}
  1210. });*/
  1211. return true;
  1212. }
  1213. },
  1214. requirements: ["login", "noMute"]
  1215. },
  1216. likeSong: {
  1217. code: function (mid) {
  1218. var user = Meteor.user();
  1219. if (user.profile.liked.indexOf(mid) === -1) {
  1220. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.liked": mid}});
  1221. Songs.update({mid: mid}, {$inc: {"likes": 1}})
  1222. } else {
  1223. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  1224. Songs.update({mid: mid}, {$inc: {likes: -1}})
  1225. }
  1226. if (user.profile.disliked.indexOf(mid) !== -1) {
  1227. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  1228. Songs.update({mid: mid}, {$inc: {dislikes: -1}})
  1229. }
  1230. return true;
  1231. },
  1232. requirements: ["login"]
  1233. },
  1234. dislikeSong: {
  1235. code: function (mid) {
  1236. var user = Meteor.user();
  1237. if (user.profile.disliked.indexOf(mid) === -1) {
  1238. Meteor.users.update({"profile.username": user.profile.username}, {$push: {"profile.disliked": mid}});
  1239. Songs.update({mid: mid}, {$inc: {dislikes: 1}});
  1240. } else {
  1241. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.disliked": mid}});
  1242. Songs.update({mid: mid}, {$inc: {dislikes: -1}});
  1243. }
  1244. if (user.profile.liked.indexOf(mid) !== -1) {
  1245. Meteor.users.update({"profile.username": user.profile.username}, {$pull: {"profile.liked": mid}});
  1246. Songs.update({mid: mid}, {$inc: {likes: -1}});
  1247. }
  1248. return true;
  1249. },
  1250. requirements: ["login"]
  1251. },
  1252. voteSkip: {
  1253. code: function (type) {
  1254. var user = Meteor.user();
  1255. getStation(type, function (station) {
  1256. if (station.voted.indexOf(user.profile.username) === -1) {
  1257. station.voted.push(user.profile.username);
  1258. Rooms.update({type: type}, {$set: {votes: station.voted.length}});
  1259. if (station.voted.length === 3) {
  1260. station.skipSong();
  1261. }
  1262. } else {
  1263. throw new Meteor.Error(401, "Already voted.");
  1264. }
  1265. });
  1266. },
  1267. requirements: ["login"]
  1268. },
  1269. votePrivateSkip: {
  1270. code: function (name) {
  1271. var user = Meteor.user();
  1272. getCommunityStation(name, function (station) {
  1273. if (station.voted.indexOf(user.profile.username) === -1) {
  1274. station.voted.push(user.profile.username);
  1275. CommunityStations.update({name: name}, {$set: {votes: station.voted.length}});
  1276. if (station.voted.length === 3) {
  1277. station.skipSong();
  1278. }
  1279. } else {
  1280. throw new Meteor.Error(401, "Already voted.");
  1281. }
  1282. });
  1283. },
  1284. requirements: ["login"]
  1285. },
  1286. submitReport: {
  1287. code: function (room, reportData) {
  1288. room = room.toLowerCase();
  1289. if (Rooms.find({type: room}).count() === 1) {
  1290. if (Reports.find({room: room}).count() === 0) {
  1291. Reports.insert({room: room, report: []});
  1292. }
  1293. if (reportData !== undefined) {
  1294. Reports.update({room: room}, {
  1295. $push: {
  1296. report: {
  1297. song: reportData.song,
  1298. type: reportData.type,
  1299. reason: reportData.reason,
  1300. other: reportData.other
  1301. }
  1302. }
  1303. });
  1304. return true;
  1305. } else {
  1306. throw new Meteor.Error(403, "Invalid data.");
  1307. }
  1308. } else {
  1309. throw new Meteor.Error(403, "Invalid genre.");
  1310. }
  1311. },
  1312. requirements: ["login"]
  1313. },
  1314. shufflePlaylist: {
  1315. code: function (type) {
  1316. getStation(type, function (station) {
  1317. if (station === undefined) {
  1318. throw new Meteor.Error(404, "Station not found.");
  1319. } else {
  1320. station.cancelTimer();
  1321. station.shufflePlaylist();
  1322. }
  1323. });
  1324. },
  1325. requirements: ["admin"]
  1326. },
  1327. skipSong: {
  1328. code: function (type) {
  1329. getStation(type, function (station) {
  1330. if (station === undefined) {
  1331. throw new Meteor.Error(404, "Station not found.");
  1332. } else {
  1333. station.skipSong();
  1334. }
  1335. });
  1336. },
  1337. requirements: ["admin"]
  1338. },
  1339. pauseRoom: {
  1340. code: function (type) {
  1341. getStation(type, function (station) {
  1342. if (station === undefined) {
  1343. throw new Meteor.Error(403, "Room doesn't exist.");
  1344. } else {
  1345. station.pauseRoom();
  1346. }
  1347. });
  1348. },
  1349. requirements: ["admin"]
  1350. },
  1351. resumeRoom: {
  1352. code: function (type) {
  1353. getStation(type, function (station) {
  1354. if (station === undefined) {
  1355. throw new Meteor.Error(403, "Room doesn't exist.");
  1356. } else {
  1357. station.resumeRoom();
  1358. }
  1359. });
  1360. },
  1361. requirements: ["admin"]
  1362. },
  1363. skipPrivateSong: function (name) {
  1364. if ((isAdmin() || isCommunityStationOwner(name)) && !isBanned()) {
  1365. getCommunityStation(name, function (station) {
  1366. if (station === undefined) {
  1367. throw new Meteor.Error(404, "Station not found.");
  1368. } else {
  1369. station.skipSong();
  1370. }
  1371. });
  1372. }
  1373. },
  1374. pauseCommunityStation: function (name) {
  1375. if ((isAdmin() || isCommunityStationOwner(name)) && !isBanned()) {
  1376. getCommunityStation(name, function (station) {
  1377. if (station === undefined) {
  1378. throw new Meteor.Error(403, "Room doesn't exist.");
  1379. } else {
  1380. station.pauseRoom();
  1381. }
  1382. });
  1383. } else {
  1384. throw new Meteor.Error(403, "Invalid permissions.");
  1385. }
  1386. },
  1387. resumeCommunityStation: function (name) {
  1388. if ((isAdmin() || isCommunityStationOwner(name)) && !isBanned()) {
  1389. getCommunityStation(name, function (station) {
  1390. if (station === undefined) {
  1391. throw new Meteor.Error(403, "Room doesn't exist.");
  1392. } else {
  1393. station.resumeRoom();
  1394. }
  1395. });
  1396. } else {
  1397. throw new Meteor.Error(403, "Invalid permissions.");
  1398. }
  1399. },
  1400. addAllowedToCommunityStation: function (name, allowed) {
  1401. if (isCommunityStationOwner(name) && !isBanned()) {
  1402. getCommunityStation(name, function (station) {
  1403. if (station === undefined) {
  1404. throw new Meteor.Error(403, "Room doesn't exist.");
  1405. } else {
  1406. allowed = allowed.toLowerCase();
  1407. allowed = Meteor.users.findOne({"profile.usernameL": allowed})._id;
  1408. station.addAllowed(allowed);
  1409. }
  1410. });
  1411. } else {
  1412. throw new Meteor.Error(403, "Invalid permissions.");
  1413. }
  1414. },
  1415. removeAllowedFromCommunityStation: function (name, allowed) {
  1416. if (isCommunityStationOwner(name) && !isBanned()) {
  1417. getCommunityStation(name, function (station) {
  1418. if (station === undefined) {
  1419. throw new Meteor.Error(403, "Room doesn't exist.");
  1420. } else {
  1421. station.removeAllowed(allowed);
  1422. }
  1423. });
  1424. } else {
  1425. throw new Meteor.Error(403, "Invalid permissions.");
  1426. }
  1427. },
  1428. setPlaylistForCommunityStation: function (name, playlist) {
  1429. if ((isCommunityStationOwner(name)) && !isBanned()) {
  1430. getCommunityStation(name, function (station) {
  1431. if (station === undefined) {
  1432. throw new Meteor.Error(403, "Room doesn't exist.");
  1433. } else {
  1434. station.setPlaylist(playlist);
  1435. }
  1436. });
  1437. } else {
  1438. throw new Meteor.Error(403, "Invalid permissions.");
  1439. }
  1440. },
  1441. createUserMethod: {
  1442. code: function (formData, captchaData) {
  1443. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  1444. if (!verifyCaptchaResponse.success) {
  1445. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  1446. } else {
  1447. Accounts.createUser({
  1448. username: formData.username,
  1449. email: formData.email,
  1450. password: formData.password
  1451. });
  1452. }
  1453. return true;
  1454. },
  1455. requirements: []
  1456. },
  1457. promoteUserMethod: {
  1458. code: function(user) {
  1459. Meteor.users.find({"profile.usernameL": username.toLowerCase()})
  1460. }
  1461. },
  1462. createArticle: {
  1463. code: function(data) {
  1464. var userId = Meteor.userId();
  1465. var requiredProperties = ["title", "content", "anonymous"];
  1466. if (data !== undefined && Object.keys(data).length === requiredProperties.length) {
  1467. for (var property in requiredProperties) {
  1468. if (data[requiredProperties[property]] === undefined) {
  1469. throw new Meteor.Error(403, "Invalid data.");
  1470. }
  1471. }
  1472. if (data.anonymous === false) {
  1473. data.author = Meteor.user().profile.username
  1474. } else {
  1475. data.author = "A Musare Admin";
  1476. }
  1477. delete data.anonymous;
  1478. data.time = new Date();
  1479. data.content = htmlEntities(data.content);
  1480. News.insert(data, function(err, res) {
  1481. if (err) {
  1482. console.log(err);
  1483. throw err.sanitizedError;
  1484. } else {
  1485. return true;
  1486. }
  1487. });
  1488. } else {
  1489. throw new Meteor.Error(403, "Invalid data.");
  1490. }
  1491. },
  1492. requirements: ["moderator"]
  1493. },
  1494. addSongToQueue: {
  1495. code: function (songData) {
  1496. var userId = Meteor.userId();
  1497. var requiredProperties = ["title", "artist", "id", "genres"];
  1498. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  1499. for (var property in requiredProperties) {
  1500. if (songData[requiredProperties[property]] === undefined) {
  1501. throw new Meteor.Error(403, "Invalid data.");
  1502. }
  1503. }
  1504. songData.duration = Number(getSongDuration(songData.title, songData.artist));
  1505. songData.img = getSongAlbumArt(songData.title, songData.artist) | "";
  1506. songData.skipDuration = 0;
  1507. songData.likes = 0;
  1508. songData.dislikes = 0;
  1509. songData.requestedBy = userId;
  1510. var mid = createUniqueSongId();
  1511. if (mid !== undefined) {
  1512. songData.mid = mid;
  1513. Queues.insert(songData, function(err, res) {
  1514. if (err) {
  1515. console.log(err);
  1516. throw err.sanitizedError;
  1517. } else {
  1518. var songsRequested = (Meteor.user().profile !== undefined && Meteor.user().profile.statistics !== undefined && Meteor.user().profile.statistics.songsRequested !== undefined) ? Meteor.user().profile.statistics.songsRequested : 0;
  1519. songsRequested++;
  1520. Meteor.users.update(Meteor.userId(), {$set: {"profile.statistics.songsRequested": songsRequested}}); // TODO Make mongo query use $inc correctly.
  1521. return true;
  1522. }
  1523. });
  1524. } else {
  1525. throw new Meteor.Error(500, "Am error occured.");
  1526. }
  1527. } else {
  1528. throw new Meteor.Error(403, "Invalid data.");
  1529. }
  1530. },
  1531. requirements: ["login"]
  1532. },
  1533. updateQueueSong: {
  1534. code: function (mid, newSong) {
  1535. Queues.update({mid: mid}, {$set: {
  1536. "title": newSong.title,
  1537. "artist": newSong.artist,
  1538. "id": newSong.id,
  1539. "img": newSong.img,
  1540. "duration" : newSong.duration,
  1541. "skipDuration" : newSong.skipDuration,
  1542. "genres": newSong.genres
  1543. }}, function(err) {
  1544. console.log(err);
  1545. if (err) {
  1546. throw err.sanitizedError;
  1547. } else {
  1548. return true;
  1549. }
  1550. });
  1551. },
  1552. requirements: ["moderator"]
  1553. },
  1554. updatePlaylistSong: {
  1555. code: function (mid, newSong) {
  1556. Songs.update({mid: mid}, {$set: {
  1557. "title": newSong.title,
  1558. "artist": newSong.artist,
  1559. "id": newSong.id,
  1560. "img": newSong.img,
  1561. "duration": newSong.duration,
  1562. "skipDuration": newSong.skipDuration,
  1563. "approvedBy": Meteor.userId(),
  1564. "genres": newSong.genres
  1565. }}, function(err) {
  1566. console.log(err);
  1567. if (err) {
  1568. throw err.sanitizedError;
  1569. } else {
  1570. return true;
  1571. }
  1572. });
  1573. return true;
  1574. },
  1575. requirements: ["moderator"]
  1576. },
  1577. removeSongFromQueue: {
  1578. code: function (mid) {
  1579. Queues.remove({mid: mid});
  1580. },
  1581. requirements: ["moderator"]
  1582. },
  1583. removeSongFromPlaylist: {
  1584. code: function (type, mid) {
  1585. Playlists.update({type: type}, {$pull: {songs: mid}});
  1586. },
  1587. requirements: ["moderator"]
  1588. },
  1589. deleteSong: {
  1590. code: function (mid) {
  1591. Songs.remove({mid: mid})
  1592. },
  1593. requirements: ["moderator"]
  1594. },
  1595. addSongToPlaylist: {
  1596. code: function (songData) {
  1597. var requiredProperties = ["_id", "mid", "id", "title", "artist", "duration", "skipDuration", "img", "likes", "dislikes", "requestedBy", "genres"];
  1598. if (songData !== undefined && Object.keys(songData).length === requiredProperties.length) {
  1599. for (var property in requiredProperties) {
  1600. if (songData[requiredProperties[property]] === undefined) {
  1601. throw new Meteor.Error(403, "Invalid data.");
  1602. }
  1603. }
  1604. delete songData._id;
  1605. songData.approvedBy = Meteor.userId();
  1606. Songs.insert(songData);
  1607. Queues.remove({mid: songData.mid});
  1608. songData.genres.forEach(function(genre) {
  1609. genre = genre.toLowerCase();
  1610. if (Playlists.findOne({type: genre}) === undefined) {
  1611. Playlists.insert({type: genre, songs: [songData.mid]});
  1612. } else {
  1613. Playlists.update({type: genre}, {$push: {songs: songData.mid}});
  1614. }
  1615. });
  1616. return true;
  1617. } else {
  1618. throw new Meteor.Error(403, "Invalid data.");
  1619. }
  1620. },
  1621. requirements: ["moderator"]
  1622. },
  1623. createRoom: {
  1624. code: function (display, tag, private, desc) {
  1625. createRoom(display, tag, private, desc);
  1626. },
  1627. requirements: ["admin"]
  1628. },
  1629. createCommunityStation: {
  1630. code: function (name, display, private, desc) {
  1631. name = name.toLowerCase();
  1632. createCommunityStation(name, display, private, desc, Meteor.userId());
  1633. },
  1634. requirements: ["login"]
  1635. },
  1636. createPrivatePlaylist: {
  1637. code: function (name, display) {
  1638. name = name.toLowerCase();
  1639. if (PrivatePlaylists.findOne({name: name, owner: Meteor.userId()}) === undefined) {
  1640. PrivatePlaylists.insert({name: name, displayName: display, songs: [{id: "60ItHLz5WEA", duration: 213, title: "Alan Walker - Faded"}], owner: Meteor.userId()});
  1641. }
  1642. },
  1643. requirements: ["login"]
  1644. },
  1645. deleteRoom: {
  1646. code: function (type) {
  1647. Rooms.remove({type: type});
  1648. return true;
  1649. },
  1650. requirements: ["admin"]
  1651. },
  1652. getUserNum: {
  1653. code: function () {
  1654. return Object.keys(Meteor.default_server.sessions).length;
  1655. },
  1656. requirements: []
  1657. },
  1658. getTotalUsers: function () {
  1659. return Meteor.users.find().count();
  1660. },
  1661. updateRealName: {
  1662. code: function (realname) {
  1663. var oldName = Meteor.users.findOne(Meteor.userId()).profile.realname;
  1664. Meteor.users.update(Meteor.userId(), {
  1665. $set: {"profile.realname": realname},
  1666. $push: {"profile.realnames": oldName}
  1667. });
  1668. },
  1669. requirements: ["login"]
  1670. },
  1671. updateUserName: {
  1672. code: function (newUserName) {
  1673. var oldUsername = Meteor.users.findOne(Meteor.userId()).profile.username;
  1674. Meteor.users.update(Meteor.userId(), {
  1675. $set: {
  1676. "username": newUserName,
  1677. "profile.username": newUserName,
  1678. "profile.usernameL": newUserName.toLowerCase()
  1679. }, $push: {"profile.usernames": oldUsername}
  1680. });
  1681. },
  1682. requirements: ["login"]
  1683. },
  1684. promoteUserRank: {
  1685. code: function(username){
  1686. if (Meteor.userId()) {
  1687. Meteor.users.update({"username": username}, {$set: {"profile.rank": "admin"}});
  1688. } else {
  1689. throw new Meteor.Error(403, "Invalid permissions.");
  1690. }
  1691. }
  1692. },
  1693. demoteUserRank: {
  1694. code: function(username){
  1695. if (Meteor.userId()) {
  1696. Meteor.users.update({"username": username}, {$set: {"profile.rank": "default"}});
  1697. } else {
  1698. throw new Meteor.Error(403, "Invalid permissions.");
  1699. }
  1700. }
  1701. },
  1702. deleteAccount: {
  1703. code: function () {
  1704. var user = Meteor.users.findOne(Meteor.userId());
  1705. Meteor.users.remove({_id: Meteor.userId()});
  1706. },
  1707. requirements: ["login"]
  1708. },
  1709. sendFeedback: {
  1710. code: function(message){
  1711. /*HTTP.call("GET", "http://www.wdyl.com/profanity?q=" + encodeURIComponent(message), function (err, res) {
  1712. if (res.content.indexOf("true") > -1) {
  1713. return true;
  1714. } else {*/
  1715. Feedback.insert({
  1716. "username": Meteor.user().profile.username,
  1717. "message": message,
  1718. "upvotes": 0,
  1719. "upvotedBy": []
  1720. })
  1721. /*}
  1722. });*/
  1723. },
  1724. requirements: ["login"]
  1725. },
  1726. upvoteFeedback: {
  1727. code: function(message){
  1728. //TODO Fix feedback upvoting to use Id's
  1729. if(Feedback.findOne({"message": message}).upvotedBy.indexOf(Meteor.user().profile.username) === -1){
  1730. Feedback.update({"message": message}, {$inc: {"upvotes": 1}});
  1731. Feedback.update({"message": message}, {$push: {"upvotedBy": Meteor.user().profile.username}});
  1732. } else{
  1733. Feedback.update({"message": message}, {$inc: {"upvotes": -1}});
  1734. Feedback.update({"message": message}, {$pull: {"upvotedBy": Meteor.user().profile.username}});
  1735. }
  1736. },
  1737. requirements: ["login"]
  1738. },
  1739. deleteFeedback: {
  1740. code: function(message){
  1741. Feedback.remove({"message": message});
  1742. },
  1743. requirements: ["admin"]
  1744. },
  1745. updateFeedback: {
  1746. code: function(oldMessage, newMessage){
  1747. Feedback.update({"message": oldMessage}, {$set: {"message": newMessage}});
  1748. },
  1749. requirements: ["admin"]
  1750. },
  1751. editRoomDesc: {
  1752. code: function(type, description){
  1753. Rooms.update({type: type}, {$set: {"roomDesc": description}});
  1754. },
  1755. requirements: ["admin"]
  1756. },
  1757. removeReport: {
  1758. code: function(query, obj){
  1759. Reports.update(query, {$pull: {"report": obj}});
  1760. },
  1761. requirements: ["admin"]
  1762. }
  1763. });
  1764. Meteor.setInterval(function () {
  1765. checkUsersPR();
  1766. }, 10000);
  1767. Meteor.users.after.insert(function (err, user) {
  1768. Accounts.sendVerificationEmail(user._id);
  1769. });
  1770. function htmlEntities(str) {
  1771. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  1772. }