client.js 86 KB

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