client.js 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. Meteor.startup(function() {
  2. reCAPTCHA.config({
  3. publickey: '6LcVxg0TAAAAAE18vBiH00UAyaJggsmLm890SjZl'
  4. });
  5. Avatar.setOptions({
  6. fallbackType: "initials",
  7. defaultImageUrl: "http://static.boredpanda.com/blog/wp-content/uploads/2014/04/amazing-fox-photos-182.jpg",
  8. generateCSS: true,
  9. imageSizes: {
  10. 'header': 40
  11. }
  12. });
  13. });
  14. // Way to get paramater from url.
  15. // Taken from http://stackoverflow.com/a/979997/4670703
  16. // gup('q', 'http://example.com/?q=abc') returns abc.
  17. function gup( name, url ) {
  18. if (!url) url = location.href;
  19. name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  20. var regexS = "[\\?&]"+name+"=([^&#]*)";
  21. var regex = new RegExp( regexS );
  22. var results = regex.exec( url );
  23. return results == null ? null : results[1];
  24. }
  25. /* Global Helpers */
  26. Handlebars.registerHelper("isAdmin", function(argument){
  27. if (Meteor.user() && Meteor.user().profile) {
  28. return Meteor.user().profile.rank === "admin";
  29. } else {
  30. return false;
  31. }
  32. });
  33. Handlebars.registerHelper("isModerator", function(argument){
  34. if (Meteor.user() && Meteor.user().profile && (Meteor.user().profile.rank === "admin" || Meteor.user().profile.rank === "moderator")) {
  35. return true;
  36. } else {
  37. return false;
  38. }
  39. });
  40. Handlebars.registerHelper("initials", function(argument){
  41. var user = Meteor.user();
  42. if (user !== undefined) {
  43. return user.profile.username[0].toUpperCase();
  44. } else {
  45. return "";
  46. }
  47. });
  48. Deps.autorun(function() {
  49. Meteor.subscribe("queues");
  50. Meteor.subscribe("reports");
  51. Meteor.subscribe("chat");
  52. Meteor.subscribe("playlists");
  53. Meteor.subscribe("alerts");
  54. Meteor.subscribe("rooms");
  55. Meteor.subscribe("userData", Meteor.userId());
  56. });
  57. var ban_interval = Meteor.setInterval(function() {
  58. var userId = Meteor.userId();
  59. if (userId !== undefined) {
  60. var userData = Meteor.user();
  61. if (localStorage.getItem("banned") === "true") {
  62. if (userData !== undefined && userData !== null && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  63. var ban = userData.punishments.ban;
  64. if (new Date(ban.bannedUntil).getTime() <= new Date().getTime()) {
  65. Meteor.call("isBanned", function(err, res) {
  66. if (res === false) {
  67. localStorage.setItem("banned", false);
  68. Meteor._reload.reload();
  69. }
  70. });
  71. }
  72. } else {
  73. localStorage.setItem("banned", false);
  74. Meteor._reload.reload();
  75. }
  76. } else {
  77. if (userData !== undefined && userData !== null && userData.punishments !== undefined && userData.punishments.ban !== undefined) {
  78. localStorage.setItem("banned", true);
  79. Meteor._reload.reload();
  80. }
  81. }
  82. }
  83. }, 1000);
  84. var minterval;
  85. var hpSound = undefined;
  86. var songsArr = [];
  87. var SCPlayer = undefined;
  88. var parts = location.href.split('/');
  89. var id = parts.pop();
  90. var type = id.toLowerCase();
  91. var resizeSeekerbarInterval;
  92. var StationSubscription = undefined;
  93. UI.registerHelper("formatTime", function(seconds) {
  94. var d = moment.duration(parseInt(seconds), 'seconds');
  95. return d.minutes() + ":" + ("0" + d.seconds()).slice(-2);
  96. });
  97. /*UI.registerHelper("formatTimeFromNow", function(time) {
  98. var d = moment(time);
  99. return d.fromNow();
  100. });*/
  101. function getSpotifyInfo(title, cb, artist) {
  102. var q = "";
  103. q = title;
  104. if (artist !== undefined) {
  105. q += " artist:" + artist;
  106. }
  107. $.ajax({
  108. type: "GET",
  109. url: 'https://api.spotify.com/v1/search?q=' + encodeURIComponent(q) + '&type=track',
  110. applicationType: "application/json",
  111. contentType: "json",
  112. success: function (data) {
  113. cb(data);
  114. }
  115. });
  116. }
  117. // Admin Template
  118. Template.admin.helpers({
  119. queueCount: function(display) {
  120. display = display.toLowerCase();
  121. return queues && "songs" in queues ? queues.songs.length : 0;
  122. var queues = Queues.findOne({type:display});
  123. },
  124. queues: function() {
  125. var queues = Queues.find({}).fetch();
  126. return queues;
  127. },
  128. usersOnline: function(){
  129. Meteor.call("getUserNum", function(err, num){
  130. if(err){
  131. console.log(err);
  132. }
  133. Session.set("userNum", num);
  134. });
  135. return Session.get("userNum");
  136. },
  137. roomUserNum: function(){
  138. var type = this.type;
  139. var userNum = Rooms.findOne({type: type}).users;
  140. return userNum;
  141. },
  142. allUsers: function(){
  143. Meteor.call("getTotalUsers", function(err, num){
  144. Session.set("allUsers", num);
  145. })
  146. return Session.get("allUsers");
  147. },
  148. playlists: function() {
  149. var playlists = Playlists.find({}).fetch();
  150. playlists.map(function(playlist) {
  151. if (Rooms.find({type: playlist.type}).count() !== 1) {
  152. return;
  153. } else {
  154. playlist.display = Rooms.findOne({type: playlist.type}).display;
  155. return playlist;
  156. }
  157. });
  158. return playlists;
  159. },
  160. reportsCount: function(room) {
  161. room = room.toLowerCase();
  162. var reports = Reports.findOne({room:room});
  163. return reports && "report" in reports ? reports.report.length : 0;
  164. }
  165. });
  166. Template.admin.events({
  167. "click #croom_create": function() {
  168. Meteor.call("createRoom", $("#croom_display").val(), $("#croom_tag").val(), function (err, res) {
  169. if (err) {
  170. alert("Error " + err.error + ": " + err.reason);
  171. } else {
  172. window.location = "/" + $("#croom_tag").val();
  173. }
  174. });
  175. },
  176. "click a": function(e){
  177. var id = e.currentTarget.id;
  178. console.log(id.toLowerCase());
  179. Session.set("playlistToEdit", id);
  180. },
  181. "click #croom_create": function() {
  182. Meteor.call("createRoom", $("#croom_display").val(), $("#croom_tag").val(), $("#two").prop("checked"), function (err, res) {
  183. if (err) {
  184. alert("Error " + err.error + ": " + err.reason);
  185. } else {
  186. window.location = "/" + $("#croom_tag").val();
  187. }
  188. });
  189. },
  190. "click #rreset_confirm": function(){
  191. $('#confirmModal').modal('hide');
  192. Meteor.call("resetRating");
  193. }
  194. });
  195. // Alerts Template
  196. Template.alerts.helpers({
  197. alerts: function() {
  198. return Alerts.find({active: true});
  199. }
  200. });
  201. // AlertsDashboard Template
  202. Template.alertsDashboard.onCreated(function() {
  203. if (allAlertSub === undefined) {
  204. allAlertSub = Meteor.subscribe("allAlerts");
  205. }
  206. });
  207. Template.alertsDashboard.helpers({
  208. "activeAlerts": function() {
  209. return Alerts.find({active: true});
  210. },
  211. "inactiveAlerts": function() {
  212. return Alerts.find({active: false});
  213. }
  214. });
  215. Template.alertsDashboard.events({
  216. "click #calart-create": function() {
  217. Meteor.call("addAlert", $("#calert-description").val(), $("#calert-priority").val().toLowerCase(), function (err, res) {
  218. if (err) {
  219. alert("Error " + err.error + ": " + err.reason);
  220. } else {
  221. $("#calert-description").val("");
  222. }
  223. });
  224. },
  225. "click #ralert-button": function() {
  226. Meteor.call("removeAlerts");
  227. }
  228. });
  229. // Banned Template
  230. Template.banned.helpers({
  231. bannedAt: function() {
  232. if (Session.get("ban") !== undefined) {
  233. return Session.get("ban").bannedAt;
  234. }
  235. },
  236. bannedBy: function() {
  237. if (Session.get("ban") !== undefined) {
  238. return Session.get("ban").bannedBy;
  239. }
  240. },
  241. bannedUntil: function() {
  242. if (Session.get("ban") !== undefined) {
  243. return Session.get("ban").bannedUntil;
  244. }
  245. },
  246. bannedReason: function() {
  247. if (Session.get("ban") !== undefined) {
  248. return Session.get("ban").bannedReason;
  249. }
  250. }
  251. });
  252. Template.banned.onCreated(function() {
  253. if (rTimeInterval !== undefined) {
  254. Meteor.clearInterval(rTimeInterval)
  255. }
  256. rTimeInterval = Meteor.setInterval(function() {
  257. Session.set("time", new Date().getTime());
  258. }, 10000);
  259. Session.set("ban", Meteor.user().punishments.ban);
  260. });
  261. // Dashboard Template
  262. Template.dashboard.helpers({
  263. rooms: function() {
  264. return Rooms.find({});
  265. },
  266. currentSong: function() {
  267. var type = this.type;
  268. var room = Rooms.findOne({type: type});
  269. if (room !== undefined) {
  270. return room.currentSong;
  271. } else {
  272. return {};
  273. }
  274. },
  275. userNum: function(){
  276. var type = this.type;
  277. var userNum = Rooms.findOne({type: type}).users;
  278. return userNum;
  279. }
  280. });
  281. Template.dashboard.onCreated(function() {
  282. if (SCPlayer !== undefined) SCPlayer.stop();
  283. if (minterval !== undefined) {
  284. Meteor.clearInterval(minterval);
  285. }
  286. if (resizeSeekerbarInterval !== undefined) {
  287. Meteor.clearInterval(resizeSeekerbarInterval);
  288. resizeSeekerbarInterval = undefined;
  289. }
  290. if (StationSubscription !== undefined) {
  291. StationSubscription.stop();
  292. }
  293. Session.set("type", undefined);
  294. });
  295. // Header Template
  296. Template.header.helpers({
  297. userId: function() {
  298. return Meteor.userId();
  299. }
  300. });
  301. Template.header.events({
  302. "click .logout": function(e){
  303. e.preventDefault();
  304. Meteor.logout();
  305. if (hpSound !== undefined) {
  306. hpSound.stop();
  307. }
  308. },
  309. "click #profile": function(){
  310. window.location = "/u/" + Meteor.user().profile.username;
  311. }
  312. });
  313. // Login Template
  314. Template.login.onCreated(function() {
  315. Session.set("github", true);
  316. Accounts.onLoginFailure(function() {
  317. if (Session.get("github") === true) {
  318. var errAlert = $('<div style="margin-bottom: 0" class="alert alert-danger" role="alert"><strong>Oh Snap!</strong> Something went wrong when trying to log in with GitHub.</div>');
  319. $(".landing").before(errAlert);
  320. Meteor.setTimeout(function() {
  321. errAlert.fadeOut(5000, function() {
  322. errAlert.remove();
  323. });
  324. }, 10000);
  325. }
  326. });
  327. });
  328. Template.login.events({
  329. "submit form": function(e){
  330. e.preventDefault();
  331. Session.set("github", false);
  332. var username = e.target.loginUsername.value;
  333. var password = e.target.loginPassword.value;
  334. Meteor.loginWithPassword(username, password, function(err) {
  335. if (err) {
  336. var errAlert = $('<div style="margin-bottom: 0" class="alert alert-danger" role="alert"><strong>Oh Snap!</strong> ' + err.reason + '</div>');
  337. $(".landing").before(errAlert);
  338. Meteor.setTimeout(function() {
  339. errAlert.fadeOut(5000, function() {
  340. errAlert.remove();
  341. });
  342. }, 5000);
  343. } else {
  344. window.location.href = "/";
  345. }
  346. });
  347. },
  348. "click #github-login": function(){
  349. Meteor.loginWithGithub({loginStyle: "redirect"}, function(err, res) {
  350. console.log(err, res);
  351. });
  352. }
  353. });
  354. // Plalist Template
  355. Template.playlist.helpers({
  356. playlist_songs: function() {
  357. parts = location.href.split('/');
  358. id = parts.pop();
  359. type = id.toLowerCase();
  360. var data = Playlists.findOne({type: type});
  361. if (data !== undefined) {
  362. data.songs.map(function(song) {
  363. if (Session.get("currentSong") !== undefined && song.mid === Session.get("currentSong").mid) {
  364. song.current = true;
  365. } else {
  366. song.current = false;
  367. }
  368. return song;
  369. });
  370. return data.songs;
  371. } else {
  372. return [];
  373. }
  374. }
  375. });
  376. Template.playlist.events({
  377. "keyup #search-playlist": function(){
  378. if($("#search-playlist").val().length === 0){
  379. $(".pl-item").show();
  380. } else {
  381. $(".pl-item").hide();
  382. var input = $("#search-playlist").val().toLowerCase();
  383. $(".pl-item strong").each(function(i, el){
  384. if($(el).text().toLowerCase().indexOf(input) !== -1){
  385. $(el).parent(".pl-item").show();
  386. }
  387. })
  388. $(".pl-item #pl-artist").each(function(i, el){
  389. if($(el).text().toLowerCase().indexOf(input) !== -1){
  390. $(el).parent(".pl-item").show();
  391. }
  392. })
  393. }
  394. },
  395. "click #pl-item": function(){
  396. console.log($(this).text());
  397. }
  398. });
  399. // Profile Template
  400. Template.profile.events({
  401. //Edit real name
  402. "click #edit-name": function(){
  403. $("#name").hide();
  404. $("#name-div").show();
  405. $("#edit-name").hide();
  406. $("#cancel-edit").show();
  407. },
  408. "click #submit-name": function(){
  409. var user = Meteor.user();
  410. $("#name").show();
  411. $("#name-div").hide();
  412. $("#edit-name").show();
  413. $("#cancel-edit").hide();
  414. var realname = $("#input-name").val();
  415. var username = user.profile.username;
  416. $("#name").text("Name: " + realname);
  417. $("#input-name").val("")
  418. Meteor.call("updateRealName", realname);
  419. },
  420. "click #cancel-edit": function(){
  421. $("#name").show();
  422. $("#name-div").hide();
  423. $("#edit-name").show();
  424. $("#cancel-edit").hide();
  425. $("#input-name").val("");
  426. },
  427. //Edit username
  428. "click #edit-username": function(){
  429. $("#username").hide();
  430. $("#username-div").show();
  431. $("#edit-username").hide();
  432. $("#cancel-username").show();
  433. },
  434. "click #submit-username": function(){
  435. var user = Meteor.user()
  436. $("#username").show();
  437. $("#username-div").hide();
  438. $("#edit-username").show();
  439. $("#cancel-username").hide();
  440. var username = user.username;
  441. var newUserName = $("#input-username").val();
  442. $("#profile-name").text(newUserName)
  443. $("#username").text("Username: " + newUserName);
  444. $("#input-username").val("")
  445. Meteor.call("updateUserName", newUserName);
  446. window.location = "/u/" + newUserName;
  447. },
  448. "click #cancel-username": function(){
  449. $("#username").show();
  450. $("#username-div").hide();
  451. $("#edit-username").show();
  452. $("#cancel-username").hide();
  453. $("#input-username").val("");
  454. },
  455. // Admins only Edit Rank
  456. "click #edit-rank": function() {
  457. $("#rank").hide();
  458. $("#rank-div").show();
  459. $("#edit-rank").hide();
  460. $("#cancel-rank").show();
  461. },
  462. "click #submit-rank": function() {
  463. $("#rank").show();
  464. $("#rank-div").hide();
  465. $("#edit-rank").show();
  466. $("#cancel-rank").hide();
  467. var newRank = $("#select-rank option:selected").val();
  468. var username = Session.get("username");
  469. console.log(username, newRank);
  470. },
  471. "click #cancel-rank": function() {
  472. $("#rank").show();
  473. $("#rank-div").hide();
  474. $("#edit-rank").show();
  475. $("#cancel-rank").hide();
  476. }
  477. });
  478. Template.profile.helpers({
  479. "real_name": function(){
  480. return Session.get("real_name");
  481. },
  482. "username": function() {
  483. return Session.get("username")
  484. },
  485. "first_joined": function() {
  486. return moment(Session.get("first_joined")).format("DD/MM/YYYY HH:mm:ss");
  487. },
  488. "rank": function() {
  489. return Session.get("rank");
  490. },
  491. loaded: function() {
  492. return Session.get("loaded");
  493. },
  494. likedSongs: function(){
  495. var likedArr = [];
  496. Session.get("liked").forEach(function(mid){
  497. Rooms.find().forEach(function(room){
  498. Playlists.find({type: room.type}).forEach(function(pl){
  499. for(var i in pl.songs){
  500. if(pl.songs[i].mid === mid){
  501. likedArr.push({title: pl.songs[i].title, artist: pl.songs[i].artist, room: room.display});
  502. }
  503. }
  504. });
  505. })
  506. });
  507. return likedArr;
  508. },
  509. dislikedSongs: function(){
  510. var dislikedArr = [];
  511. Session.get("disliked").forEach(function(mid){
  512. Rooms.find().forEach(function(room){
  513. Playlists.find({type: room.type}).forEach(function(pl){
  514. for(var i in pl.songs){
  515. if(pl.songs[i].mid === mid){
  516. dislikedArr.push({title: pl.songs[i].title, artist: pl.songs[i].artist, room: room.display});
  517. }
  518. }
  519. });
  520. })
  521. });
  522. return dislikedArr;
  523. },
  524. isUser: function(){
  525. var parts = Router.current().url.split('/');
  526. var username = parts.pop();
  527. if(username === Meteor.user().profile.username){
  528. return true;
  529. }
  530. }
  531. });
  532. Template.profile.onCreated(function() {
  533. var parts = Router.current().url.split('/');
  534. var username = parts.pop();
  535. Session.set("loaded", false);
  536. Meteor.subscribe("userProfiles", username.toLowerCase(), function() {
  537. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() === 0) {
  538. window.location = "/";
  539. } else {
  540. var data = Meteor.users.findOne({"profile.usernameL": username.toLowerCase()});
  541. Session.set("real_name", data.profile.realname);
  542. Session.set("username", data.profile.username);
  543. Session.set("first_joined", data.createdAt);
  544. Session.set("rank", data.profile.rank);
  545. Session.set("liked", data.profile.liked);
  546. Session.set("disliked", data.profile.disliked);
  547. Session.set("loaded", true);
  548. }
  549. });
  550. });
  551. // Queues Template
  552. Template.queues.helpers({
  553. queues: function() {
  554. var queues = Queues.find({}).fetch();
  555. queues.map(function(queue) {
  556. if (Rooms.find({type: queue.type}).count() !== 1) {
  557. return;
  558. } else {
  559. queue.display = Rooms.findOne({type: queue.type}).display;
  560. return queue;
  561. }
  562. });
  563. return queues;
  564. }
  565. });
  566. Template.queues.events({
  567. "click .preview-button": function(e){
  568. Session.set("song", this);
  569. },
  570. "click #previewImageButton": function() {
  571. $("#preview-image").attr("src", Session.get("song").img);
  572. },
  573. "click .edit-queue-button": function(e){
  574. Session.set("song", this);
  575. Session.set("genre", $(e.target).data("genre"));
  576. Session.set("type", "queue");
  577. $("#type").val(this.type);
  578. $("#mid").val(this.mid);
  579. $("#artist").val(this.artist);
  580. $("#title").val(this.title);
  581. $("#img").val(this.img);
  582. $("#id").val(this.id);
  583. $("#likes").val(this.likes);
  584. $("#dislikes").val(this.dislikes);
  585. $("#duration").val(this.duration);
  586. $("#skip-duration").val(this.skipDuration);
  587. },
  588. "click .add-song-button": function(e){
  589. var genre = $(e.target).data("genre") || $(e.target).parent().data("genre");
  590. Meteor.call("addSongToPlaylist", genre, this);
  591. },
  592. "click .deny-song-button": function(e){
  593. var genre = $(e.target).data("genre") || $(e.target).parent().data("genre");
  594. Meteor.call("removeSongFromQueue", genre, this.mid);
  595. },
  596. "click #play": function() {
  597. $("#play").attr("disabled", true);
  598. $("#stop").attr("disabled", false);
  599. var song = Session.get("song");
  600. var id = song.id;
  601. var type = song.type;
  602. var volume = localStorage.getItem("volume") || 20;
  603. if (type === "YouTube") {
  604. if (YTPlayer === undefined) {
  605. YTPlayer = new YT.Player("previewPlayer", {
  606. height: 540,
  607. width: 568,
  608. videoId: id,
  609. playerVars: {autoplay: 1, controls: 0, iv_load_policy: 3, showinfo: 0},
  610. events: {
  611. 'onReady': function(event) {
  612. event.target.seekTo(Number(song.skipDuration));
  613. event.target.playVideo();
  614. event.target.setVolume(volume);
  615. },
  616. 'onStateChange': function(event){
  617. if (event.data == YT.PlayerState.PAUSED) {
  618. event.target.playVideo();
  619. }
  620. if (event.data == YT.PlayerState.PLAYING) {
  621. $("#play").attr("disabled", true);
  622. $("#stop").attr("disabled", false);
  623. } else {
  624. $("#play").attr("disabled", false);
  625. $("#stop").attr("disabled", true);
  626. }
  627. }
  628. }
  629. });
  630. } else {
  631. YTPlayer.loadVideoById(id);
  632. YTPlayer.seekTo(Number(song.skipDuration));
  633. }
  634. $("#previewPlayer").show();
  635. } else if (type === "SoundCloud") {
  636. SC.stream("/tracks/" + song.id, function(sound) {
  637. SCPlayer = sound;
  638. sound.setVolume(volume / 100);
  639. sound.play();
  640. });
  641. }
  642. if (previewEndSongTimeout !== undefined) {
  643. Meteor.clearTimeout(previewEndSongTimeout);
  644. }
  645. previewEndSongTimeout = Meteor.setTimeout(function() {
  646. if (YTPlayer !== undefined) {
  647. YTPlayer.stopVideo();
  648. }
  649. if (SCPlayer !== undefined) {
  650. SCPlayer.stop();
  651. }
  652. $("#play").attr("disabled", false);
  653. $("#stop").attr("disabled", true);
  654. $("#previewPlayer").hide();
  655. }, song.duration * 1000);
  656. },
  657. "click #stop": function() {
  658. $("#play").attr("disabled", false);
  659. $("#stop").attr("disabled", true);
  660. if (previewEndSongTimeout !== undefined) {
  661. Meteor.clearTimeout(previewEndSongTimeout);
  662. }
  663. if (YTPlayer !== undefined) {
  664. YTPlayer.stopVideo();
  665. }
  666. if (SCPlayer !== undefined) {
  667. SCPlayer.stop();
  668. }
  669. },
  670. "click #forward": function() {
  671. var error = false;
  672. if (YTPlayer !== undefined) {
  673. var duration = Number(Session.get("song").duration) | 0;
  674. var skipDuration = Number(Session.get("song").skipDuration) | 0;
  675. if (YTPlayer.getDuration() < duration + skipDuration) {
  676. alert("The duration of the YouTube video is smaller than the duration.");
  677. error = true;
  678. } else {
  679. YTPlayer.seekTo(skipDuration + duration - 10);
  680. }
  681. }
  682. if (SCPlayer !== undefined) {
  683. SCPlayer.seekTo((skipDuration + duration - 10) * 1000);
  684. }
  685. if (!error) {
  686. if (previewEndSongTimeout !== undefined) {
  687. Meteor.clearTimeout(previewEndSongTimeout);
  688. }
  689. previewEndSongTimeout = Meteor.setTimeout(function() {
  690. if (YTPlayer !== undefined) {
  691. YTPlayer.stopVideo();
  692. }
  693. if (SCPlayer !== undefined) {
  694. SCPlayer.stop();
  695. }
  696. $("#play").attr("disabled", false);
  697. $("#stop").attr("disabled", true);
  698. $("#previewPlayer").hide();
  699. }, 10000);
  700. }
  701. },
  702. "click #get-spotify-info": function() {
  703. var search = $("#title").val();
  704. var artistName = $("#artist").val();
  705. getSpotifyInfo(search, function(data) {
  706. for(var i in data){
  707. for(var j in data[i].items){
  708. if(search.indexOf(data[i].items[j].name) !== -1 && artistName.indexOf(data[i].items[j].artists[0].name) !== -1){
  709. $("#img").val(data[i].items[j].album.images[1].url);
  710. $("#duration").val(data[i].items[j].duration_ms / 1000);
  711. return;
  712. }
  713. }
  714. }
  715. }, artistName);
  716. },
  717. "click #save-song-button": function() {
  718. var newSong = {};
  719. newSong.id = $("#id").val();
  720. newSong.likes = Number($("#likes").val());
  721. newSong.dislikes = Number($("#dislikes").val());
  722. newSong.title = $("#title").val();
  723. newSong.artist = $("#artist").val();
  724. newSong.img = $("#img").val();
  725. newSong.type = $("#type").val();
  726. newSong.duration = Number($("#duration").val());
  727. newSong.skipDuration = $("#skip-duration").val();
  728. if(newSong.skipDuration === undefined){
  729. newSong.skipDuration = 0;
  730. };
  731. if (Session.get("type") === "playlist") {
  732. Meteor.call("updatePlaylistSong", Session.get("genre"), Session.get("song"), newSong, function() {
  733. $('#editModal').modal('hide');
  734. });
  735. } else {
  736. Meteor.call("updateQueueSong", Session.get("genre"), Session.get("song"), newSong, function() {
  737. $('#editModal').modal('hide');
  738. });
  739. }
  740. }
  741. });
  742. Template.queues.onCreated(function() {
  743. var tag = document.createElement("script");
  744. tag.src = "https://www.youtube.com/iframe_api";
  745. var firstScriptTag = document.getElementsByTagName('script')[0];
  746. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  747. YTPlayer = undefined;
  748. SCPlayer = undefined;
  749. });
  750. Template.queues.onRendered(function() {
  751. $("#previewModal").on("hidden.bs.modal", function() {
  752. if (previewEndSongTimeout !== undefined) {
  753. Meteor.clearTimeout(previewEndSongTimeout);
  754. }
  755. $("#play").attr("disabled", false);
  756. $("#stop").attr("disabled", true);
  757. if (YTPlayer !== undefined) {
  758. $("#previewPlayer").hide();
  759. YTPlayer.seekTo(0);
  760. YTPlayer.stopVideo();
  761. }
  762. if (SCPlayer !== undefined) {
  763. SCPlayer.stop();
  764. }
  765. });
  766. $(document).ready(function() {
  767. function makeSlider(){
  768. var slider = $("#volume-slider").slider();
  769. var volume = localStorage.getItem("volume") || 20;
  770. $("#volume-slider").slider("setValue", volume);
  771. if (slider.length === 0) {
  772. Meteor.setTimeout(function() {
  773. makeSlider();
  774. }, 500);
  775. } else {
  776. slider.on("slide", function(val) {
  777. localStorage.setItem("volume", val.value);
  778. if (YTPlayer !== undefined) {
  779. YTPlayer.setVolume(val.value);
  780. } else if (SCPlayer !== undefined) {
  781. var volume = val.value / 100;
  782. SCPlayer.setVolume(volume);
  783. }
  784. });
  785. }
  786. }
  787. makeSlider();
  788. });
  789. });
  790. // Register Template
  791. Template.register.onCreated(function() {
  792. Accounts.onLoginFailure(function() {
  793. var errAlert = $('<div style="margin-bottom: 0" class="alert alert-danger" role="alert"><strong>Oh Snap!</strong> Something went wrong when trying to register with GitHub. Maybe an account with that username already exists?</div>');
  794. $(".landing").before(errAlert);
  795. Meteor.setTimeout(function() {
  796. errAlert.fadeOut(5000, function() {
  797. errAlert.remove();
  798. });
  799. }, 10000);
  800. });
  801. });
  802. Template.register.events({
  803. "submit form": function(e){
  804. e.preventDefault();
  805. var username = e.target.registerUsername.value;
  806. var email = e.target.registerEmail.value;
  807. var password = e.target.registerPassword.value;
  808. var captchaData = grecaptcha.getResponse();
  809. Meteor.call("createUserMethod", {username: username, email: email, password: password}, captchaData, function(err, res) {
  810. grecaptcha.reset();
  811. if (err) {
  812. console.log(err);
  813. var errAlert = $('<div style="margin-bottom: 0" class="alert alert-danger" role="alert"><strong>Oh Snap!</strong> ' + err.reason + '</div>');
  814. $(".landing").before(errAlert);
  815. Meteor.setTimeout(function() {
  816. errAlert.fadeOut(5000, function() {
  817. errAlert.remove();
  818. });
  819. }, 5000);
  820. } else {
  821. Meteor.loginWithPassword(username, password);
  822. Accounts.onLogin(function(){
  823. window.location.href = "/";
  824. })
  825. }
  826. });
  827. },
  828. "click #github-login": function(){
  829. Meteor.loginWithGithub({loginStyle: "redirect"}, function(err, res) {
  830. console.log(err, res);
  831. });
  832. }
  833. });
  834. // Room Template
  835. Template.room.events({
  836. "click #youtube-playlist-button": function() {
  837. if (!Session.get("importingPlaylist")) {
  838. var playlist_link = $("#youtube-playlist-input").val();
  839. var playlist_id = gup("list", playlist_link);
  840. var ytImportQueue = [];
  841. var totalVideos = 0;
  842. var videosInvalid = 0;
  843. var videosInQueue = 0;
  844. var videosInPlaylist = 0;
  845. var ranOnce = false;
  846. Session.set("importingPlaylist", true);
  847. $("#youtube-playlist-button").attr("disabled", "");
  848. $("#youtube-playlist-button").addClass("disabled");
  849. $("#youtube-playlist-input").attr("disabled", "");
  850. $("#youtube-playlist-input").addClass("disabled");
  851. $("#playlist-import-queue").empty();
  852. $("#playlist-import-queue").hide();
  853. $("#add-youtube-playlist").addClass("hidden-2");
  854. $("#import-progress").attr("aria-valuenow", 0);
  855. $("#import-progress").css({width: "0%"});
  856. $("#import-progress").text("0%");
  857. function makeAPICall(playlist_id, nextPageToken){
  858. if (nextPageToken !== undefined) {
  859. nextPageToken = "&pageToken=" + nextPageToken;
  860. } else {
  861. nextPageToken = "";
  862. }
  863. $.ajax({
  864. type: "GET",
  865. url: "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=" + playlist_id + nextPageToken + "&key=AIzaSyAgBdacEWrHCHVPPM4k-AFM7uXg-Q__YXY",
  866. applicationType: "application/json",
  867. contentType: "json",
  868. success: function(data){
  869. if (!ranOnce) {
  870. ranOnce = true;
  871. totalVideos = data.pageInfo.totalResults;
  872. }
  873. var nextToken = data.nextPageToken;
  874. for(var i in data.items){
  875. var item = data.items[i];
  876. if (item.snippet.thumbnails !== undefined) {
  877. var genre = Session.get("type");
  878. if (Playlists.find({type: genre, "songs.id": item.snippet.resourceId.videoId}, {songs: {$elemMatch: {id: item.snippet.resourceId.videoId}}}).count() !== 0) {
  879. videosInPlaylist++;
  880. } else if (Queues.find({type: genre, "songs.id": item.snippet.resourceId.videoId}, {songs: {$elemMatch: {id: item.snippet.resourceId.videoId}}}).count() !== 0) {
  881. videosInQueue++;
  882. } else {
  883. $("#playlist-import-queue").append(
  884. "<div class='youtube-import-queue-item'>" +
  885. "<img src='" + item.snippet.thumbnails.medium.url + "' class='song-result-thumbnail'/>" +
  886. "<div>" +
  887. "<span class='song-result-title'>" + item.snippet.title + "</span>" +
  888. "<span class='song-result-channel'>" + item.snippet.channelTitle + "</span>" +
  889. "</div>" +
  890. "<i class='fa fa-times remove-import-song'></i>" +
  891. "</div>"
  892. );
  893. var percentage = ytImportQueue.length / (totalVideos - videosInvalid) * 100;
  894. $("#import-progress").attr("aria-valuenow", percentage.toFixed(2));
  895. $("#import-progress").css({width: percentage + "%"});
  896. $("#import-progress").text(percentage.toFixed(1) + "%");
  897. ytImportQueue.push({title: item.snippet.title, id: item.snippet.resourceId.videoId});
  898. }
  899. } else {
  900. videosInvalid++;
  901. }
  902. }
  903. if (nextToken !== undefined) {
  904. makeAPICall(playlist_id, nextToken);
  905. } else {
  906. $("#playlist-import-queue > div > i").click(function(){
  907. var title = $(this).parent().find("div > .song-result-title").text();
  908. for(var i in ytImportQueue){
  909. if(ytImportQueue[i].title === title){
  910. ytImportQueue.splice(i, 1);
  911. }
  912. }
  913. $(this).parent().remove();
  914. });
  915. Session.set("importingPlaylist", false);
  916. $("#import-progress").attr("aria-valuenow", 100);
  917. $("#import-progress").css({width: "100%"});
  918. $("#import-progress").text("100%");
  919. $("#youtube-playlist-button").removeAttr("disabled");
  920. $("#youtube-playlist-button").removeClass("disabled");
  921. $("#youtube-playlist-input").removeAttr("disabled");
  922. $("#youtube-playlist-input").removeClass("disabled");
  923. $("#playlist-import-queue").show();
  924. $("#add-youtube-playlist").removeClass("hidden-2");
  925. Session.set("YTImportQueue", ytImportQueue);
  926. }
  927. }
  928. })
  929. }
  930. makeAPICall(playlist_id);
  931. }
  932. },
  933. "click #add-youtube-playlist": function() {
  934. var YTImportQueue = Session.get("YTImportQueue");
  935. $("#youtube-playlist-button").attr("disabled", "");
  936. $("#youtube-playlist-button").addClass("disabled");
  937. $("#youtube-playlist-input").attr("disabled", "");
  938. $("#youtube-playlist-input").addClass("disabled");
  939. $("#import-progress").attr("aria-valuenow", 0);
  940. $("#import-progress").css({width: "0%"});
  941. $("#import-progress").text("0%");
  942. var failed = 0;
  943. var success = 0;
  944. var processed = 0;
  945. var total = YTImportQueue.length;
  946. YTImportQueue.forEach(function(song) {
  947. var songData = {type: "YouTube", id: song.id, title: song.title, artist: "", img: ""};
  948. Meteor.call("addSongToQueue", Session.get("type"), songData, function(err, res) {
  949. if (err) {
  950. failed++;
  951. } else {
  952. success++;
  953. }
  954. processed++;
  955. var percentage = processed / total * 100;
  956. $("#import-progress").attr("aria-valuenow", percentage.toFixed(2));
  957. $("#import-progress").css({width: percentage + "%"});
  958. $("#import-progress").text(percentage.toFixed(1) + "%");
  959. });
  960. });
  961. },
  962. "click #chat-tab": function() {
  963. $("#chat-tab").removeClass("unread-messages");
  964. },
  965. "click #global-chat-tab": function() {
  966. $("#global-chat-tab").removeClass("unread-messages");
  967. },
  968. "click #sync": function() {
  969. if (Session.get("currentSong") !== undefined) {
  970. var room = Rooms.findOne({type: Session.get("type")});
  971. if (room !== undefined) {
  972. var timeIn = Date.now() - Session.get("currentSong").started - room.timePaused;
  973. var skipDuration = Number(Session.get("currentSong").skipDuration) | 0;
  974. if (YTPlayer !== undefined) {
  975. YTPlayer.seekTo(skipDuration + timeIn / 1000);
  976. }
  977. else if (SCPlayer !== undefined) {
  978. SCPlayer.seekTo(skipDuration * 1000 + timeIn);
  979. }
  980. }
  981. }
  982. },
  983. "click #lock": function() {
  984. Meteor.call("lockRoom", Session.get("type"));
  985. },
  986. "click #unlock": function() {
  987. Meteor.call("unlockRoom", Session.get("type"));
  988. },
  989. "click #chat-tab": function(e) {
  990. Meteor.setTimeout(function() {
  991. $("#chat-ul").scrollTop(100000);
  992. }, 1);
  993. },
  994. "click #global-chat-tab": function(e) {
  995. Meteor.setTimeout(function() {
  996. $("#global-chat-ul").scrollTop(100000);
  997. }, 1);
  998. },
  999. "click #submit": function() {
  1000. sendMessage();
  1001. Meteor.setTimeout(function(){
  1002. $("#chat-ul").scrollTop(100000);
  1003. }, 1000)
  1004. },
  1005. "click #global-submit": function() {
  1006. sendMessageGlobal();
  1007. Meteor.setTimeout(function(){
  1008. $("#global-chat-ul").scrollTop(100000);
  1009. }, 1000)
  1010. },
  1011. "keyup #chat-input": function(e) {
  1012. if (e.type === "keyup" && e.which === 13) {
  1013. e.preventDefault();
  1014. if (!$('#chat-input').data('dropdownshown')) {
  1015. sendMessage();
  1016. Meteor.setTimeout(function(){
  1017. $("#chat-ul").scrollTop(100000);
  1018. }, 1000)
  1019. }
  1020. }
  1021. },
  1022. "keyup #global-chat-input": function(e) {
  1023. if (e.type === "keyup" && e.which === 13) {
  1024. e.preventDefault();
  1025. if (!$('#global-chat-input').data('dropdownshown')) {
  1026. sendMessageGlobal();
  1027. Meteor.setTimeout(function(){
  1028. $("#global-chat-ul").scrollTop(100000);
  1029. }, 1000)
  1030. }
  1031. }
  1032. },
  1033. "click #like": function(e) {
  1034. $("#like").blur();
  1035. Meteor.call("likeSong", Session.get("currentSong").mid);
  1036. },
  1037. "click #dislike": function(e) {
  1038. $("#dislike").blur();
  1039. Meteor.call("dislikeSong", Session.get("currentSong").mid);
  1040. },
  1041. "click #vote-skip": function(){
  1042. Meteor.call("voteSkip", type, function(err, res) {
  1043. $("#vote-skip").attr("disabled", true);
  1044. });
  1045. },
  1046. "click #report-prev": function(e) {
  1047. if (Session.get("previousSong") !== undefined) {
  1048. Session.set("reportPrevious", true);
  1049. $("#report-prev").prop("disabled", true);
  1050. $("#report-curr").prop("disabled", false);
  1051. }
  1052. },
  1053. "click #report-curr": function(e) {
  1054. Session.set("reportPrevious", false);
  1055. $("#report-prev").prop("disabled", false);
  1056. $("#report-curr").prop("disabled", true);
  1057. },
  1058. "click #report-modal": function() {
  1059. Session.set("currentSongR", Session.get("currentSong"));
  1060. Session.set("previousSongR", Session.get("previousSong"));
  1061. },
  1062. "click #add-song-button": function(e){
  1063. e.preventDefault();
  1064. parts = location.href.split('/');
  1065. var roomType = parts.pop();
  1066. var genre = roomType.toLowerCase();
  1067. var type = $("#type").val();
  1068. id = $("#id").val();
  1069. var title = $("#title").val();
  1070. var artist = $("#artist").val();
  1071. var img = $("#img").val();
  1072. var songData = {type: type, id: id, title: title, artist: artist, img: img};
  1073. if(Playlists.find({type: genre, "songs.id": songData.id}, {songs: {$elemMatch: {id: songData.id}}}).count() !== 0) {
  1074. $("<div class='alert alert-danger alert-dismissible' role='alert' style='margin-bottom: 0'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'><i class='fa fa-times'></i></span></button><strong>Song not added.</strong> This song is already in the playlist.</div>").prependTo($(".landing")).delay(7000).fadeOut(1000, function() { $(this).remove(); });
  1075. } else if(Queues.find({type: genre, "songs.id": songData.id}, {songs: {$elemMatch: {id: songData.id}}}).count() !== 0) {
  1076. $("<div class='alert alert-danger alert-dismissible' role='alert' style='margin-bottom: 0'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'><i class='fa fa-times'></i></span></button><strong>Song not added.</strong> This song has already been requested.</div>").prependTo($(".landing")).delay(7000).fadeOut(1000, function() { $(this).remove(); });
  1077. } else{
  1078. Meteor.call("addSongToQueue", genre, songData, function(err, res) {
  1079. console.log(err, res);
  1080. if (err) {
  1081. $("<div class='alert alert-danger alert-dismissible' role='alert' style='margin-bottom: 0'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'><i class='fa fa-times'></i></span></button><strong>Song not added.</strong> Something went wrong.</div>").prependTo($(".landing")).delay(7000).fadeOut(1000, function() { $(this).remove(); });
  1082. } else {
  1083. $("<div class='alert alert-success alert-dismissible' role='alert' style='margin-bottom: 0'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'><i class='fa fa-times'></i></span></button><strong>Song added.</strong> Your song has been added to the queue.</div>").prependTo($(".landing")).delay(7000).fadeOut(1000, function() { $(this).remove(); });
  1084. }
  1085. });
  1086. }
  1087. $("#close-modal-a").click();
  1088. },
  1089. "click #toggle-video": function(e){
  1090. e.preventDefault();
  1091. if (Session.get("mediaHidden")) {
  1092. $("#media-container").removeClass("hidden");
  1093. $("#toggle-video").text("Hide video");
  1094. Session.set("mediaHidden", false);
  1095. } else {
  1096. $("#media-container").addClass("hidden");
  1097. $("#toggle-video").text("Show video");
  1098. Session.set("mediaHidden", true);
  1099. }
  1100. },
  1101. "click #return": function(e){
  1102. $("#add-info").hide();
  1103. $("#search-info").show();
  1104. },
  1105. "click #search-song": function(){
  1106. var songs = [];
  1107. $("#song-results").empty();
  1108. var search_type = $("#search_type").val();
  1109. if (search_type === "YouTube") {
  1110. $.ajax({
  1111. type: "GET",
  1112. url: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + $("#song-input").val() + "&key=AIzaSyAgBdacEWrHCHVPPM4k-AFM7uXg-Q__YXY",
  1113. applicationType: "application/json",
  1114. contentType: "json",
  1115. success: function(data){
  1116. for(var i in data.items){
  1117. var item = data.items[i];
  1118. $("#song-results").append(
  1119. "<div>" +
  1120. "<img src='" + item.snippet.thumbnails.medium.url + "' class='song-result-thumbnail'/>" +
  1121. "<div>" +
  1122. "<span class='song-result-title'>" + item.snippet.title + "</span>" +
  1123. "<span class='song-result-channel'>" + item.snippet.channelTitle + "</span>" +
  1124. "</div>" +
  1125. "</div>"
  1126. );
  1127. songs.push({title: item.snippet.title, id: item.id.videoId});
  1128. }
  1129. $("#song-results > div").click(function(){
  1130. $("#search-info").hide();
  1131. $("#add-info").show();
  1132. var title = $(this).find("div > .song-result-title").text();
  1133. for(var i in songs){
  1134. if(songs[i].title === title){
  1135. var songObj = {
  1136. id: songs[i].id,
  1137. title: songs[i].title,
  1138. type: "youtube"
  1139. };
  1140. $("#title").val(songObj.title);
  1141. $("#artist").val("");
  1142. $("#id").val(songObj.id);
  1143. $("#type").val("YouTube");
  1144. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  1145. if (data.tracks.items.length > 0) {
  1146. $("#title").val(data.tracks.items[0].name);
  1147. var artists = [];
  1148. $("#img").val(data.tracks.items[0].album.images[1].url);
  1149. data.tracks.items[0].artists.forEach(function(artist) {
  1150. artists.push(artist.name);
  1151. });
  1152. $("#artist").val(artists.join(", "));
  1153. }
  1154. });
  1155. }
  1156. }
  1157. })
  1158. }
  1159. })
  1160. } else if (search_type === "SoundCloud") {
  1161. SC.get('/tracks', { q: $("#song-input").val()}, function(tracks) {
  1162. for(var i in tracks){
  1163. $("#song-results").append("<p>" + tracks[i].title + "</p>")
  1164. songsArr.push({title: tracks[i].title, id: tracks[i].id, duration: tracks[i].duration / 1000});
  1165. }
  1166. $("#song-results p").click(function(){
  1167. $("#search-info").hide();
  1168. $("#add-info").show();
  1169. var title = $(this).text();
  1170. for(var i in songsArr){
  1171. if(songsArr[i].title === title){
  1172. var id = songsArr[i].id;
  1173. var duration = songsArr[i].duration;
  1174. var songObj = {
  1175. title: songsArr[i].title,
  1176. id: id,
  1177. duration: duration,
  1178. type: "soundcloud"
  1179. }
  1180. $("#title").val(songObj.title);
  1181. // Set ID field
  1182. $("#id").val(songObj.id);
  1183. $("#type").val("SoundCloud");
  1184. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  1185. if (data.tracks.items.length > 0) {
  1186. $("#title").val(data.tracks.items[0].name);
  1187. var artists = [];
  1188. data.tracks.items[0].artists.forEach(function(artist) {
  1189. artists.push(artist.name);
  1190. });
  1191. $("#artist").val(artists.join(", "));
  1192. }
  1193. // Set title field again if possible
  1194. // Set artist if possible
  1195. });
  1196. }
  1197. }
  1198. })
  1199. });
  1200. }
  1201. },
  1202. "click #volume-icon": function(){
  1203. var volume = 0;
  1204. var slider = $("#volume-slider").slider();
  1205. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off")
  1206. if (YTPlayer !== undefined) {
  1207. YTPlayer.setVolume(volume);
  1208. localStorage.setItem("volume", volume);
  1209. $("#volume-slider").slider("setValue", volume);
  1210. } else if (SCPlayer !== undefined) {
  1211. SCPlayer.setVolume(volume);
  1212. localStorage.setItem("volume", volume);
  1213. $("#volume-slider").slider("setValue", volume);
  1214. }
  1215. },
  1216. "click #play": function() {
  1217. Meteor.call("resumeRoom", type);
  1218. },
  1219. "click #pause": function() {
  1220. Meteor.call("pauseRoom", type);
  1221. },
  1222. "click #skip": function() {
  1223. Meteor.call("skipSong", type);
  1224. },
  1225. "click #shuffle": function() {
  1226. Meteor.call("shufflePlaylist", type);
  1227. },
  1228. "change input": function(e) {
  1229. if (e.target && e.target.id) {
  1230. var partsOfId = e.target.id.split("-");
  1231. partsOfId[1] = partsOfId[1].charAt(0).toUpperCase() + partsOfId[1].slice(1);
  1232. var camelCase = partsOfId.join("");
  1233. Session.set(camelCase, e.target.checked);
  1234. }
  1235. },
  1236. "click #report-song-button": function() {
  1237. var room = Session.get("type");
  1238. var reportData = {};
  1239. reportData.song = Session.get("currentSong").mid;
  1240. reportData.type = [];
  1241. reportData.reason = [];
  1242. $(".report-layer-1 > .checkbox input:checked").each(function(){
  1243. reportData.type.push(this.id);
  1244. if (this.id == "report-other") {
  1245. var otherText = $(".other-textarea").val();
  1246. }
  1247. });
  1248. $(".report-layer-2 input:checked").each(function(){
  1249. reportData.reason.push(this.id);
  1250. });
  1251. console.log(reportData);
  1252. Meteor.call("submitReport", room, reportData, Session.get("id"), function() {
  1253. $("#close-modal-r").click();
  1254. });
  1255. },
  1256. "change #si_or_pl": function(){
  1257. if($("#select_playlist").is(':selected')){
  1258. $("#search-info").hide();
  1259. $("#playlist-import").show();
  1260. }
  1261. if($("#select_single").is(':selected')){
  1262. $("#search-info").show();
  1263. $("#playlist-import").hide();
  1264. }
  1265. },
  1266. "click #close-modal-a": function(){
  1267. $("#select_single").attr("selected", true);
  1268. $("#search-info").show();
  1269. $("#playlist-import").hide();
  1270. }
  1271. });
  1272. Template.room.onRendered(function() {
  1273. if (rTimeInterval !== undefined) {
  1274. Meteor.clearInterval(rTimeInterval)
  1275. }
  1276. rTimeInterval = Meteor.setInterval(function() {
  1277. Session.set("time", new Date().getTime());
  1278. }, 10000);
  1279. $(document).ready(function() {
  1280. function makeSlider(){
  1281. var slider = $("#volume-slider").slider();
  1282. var volume = Number(localStorage.getItem("volume"));
  1283. $("#volume-slider").slider("setValue", volume);
  1284. if (slider.length === 0) {
  1285. Meteor.setTimeout(function() {
  1286. makeSlider();
  1287. }, 500);
  1288. } else {
  1289. if (volume === 0) {
  1290. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off")
  1291. } else {
  1292. $("#volume-icon").removeClass("fa-volume-off").addClass("fa-volume-down")
  1293. }
  1294. slider.on("slide", function(val) {
  1295. if (val.value === 0) {
  1296. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off")
  1297. } else {
  1298. $("#volume-icon").removeClass("fa-volume-off").addClass("fa-volume-down")
  1299. }
  1300. if (YTPlayer !== undefined) {
  1301. YTPlayer.setVolume(val.value);
  1302. localStorage.setItem("volume", val.value);
  1303. } else if (SCPlayer !== undefined) {
  1304. //SCPlayer
  1305. var volume = val.value / 100;
  1306. SCPlayer.setVolume(volume);
  1307. localStorage.setItem("volume", val.value);
  1308. }
  1309. });
  1310. }
  1311. }
  1312. makeSlider();
  1313. });
  1314. });
  1315. Template.room.helpers({
  1316. singleVideo: function() {
  1317. return true;
  1318. },
  1319. chat: function() {
  1320. Meteor.setTimeout(function() {
  1321. var elem = document.getElementById('chat');
  1322. if (elem !== undefined && elem !== null) {
  1323. elem.scrollTop = elem.scrollHeight;
  1324. }
  1325. }, 100);
  1326. return Chat.find({type: Session.get("type")}, {sort: {time: -1}, limit: 50 }).fetch().reverse();
  1327. },
  1328. globalChat: function() {
  1329. Meteor.setTimeout(function() {
  1330. var elem = document.getElementById('global-chat');
  1331. if (elem !== undefined && elem !== null) {
  1332. elem.scrollTop = elem.scrollHeight;
  1333. }
  1334. }, 100);
  1335. return Chat.find({type: "global"}, {sort: {time: -1}, limit: 50 }).fetch().reverse();
  1336. },
  1337. likes: function() {
  1338. var playlist = Playlists.findOne({type: Session.get("type")});
  1339. var likes = 0;
  1340. playlist.songs.forEach(function(song) {
  1341. if (Session.get("currentSong") && song.mid === Session.get("currentSong").mid) {
  1342. likes = song.likes;
  1343. return;
  1344. }
  1345. });
  1346. return likes;
  1347. },
  1348. dislikes: function() {
  1349. var playlist = Playlists.findOne({type: Session.get("type")});
  1350. var dislikes = 0;
  1351. playlist.songs.forEach(function(song) {
  1352. if (Session.get("currentSong") && song.mid === Session.get("currentSong").mid) {
  1353. dislikes = song.dislikes;
  1354. return;
  1355. }
  1356. });
  1357. return dislikes;
  1358. },
  1359. liked: function() {
  1360. if (Meteor.userId()) {
  1361. var currentSong = Session.get("currentSong");
  1362. if (currentSong && Meteor.user().profile.liked.indexOf(currentSong.mid) !== -1) {
  1363. return "active";
  1364. } else {
  1365. return "";
  1366. }
  1367. } else {
  1368. "";
  1369. }
  1370. },
  1371. disliked: function() {
  1372. if (Meteor.userId()) {
  1373. var currentSong = Session.get("currentSong");
  1374. if (currentSong && Meteor.user().profile.disliked.indexOf(currentSong.mid) !== -1) {
  1375. return "active";
  1376. } else {
  1377. return "";
  1378. }
  1379. } else {
  1380. "";
  1381. }
  1382. },
  1383. type: function() {
  1384. var parts = location.href.split('/');
  1385. var id = parts.pop().toLowerCase();
  1386. return Rooms.findOne({type: id}).display;
  1387. },
  1388. users: function() {
  1389. var parts = location.href.split('/');
  1390. var id = parts.pop().toLowerCase();
  1391. return Rooms.findOne({type: id}).users;
  1392. },
  1393. title: function(){
  1394. return Session.get("title");
  1395. },
  1396. artist: function(){
  1397. return Session.get("artist");
  1398. },
  1399. loaded: function() {
  1400. return Session.get("loaded");
  1401. },
  1402. paused: function() {
  1403. return Session.get("state") === "paused";
  1404. },
  1405. private: function() {
  1406. return Rooms.findOne({type: Session.get("type")}).private === true;
  1407. },
  1408. report: function() {
  1409. return Session.get("reportObj");
  1410. },
  1411. reportSong: function() {
  1412. return Session.get("reportSong");
  1413. },
  1414. reportTitle: function() {
  1415. return Session.get("reportTitle");
  1416. },
  1417. reportAuthor: function() {
  1418. return Session.get("reportAuthor");
  1419. },
  1420. reportDuration: function() {
  1421. return Session.get("reportDuration");
  1422. },
  1423. reportAudio: function() {
  1424. return Session.get("reportAudio");
  1425. },
  1426. reportAlbumart: function() {
  1427. return Session.get("reportAlbumart");
  1428. },
  1429. reportOther: function() {
  1430. return Session.get("reportOther");
  1431. },
  1432. currentSong: function() {
  1433. return Session.get("currentSong");
  1434. },
  1435. previousSong: function() {
  1436. return Session.get("previousSong");
  1437. },
  1438. currentSongR: function() {
  1439. return Session.get("currentSongR");
  1440. },
  1441. previousSongR: function() {
  1442. return Session.get("previousSongR");
  1443. },
  1444. reportingSong: function() {
  1445. if (Session.get("reportPrevious")) {
  1446. return Session.get("previousSongR");
  1447. } else {
  1448. return Session.get("currentSongR");
  1449. }
  1450. },
  1451. votes: function(){
  1452. return Rooms.findOne({type: Session.get("type")}).votes;
  1453. }
  1454. });
  1455. Template.room.onCreated(function () {
  1456. Chat.after.find(function(userId, selector) {
  1457. if (selector.type === "global") {
  1458. if (!$("#global-chat-tab").hasClass("active")) {
  1459. $("#global-chat-tab").addClass("unread-messages");
  1460. }
  1461. } else if(selector.type === Session.get("type")) {
  1462. if (!$("#chat-tab").hasClass("active")) {
  1463. $("#chat-tab").addClass("unread-messages");
  1464. }
  1465. }
  1466. });
  1467. Session.set("reportSong", false);
  1468. Session.set("reportTitle", false);
  1469. Session.set("reportAuthor", false);
  1470. Session.set("reportDuration", false);
  1471. Session.set("reportAudio", false);
  1472. Session.set("reportAlbumart", false);
  1473. Session.set("reportOther", false);
  1474. if (resizeSeekerbarInterval !== undefined) {
  1475. Meteor.clearInterval(resizeSeekerbarInterval);
  1476. resizeSeekerbarInterval = undefined;
  1477. }
  1478. YTPlayer = undefined;
  1479. SCPlayer = undefined;
  1480. Session.set("videoHidden", false);
  1481. var tag = document.createElement("script");
  1482. tag.src = "https://www.youtube.com/iframe_api";
  1483. var firstScriptTag = document.getElementsByTagName('script')[0];
  1484. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  1485. Session.set("singleVideo", true);
  1486. var currentSong = undefined;
  1487. var currentSongR = undefined;
  1488. function getTimeElapsed() {
  1489. if (currentSong !== undefined) {
  1490. var room = Rooms.findOne({type: type});
  1491. if (room !== undefined) {
  1492. return Date.now() - currentSong.started - room.timePaused;
  1493. }
  1494. }
  1495. return 0;
  1496. }
  1497. function getSongInfo(songData){
  1498. Session.set("title", songData.title);
  1499. Session.set("artist", songData.artist);
  1500. Session.set("id", songData.id);
  1501. $("#song-img").attr("src", songData.img);
  1502. Session.set("duration", parseInt(songData.duration));
  1503. var d = moment.duration(parseInt(songData.duration), 'seconds');
  1504. $("#time-total").text(d.minutes() + ":" + ("0" + d.seconds()).slice(-2));
  1505. Session.set("timeFormat", d.minutes() + ":" + ("0" + d.seconds()).slice(-2));
  1506. }
  1507. function resizeSeekerbar() {
  1508. if (Session.get("state") === "playing") {
  1509. $("#seeker-bar").width(((getTimeElapsed() / 1000) / Session.get("duration") * 100) + "%");
  1510. }
  1511. }
  1512. function startSong() {
  1513. $("#time-elapsed").text("0:00");
  1514. $("#vote-skip").attr("disabled", false);
  1515. if (currentSong !== undefined) {
  1516. if (SCPlayer !== undefined) SCPlayer.stop();
  1517. if (YTPlayer !== undefined && YTPlayer.stopVideo !== undefined) YTPlayer.stopVideo();
  1518. var volume = localStorage.getItem("volume") || 20;
  1519. if (currentSong.type === "SoundCloud") {
  1520. if ($("#soundcloud-image").length !== 1) {
  1521. //$("#media-container").append('<img alt="Not loading" src="/soundcloud-image.png" class="embed-responsive-item" id="soundcloud-image" />');
  1522. $("#media-container").append('<h1 id="soundcloud-image">We have temporarily disabled the playing of SoundCloud songs. We are sorry for this inconvenience.</h1>');
  1523. }
  1524. if ($("#player").length === 1) {
  1525. $("#player").hide();
  1526. }
  1527. $("#soundcloud-image").show();
  1528. //getSongInfo(currentSong);
  1529. /*SC.stream("/tracks/" + currentSong.id, function(sound){
  1530. SCPlayer = sound;
  1531. sound.setVolume(volume / 100);
  1532. sound.play();
  1533. var interval = setInterval(function() {
  1534. if (sound.getState() === "playing") {
  1535. sound.seek(getTimeElapsed());
  1536. window.clearInterval(interval);
  1537. }
  1538. }, 200);
  1539. Session.set("duration", parseInt(currentSong.duration));
  1540. var d = moment.duration(parseInt(currentSong.duration), 'seconds');
  1541. $("#time-total").text(d.minutes() + ":" + ("0" + d.seconds()).slice(-2));
  1542. resizeSeekerbar();
  1543. });*/
  1544. } else {
  1545. if ($("#player").length !== 1) {
  1546. $("#media-container").append('<div id="player" class="embed-responsive-item"></div>');
  1547. }
  1548. if ($("#soundcloud-image").length === 1) {
  1549. $("#soundcloud-image").hide();
  1550. }
  1551. $("#player").show();
  1552. function loadVideo() {
  1553. if (!Session.get("YTLoaded")) {
  1554. Session.set("loadVideoTimeout", Meteor.setTimeout(function () {
  1555. loadVideo();
  1556. }, 500));
  1557. } else {
  1558. if (YTPlayer === undefined) {
  1559. YTPlayer = new YT.Player("player", {
  1560. height: 540,
  1561. width: 960,
  1562. videoId: currentSong.id,
  1563. playerVars: {controls: 0, iv_load_policy: 3, rel: 0, showinfo: 0},
  1564. events: {
  1565. 'onReady': function (event) {
  1566. if (currentSong.skipDuration === undefined) {
  1567. currentSong.skipDuration = 0;
  1568. }
  1569. event.target.seekTo(Number(currentSong.skipDuration) + getTimeElapsed() / 1000);
  1570. event.target.playVideo();
  1571. event.target.setVolume(volume);
  1572. resizeSeekerbar();
  1573. },
  1574. 'onStateChange': function (event) {
  1575. if (Session.get("YTLoaded")) {
  1576. if (event.data == YT.PlayerState.PAUSED && Session.get("state") === "playing") {
  1577. event.target.seekTo(Number(currentSong.skipDuration) + getTimeElapsed() / 1000);
  1578. event.target.playVideo();
  1579. }
  1580. if (event.data == YT.PlayerState.PLAYING && Session.get("state") === "paused") {
  1581. event.target.seekTo(Number(currentSong.skipDuration) + getTimeElapsed() / 1000);
  1582. event.target.pauseVideo();
  1583. }
  1584. }
  1585. }
  1586. }
  1587. });
  1588. } else {
  1589. YTPlayer.loadVideoById(currentSong.id);
  1590. if (currentSong.skipDuration === undefined) {
  1591. currentSong.skipDuration = 0;
  1592. }
  1593. YTPlayer.seekTo(Number(currentSong.skipDuration) + getTimeElapsed() / 1000);
  1594. }
  1595. Session.set("pauseVideo", false);
  1596. getSongInfo(currentSong);
  1597. }
  1598. }
  1599. loadVideo();
  1600. }
  1601. }
  1602. }
  1603. Session.set("loaded", false);
  1604. Meteor.subscribe("rooms", function() {
  1605. var parts = location.href.split('/');
  1606. var id = parts.pop();
  1607. var type = id.toLowerCase();
  1608. Session.set("type", type);
  1609. if (Rooms.find({type: type}).count() !== 1) {
  1610. window.location = "/";
  1611. } else {
  1612. StationSubscription = Meteor.subscribe(type);
  1613. Session.set("loaded", true);
  1614. minterval = Meteor.setInterval(function () {
  1615. var room = Rooms.findOne({type: type});
  1616. if (room !== undefined) {
  1617. if (room.state === "paused" || Session.get("pauseVideo")) {
  1618. Session.set("state", "paused");
  1619. // TODO Fix issue where sometimes nothing loads with the YT is not defined error. The error points to around this.
  1620. if (YTPlayer !== undefined && YTPlayer.getPlayerState !== undefined && YTPlayer.getPlayerState() === 1) {
  1621. YTPlayer.pauseVideo();
  1622. } else if (SCPlayer !== undefined && SCPlayer.getState().indexOf("playing") !== -1) {
  1623. SCPlayer.pause();
  1624. }
  1625. } else {
  1626. Session.set("state", "playing");
  1627. if (YTPlayer !== undefined && YTPlayer.getPlayerState !== undefined && YTPlayer.getPlayerState() !== 1) {
  1628. YTPlayer.playVideo();
  1629. } else if (SCPlayer !== undefined && SCPlayer.getState().indexOf("paused") !== -1) {
  1630. SCPlayer.play();
  1631. }
  1632. }
  1633. }
  1634. if (room.currentSong.song !== undefined && (currentSongR === undefined || room.currentSong.started !== currentSongR.started)) {
  1635. Session.set("previousSong", currentSong);
  1636. currentSongR = room.currentSong;
  1637. currentSong = room.currentSong.song;
  1638. currentSong.started = room.currentSong.started;
  1639. Session.set("currentSong", currentSong);
  1640. Meteor.clearTimeout(Session.get("loadVideoTimeout"));
  1641. startSong();
  1642. }
  1643. if (currentSong !== undefined) {
  1644. if (room !== undefined) {
  1645. var duration = (Date.now() - currentSong.started - room.timePaused) / 1000;
  1646. var song_duration = currentSong.duration;
  1647. if (song_duration <= duration) {
  1648. Session.set("pauseVideo", true);
  1649. }
  1650. var d = moment.duration(duration, 'seconds');
  1651. if (Session.get("state") === "playing") {
  1652. $("#time-elapsed").text(d.minutes() + ":" + ("0" + d.seconds()).slice(-2));
  1653. }
  1654. }
  1655. }
  1656. }, 100);
  1657. resizeSeekerbarInterval = Meteor.setInterval(function () {
  1658. resizeSeekerbar();
  1659. }, 500);
  1660. }
  1661. });
  1662. });
  1663. // Settings Template
  1664. Template.settings.events({
  1665. "click #save-settings": function() {
  1666. Meteor.call("updateSettings", $("#showRating").is(":checked"));
  1667. },
  1668. "click #delete-account": function(){
  1669. $("#delete-account").text("Click to confirm");
  1670. $("#delete-account").click(function(){
  1671. var bool = confirm("Are you sure you want to delete your account?");
  1672. if(bool) {
  1673. Meteor.call("deleteAccount");
  1674. }
  1675. })
  1676. },
  1677. "click #change-password": function(){
  1678. var oldPassword = $("#old-password").val();
  1679. var newPassword= $("#new-password").val();
  1680. var confirmPassword = $("#confirm-password").val();
  1681. if(newPassword === confirmPassword){
  1682. Accounts.changePassword(oldPassword, newPassword, function(err){
  1683. if(err){
  1684. $("#old-password").val("");
  1685. $("#new-password").val("");
  1686. $("#confirm-password").val("");
  1687. $("<div class='alert alert-danger alert-dismissible' role='alert' style='margin-bottom: 0'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'><i class='fa fa-times'></i></span></button><strong>Oh Snap! </strong>" + err.reason + "</div>").prependTo($("#head")).delay(7000).fadeOut(1000, function() { $(this).remove(); });
  1688. } else {
  1689. $("#old-password").val("");
  1690. $("#new-password").val("");
  1691. $("#confirm-password").val("");
  1692. $("<div class='alert alert-success alert-dismissible' role='alert' style='margin-bottom: 0'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'><i class='fa fa-times'></i></span></button><strong>Hooray!</strong> You changed your password successfully.</div>").prependTo($("#head")).delay(7000).fadeOut(1000, function() { $(this).remove(); });
  1693. }
  1694. });
  1695. }
  1696. }
  1697. });
  1698. Template.settings.helpers({
  1699. username: function() {
  1700. if (Meteor.user() !== undefined) {
  1701. return Meteor.user().profile.username;
  1702. } else {
  1703. return "";
  1704. }
  1705. }
  1706. });
  1707. Template.settings.onCreated(function() {
  1708. $(document).ready(function() {
  1709. var user = Meteor.user();
  1710. function initSettings() {
  1711. if (user !== undefined) {
  1712. if (user.profile.settings && user.profile.settings.showRating === true) {
  1713. function setChecked() {
  1714. $("#showRating").prop("checked", true);
  1715. if (!$("#showRating").prop("checked")) {
  1716. Meteor.setTimeout(function() {
  1717. setChecked();
  1718. }, 100);
  1719. }
  1720. }
  1721. setChecked();
  1722. }
  1723. } else {
  1724. Meteor.setTimeout(function() {
  1725. initSettings();
  1726. }, 500);
  1727. }
  1728. }
  1729. initSettings();
  1730. });
  1731. });
  1732. // Stations Template
  1733. Template.stations.helpers({
  1734. playlist: function() {
  1735. var query = {type: Session.get("playlistToEdit").toLowerCase()};
  1736. var playlists = Playlists.find(query).fetch();
  1737. return playlists;
  1738. },
  1739. whichStation: function(){
  1740. return Session.get("playlistToEdit");
  1741. },
  1742. reports: function() {
  1743. var query = {room: Session.get("playlistToEdit").toLowerCase()};
  1744. var reports = Reports.find(query).fetch();
  1745. console.log(reports);
  1746. return reports;
  1747. }
  1748. });
  1749. Template.stations.events({
  1750. "click .preview-button": function(e){
  1751. Session.set("song", this);
  1752. },
  1753. "click #previewImageButton": function() {
  1754. $("#preview-image").attr("src", Session.get("song").img);
  1755. },
  1756. "click .edit-queue-button": function(e){
  1757. Session.set("song", this);
  1758. Session.set("genre", $(e.target).data("genre"));
  1759. Session.set("type", "queue");
  1760. $("#type").val(this.type);
  1761. $("#mid").val(this.mid);
  1762. $("#artist").val(this.artist);
  1763. $("#title").val(this.title);
  1764. $("#img").val(this.img);
  1765. $("#id").val(this.id);
  1766. $("#likes").val(this.likes);
  1767. $("#dislikes").val(this.dislikes);
  1768. $("#duration").val(this.duration);
  1769. $("#skip-duration").val(this.skipDuration);
  1770. },
  1771. "click .edit-playlist-button": function(e){
  1772. Session.set("song", this);
  1773. Session.set("genre", $(e.target).data("genre"));
  1774. Session.set("type", "playlist");
  1775. $("#type").val(this.type);
  1776. $("#mid").val(this.mid);
  1777. $("#artist").val(this.artist);
  1778. $("#title").val(this.title);
  1779. $("#img").val(this.img);
  1780. $("#id").val(this.id);
  1781. $("#likes").val(this.likes);
  1782. $("#dislikes").val(this.dislikes);
  1783. $("#duration").val(this.duration);
  1784. $("#skip-duration").val(this.skipDuration);
  1785. },
  1786. "click .add-song-button": function(e){
  1787. var genre = $(e.target).data("genre") || $(e.target).parent().data("genre");
  1788. Meteor.call("addSongToPlaylist", genre, this);
  1789. },
  1790. "click .deny-song-button": function(e){
  1791. var genre = $(e.target).data("genre") || $(e.target).parent().data("genre");
  1792. Meteor.call("removeSongFromQueue", genre, this.mid);
  1793. },
  1794. "click .remove-song-button": function(e){
  1795. var genre = $(e.target).data("genre") || $(e.target).parent().data("genre");
  1796. Meteor.call("removeSongFromPlaylist", genre, this.mid);
  1797. },
  1798. "click #moveSong": function(e){
  1799. var genre = $(e.target).data("genre") || $(e.target).parent().data("genre");
  1800. if (genre !== Session.get(genre)) {
  1801. Meteor.call("addSongToPlaylist", genre, {type: Session.get("song").type, mid: Session.get("song").mid, id: Session.get("song").id, title: Session.get("song").title, artist: Session.get("song").artist, duration: Session.get("song").duration, skipDuration: Session.get("song").skipDuration, img: Session.get("song").img, likes: Session.get("song").likes, dislikes: Session.get("song").dislikes, requestedBy: Session.get("song").requestedBy});
  1802. Meteor.call("removeSongFromPlaylist", Session.get("genre"), Session.get("song").mid);
  1803. }else {
  1804. console.log("Something Went Wrong?!");
  1805. return false;
  1806. }
  1807. },
  1808. "click #copySong": function(e){
  1809. var genre = $(e.target).data("genre") || $(e.target).parent().data("genre");
  1810. Meteor.call("addSongToPlaylist", genre, {type: Session.get("song").type, mid: Session.get("song").mid, id: Session.get("song").id, title: Session.get("song").title, artist: Session.get("song").artist, duration: Session.get("song").duration, skipDuration: Session.get("song").skipDuration, img: Session.get("song").img, likes: Session.get("song").likes, dislikes: Session.get("song").dislikes, requestedBy: Session.get("song").requestedBy});
  1811. },
  1812. "click .copyMove-button": function(e){
  1813. Session.set("song", this);
  1814. Session.set("genre", $(e.target).data("genre"));
  1815. },
  1816. "click #play": function() {
  1817. $("#play").attr("disabled", true);
  1818. $("#stop").attr("disabled", false);
  1819. var song = Session.get("song");
  1820. var id = song.id;
  1821. var type = song.type;
  1822. var volume = localStorage.getItem("volume") || 20;
  1823. if (type === "YouTube") {
  1824. if (YTPlayer === undefined) {
  1825. YTPlayer = new YT.Player("previewPlayer", {
  1826. height: 540,
  1827. width: 568,
  1828. videoId: id,
  1829. playerVars: {controls: 0, iv_load_policy: 3, showinfo: 0},
  1830. events: {
  1831. 'onReady': function(event) {
  1832. event.target.seekTo(Number(song.skipDuration));
  1833. event.target.playVideo();
  1834. event.target.setVolume(volume);
  1835. },
  1836. 'onStateChange': function(event){
  1837. if (event.data == YT.PlayerState.PAUSED) {
  1838. event.target.playVideo();
  1839. }
  1840. if (event.data == YT.PlayerState.PLAYING) {
  1841. $("#play").attr("disabled", true);
  1842. $("#stop").attr("disabled", false);
  1843. } else {
  1844. $("#play").attr("disabled", false);
  1845. $("#stop").attr("disabled", true);
  1846. }
  1847. }
  1848. }
  1849. });
  1850. } else {
  1851. YTPlayer.loadVideoById(id);
  1852. YTPlayer.seekTo(Number(song.skipDuration));
  1853. }
  1854. $("#previewPlayer").show();
  1855. } else if (type === "SoundCloud") {
  1856. SC.stream("/tracks/" + song.id, function(sound) {
  1857. SCPlayer = sound;
  1858. sound.setVolume(volume / 100);
  1859. sound.play();
  1860. });
  1861. }
  1862. if (previewEndSongTimeout !== undefined) {
  1863. Meteor.clearTimeout(previewEndSongTimeout);
  1864. }
  1865. previewEndSongTimeout = Meteor.setTimeout(function() {
  1866. if (YTPlayer !== undefined) {
  1867. YTPlayer.stopVideo();
  1868. }
  1869. if (SCPlayer !== undefined) {
  1870. SCPlayer.stop();
  1871. }
  1872. $("#play").attr("disabled", false);
  1873. $("#stop").attr("disabled", true);
  1874. $("#previewPlayer").hide();
  1875. }, song.duration * 1000);
  1876. },
  1877. "click #stop": function() {
  1878. $("#play").attr("disabled", false);
  1879. $("#stop").attr("disabled", true);
  1880. if (previewEndSongTimeout !== undefined) {
  1881. Meteor.clearTimeout(previewEndSongTimeout);
  1882. }
  1883. if (YTPlayer !== undefined) {
  1884. YTPlayer.stopVideo();
  1885. }
  1886. if (SCPlayer !== undefined) {
  1887. SCPlayer.stop();
  1888. }
  1889. },
  1890. "click #forward": function() {
  1891. var error = false;
  1892. if (YTPlayer !== undefined) {
  1893. var duration = Number(Session.get("song").duration) | 0;
  1894. var skipDuration = Number(Session.get("song").skipDuration) | 0;
  1895. if (YTPlayer.getDuration() < duration + skipDuration) {
  1896. alert("The duration of the YouTube video is smaller than the duration.");
  1897. error = true;
  1898. } else {
  1899. YTPlayer.seekTo(skipDuration + duration - 10);
  1900. }
  1901. }
  1902. if (SCPlayer !== undefined) {
  1903. SCPlayer.seekTo((skipDuration + duration - 10) * 1000);
  1904. }
  1905. if (!error) {
  1906. if (previewEndSongTimeout !== undefined) {
  1907. Meteor.clearTimeout(previewEndSongTimeout);
  1908. }
  1909. previewEndSongTimeout = Meteor.setTimeout(function() {
  1910. if (YTPlayer !== undefined) {
  1911. YTPlayer.stopVideo();
  1912. }
  1913. if (SCPlayer !== undefined) {
  1914. SCPlayer.stop();
  1915. }
  1916. $("#play").attr("disabled", false);
  1917. $("#stop").attr("disabled", true);
  1918. $("#previewPlayer").hide();
  1919. }, 10000);
  1920. }
  1921. },
  1922. "click #get-spotify-info": function() {
  1923. var search = $("#title").val();
  1924. var artistName = $("#artist").val();
  1925. getSpotifyInfo(search, function(data) {
  1926. for(var i in data){
  1927. for(var j in data[i].items){
  1928. if(search.indexOf(data[i].items[j].name) !== -1 && artistName.indexOf(data[i].items[j].artists[0].name) !== -1){
  1929. $("#img").val(data[i].items[j].album.images[1].url);
  1930. $("#duration").val(data[i].items[j].duration_ms / 1000);
  1931. return;
  1932. }
  1933. }
  1934. }
  1935. }, artistName);
  1936. },
  1937. "click #save-song-button": function() {
  1938. var newSong = {};
  1939. newSong.id = $("#id").val();
  1940. newSong.likes = Number($("#likes").val());
  1941. newSong.dislikes = Number($("#dislikes").val());
  1942. newSong.title = $("#title").val();
  1943. newSong.artist = $("#artist").val();
  1944. newSong.img = $("#img").val();
  1945. newSong.type = $("#type").val();
  1946. newSong.duration = Number($("#duration").val());
  1947. newSong.skipDuration = $("#skip-duration").val();
  1948. if(newSong.skipDuration === undefined){
  1949. newSong.skipDuration = 0;
  1950. };
  1951. if (Session.get("type") === "playlist") {
  1952. Meteor.call("updatePlaylistSong", Session.get("genre"), Session.get("song"), newSong, function() {
  1953. $('#editModal').modal('hide');
  1954. });
  1955. } else {
  1956. Meteor.call("updateQueueSong", Session.get("genre"), Session.get("song"), newSong, function() {
  1957. $('#editModal').modal('hide');
  1958. });
  1959. }
  1960. },
  1961. "click .delete-room": function(){
  1962. var typeDel = $(this)[0].type;
  1963. Meteor.call("deleteRoom", typeDel);
  1964. }
  1965. });
  1966. Template.stations.onCreated(function() {
  1967. var tag = document.createElement("script");
  1968. tag.src = "https://www.youtube.com/iframe_api";
  1969. var firstScriptTag = document.getElementsByTagName('script')[0];
  1970. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  1971. YTPlayer = undefined;
  1972. SCPlayer = undefined;
  1973. });
  1974. Template.stations.onRendered(function() {
  1975. $("#previewModal").on("hidden.bs.modal", function() {
  1976. if (previewEndSongTimeout !== undefined) {
  1977. Meteor.clearTimeout(previewEndSongTimeout);
  1978. }
  1979. $("#play").attr("disabled", false);
  1980. $("#stop").attr("disabled", true);
  1981. if (YTPlayer !== undefined) {
  1982. $("#previewPlayer").hide();
  1983. YTPlayer.seekTo(0);
  1984. YTPlayer.stopVideo();
  1985. }
  1986. if (SCPlayer !== undefined) {
  1987. SCPlayer.stop();
  1988. }
  1989. });
  1990. $(document).ready(function() {
  1991. function makeSlider(){
  1992. var slider = $("#volume-slider").slider();
  1993. var volume = localStorage.getItem("volume") || 20;
  1994. $("#volume-slider").slider("setValue", volume);
  1995. if (slider.length === 0) {
  1996. Meteor.setTimeout(function() {
  1997. makeSlider();
  1998. }, 500);
  1999. } else {
  2000. slider.on("slide", function(val) {
  2001. localStorage.setItem("volume", val.value);
  2002. if (YTPlayer !== undefined) {
  2003. YTPlayer.setVolume(val.value);
  2004. } else if (SCPlayer !== undefined) {
  2005. var volume = val.value / 100;
  2006. SCPlayer.setVolume(volume);
  2007. }
  2008. });
  2009. }
  2010. }
  2011. makeSlider();
  2012. });
  2013. });
  2014. curPath=function(){var c=window.location.pathname;var b=c.slice(0,-1);var a=c.slice(-1);if(b==""){return"/"}else{if(a=="/"){return b}else{return c}}};
  2015. Handlebars.registerHelper('active', function(path) {
  2016. return curPath() == path ? 'active' : '';
  2017. });
  2018. function executeCommand(command, params){
  2019. if (command === "help" || command === "commands") {
  2020. $('#helpModal').modal('show');
  2021. return true;
  2022. } else if (command === "volume") {
  2023. if (params.length === 1) {
  2024. var volume = Number(params[0]);
  2025. if (volume >= 0 || volume <= 100) {
  2026. if (volume === 0) {
  2027. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off")
  2028. } else {
  2029. $("#volume-icon").removeClass("fa-volume-off").addClass("fa-volume-down")
  2030. }
  2031. $("#volume-slider").slider("setValue", volume);
  2032. if (YTPlayer !== undefined) {
  2033. YTPlayer.setVolume(volume);
  2034. localStorage.setItem("volume", volume);
  2035. } else if (SCPlayer !== undefined) {
  2036. //SCPlayer
  2037. var volume = volume / 100;
  2038. SCPlayer.setVolume(volume);
  2039. localStorage.setItem("volume", volume * 100);
  2040. }
  2041. return true;
  2042. }
  2043. }
  2044. } else if(command === "mute"){
  2045. $("#volume-slider").slider("setValue", 0);
  2046. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off");
  2047. if (YTPlayer !== undefined) {
  2048. YTPlayer.setVolume(0);
  2049. localStorage.setItem("volume", 0);
  2050. } else if (SCPlayer !== undefined) {
  2051. //SCPlayer
  2052. SCPlayer.setVolume(0);
  2053. localStorage.setItem("volume", 0);
  2054. }
  2055. } else if(command === "ban"){
  2056. var user = params[0];
  2057. var time = params[1];
  2058. var reason = params[2];
  2059. Meteor.call("banUser", user, time, reason, function(err, res){
  2060. if(err){
  2061. console.log(err);
  2062. }
  2063. });
  2064. } else if(command === "silence"){
  2065. var user = params[0];
  2066. var time = params[1];
  2067. Meteor.call("muteUser", user, time, function(err, res){
  2068. if(err){
  2069. console.log(err);
  2070. }
  2071. });
  2072. } else if(command === "unban"){
  2073. var user = params[0];
  2074. Meteor.call("unbanUser", user, function(err, res){
  2075. if(err){
  2076. console.log(err);
  2077. }
  2078. });
  2079. } else if(command === "unsilence"){
  2080. var user = params[0];
  2081. Meteor.call("unsilenceUser", user, function(err, res){
  2082. if(err){
  2083. console.log(err);
  2084. }
  2085. });
  2086. } else if(command === "pause"){
  2087. Meteor.call("pauseRoom", Session.get("type"), function(err, res){
  2088. if(err){
  2089. console.log(err);
  2090. }
  2091. });
  2092. } else if(command === "resume"){
  2093. Meteor.call("resumeRoom", Session.get("type"), function(err, res){
  2094. if(err){
  2095. console.log(err);
  2096. }
  2097. });
  2098. } else if(command === "shuffle"){
  2099. Meteor.call("shufflePlaylist", Session.get("type"), function(err, res){
  2100. if(err){
  2101. console.log(err);
  2102. }
  2103. });
  2104. } else if(command === "skip"){
  2105. Meteor.call("skipSong", Session.get("type"), function(err, res){
  2106. if(err){
  2107. console.log(err);
  2108. }
  2109. });
  2110. }
  2111. }
  2112. function sendMessage() {
  2113. var message = $("#chat-input").val();
  2114. if (!$("#chat-input").hasClass("disabled")) {
  2115. if (message.length > 0 && message[0] !== " ") {
  2116. if (message[0] === "/") {
  2117. message = message.split("");
  2118. message.shift();
  2119. message = message.join("");
  2120. var params = message.split(" ");
  2121. params = params.map(function(param) {
  2122. return param.replace(/\r?\n|\r/g, "");
  2123. });
  2124. var command = params.shift();
  2125. command = command.replace(/\r?\n|\r/g, "");
  2126. if (executeCommand(command, params)) {
  2127. $("#chat-input").val("");
  2128. } else {
  2129. $("#chat-input").val("");
  2130. }
  2131. } else {
  2132. $("#chat-input").addClass("disabled");
  2133. $("#chat-input").attr("disabled", "");
  2134. Meteor.call("sendMessage", Session.get("type"), message, function (err, res) {
  2135. if (res) {
  2136. $("#chat-input").val("");
  2137. $("#chat-input").removeAttr("disabled");
  2138. $("#chat-input").removeClass("disabled");
  2139. }
  2140. });
  2141. }
  2142. }
  2143. }
  2144. }
  2145. function sendMessageGlobal() {
  2146. var message = $("#global-chat-input").val();
  2147. if (!$("#global-chat-input").hasClass("disabled")) {
  2148. if (message.length > 0 && message[0] !== " ") {
  2149. if (message[0] === "/") {
  2150. message = message.split("");
  2151. message.shift();
  2152. message = message.join("");
  2153. var params = message.split(" ");
  2154. var command = params.shift();
  2155. command = command.replace(/\r?\n|\r/g, "");
  2156. if (executeCommand(command, params)) {
  2157. $("#global-chat-input").val("");
  2158. } else {
  2159. $("#global-chat-input").val("");
  2160. }
  2161. } else {
  2162. $("#global-chat-input").addClass("disabled");
  2163. $("#global-chat-input").attr("disabled", "");
  2164. Meteor.call("sendMessage", "global", message, function (err, res) {
  2165. if (res) {
  2166. $("#global-chat-input").val("");
  2167. }
  2168. $("#global-chat-input").removeClass("disabled");
  2169. $("#global-chat-input").removeAttr("disabled");
  2170. });
  2171. }
  2172. }
  2173. }
  2174. }
  2175. Template.registerHelper("rtime", function(date) {
  2176. Session.get("time");
  2177. if (date) {
  2178. return moment(date).fromNow();
  2179. }
  2180. });
  2181. var rTimeInterval = undefined;
  2182. var allAlertSub = undefined;
  2183. var YTPlayer = undefined;
  2184. var SCPlayer = undefined;
  2185. var previewEndSongTimeout = undefined;