How to use dontRemoveMe method in Cypress

Best JavaScript code snippet using cypress

app.js

Source:app.js Github

copy

Full Screen

1require('dotenv').config({2 silent: process.env.NODE_ENV === 'production'3});4var request = require('request');5var firebase = require('firebase');6var YouTube = require('youtube-node');7var Vibrant = require('node-vibrant');8var youTube = new YouTube();9var SC = require('node-soundcloud')10youTube.setKey(process.env.YOUTUBE_KEY);11SC.init({12 id: process.env.SOUNDCLOUD_KEY,13});14var users = {};15var botid = null;16var started = false;17var queue = [];18var removalPending = {};19var queueRef = null;20theDJ = null;21var cardForGrabs = null;22var totalCards = 0;23var cardGen = false;24var colors = {25 color: "#fff",26 txt: "#fff"27};28var robotsDancing = false;29var cardGiftedThisSong = false;30var table = [];31var playlimit = 2;32ignoreChats = true;33var song = null;34var playDex = 0; //where does the spotlight go? (tracks SEATS not people)35var theme = null;36var songTimeout = null;37var adam_last = null;38var songtimer = null;39var cardSpecial = false;40var configs = {41 apiKey: process.env.FIREBASE_KEY,42 authDomain: process.env.FIREBASE_AUTH,43 databaseURL: process.env.FIREBASE_DB44};45firebase.initializeApp(configs);46firebase.auth().onAuthStateChanged(function(user) {47 if (user) {48 botid = user.uid;49 console.log(botid);50 var ref0 = firebase.database().ref("users/" + user.uid + "/status");51 ref0.set(true);52 ref0.onDisconnect().set(false);53 if (!started) {54 var tpeek = firebase.database().ref("table");55 tpeek.once("value").then(function(snapshot) {56 var data = snapshot.val();57 if (data) {58 for (var key in data) {59 if (data.hasOwnProperty(key)) {60 table.push(data[key]);61 }62 }63 } else {64 console.log("no DJS");65 }66 var wpeek = firebase.database().ref("waitlist");67 wpeek.once("value").then(function(snapshot) {68 var data = snapshot.val();69 if (data) {70 for (var key in data) {71 if (data.hasOwnProperty(key)) {72 queue.push(data[key]);73 }74 }75 } else {76 console.log("no waiters");77 }78 var ppeek = firebase.database().ref("playdex");79 ppeek.once("value").then(function(snapshot) {80 var data = snapshot.val();81 if (data) {82 playDex = data;83 }84 var twopeek = firebase.database().ref("songToPlay");85 twopeek.once("value").then(function(snapshot) {86 var data = snapshot.val();87 var nownow = Date.now();88 song = data;89 theDJ = table[playDex];90 console.log(queue);91 if (data) {92 var timeSince = nownow - data.started;93 var secSince = Math.floor(timeSince / 1000);94 var timeLeft = data.duration - secSince;95 if (timeLeft <= 0) {96 nextSong();97 } else {98 songTimeout = setTimeout(function() {99 songTimeout = null;100 nextSong(); //NEEEEEEXT101 }, timeLeft * 1000);102 }103 }104 updateThings();105 started = true;106 });107 });108 });109 });110 }111 }112});113var uidLookup = function(name) {114 var match = false;115 var usrs = users;116 for (var key in usrs) {117 if (usrs.hasOwnProperty(key)) {118 if (users[key].username) {119 if (users[key].username == name) {120 match = key;121 }122 }123 }124 }125 if (!match && users[name]) match = name;126 return match;127}128var talk = function(txt, card) {129 var namebo2 = botid;130 if (users[botid]) {131 if (users[botid].username) namebo2 = users[botid].username;132 }133 var chatData = firebase.database().ref("chatData");134 var chatFeed = firebase.database().ref("chatFeed");135 var chooto = {136 time: firebase.database.ServerValue.TIMESTAMP,137 id: botid,138 txt: txt,139 name: namebo2140 };141 if (card) chooto.card = card;142 var chatItem = chatData.push(chooto, function() {143 var feedObj = {144 chatID: chatItem.key145 };146 var feedItem = chatFeed.push(feedObj, function() {147 chatItem.child("feedID").set(feedItem.key);148 });149 });150};151var updateTable = function() {152 var table2 = firebase.database().ref("table");153 table2.set(table);154};155var updateWaitlist = function() {156 var waitlist2 = firebase.database().ref("waitlist");157 waitlist2.set(queue);158};159var updateLimit = function() {160 var limit2 = firebase.database().ref("playlimit");161 var limitHere = "∞";162 if (queue.length && (table.length >= 4)) {163 limitHere = playlimit;164 }165 limit2.set(limitHere);166};167var updatePlaydex = function() {168 var playdex2 = firebase.database().ref("playdex");169 playdex2.set(playDex);170};171var firelevel = {172 hot: function(id, name) {173 firelevel.fires[id] = true;174 firelevel.storms[id] = false;175 var fires = firelevel.size(firelevel.fires);176 var storms = firelevel.size(firelevel.storms);177 var level = fires - storms;178 console.log(level);179 if (level <= 0) {180 talk(name + " thinks this track is h0t... doesn't seem very hot...");181 } else if (level == 1) {182 talk(name + " thinks this track is h0t! A small fire has started.");183 } else if (level <= 7) {184 talk(name + " thinks this track is h0t! Fire is burnin' :chart_with_upwards_trend:");185 } else {186 talk(name + " thinks this track is h0t! FIRE LEVEL IS OFF THE CHARTS. CHARTS ON FIRE!");187 }188 },189 storm: function(id, name) {190 firelevel.fires[id] = false;191 firelevel.storms[id] = true;192 var fires = firelevel.size(firelevel.fires);193 var storms = firelevel.size(firelevel.storms);194 var level = fires - storms;195 console.log(level);196 if (level >= 4) {197 talk(name + " is trying to put out the DJ's fire... doesn't seem to matter...");198 } else if (level >= 1) {199 talk(name + " is trying to put out the DJ's fire... maybe this track isn't so hot afterall...");200 } else if (level == 0) {201 talk("fire is out. thanks " + name);202 } else if (level == -1) {203 talk("this track has caused a storm to form around " + name + ". hard to start a fire with all this rain...");204 } else if (level >= -5) {205 talk("the storm has expanded with the help of " + name + ". certainly not a h0t track.");206 } else {207 talk(":rotating_light: :warning: SEVERE WEATHER ALERT. STAY FAR AWAY FROM THIS TRACK.");208 }209 },210 clear: function() {211 firelevel.fires = {};212 firelevel.storms = {};213 },214 fires: {},215 storms: {},216 size: function(obj) {217 var size = 0;218 for (var key in obj) {219 if (obj.hasOwnProperty(key)) {220 if (obj[key]) {221 size++;222 }223 }224 }225 return size;226 }227};228var ytVideoCheck = function(result) {229 var isBroken = false;230 if (result.items[0].contentDetails) {231 if (result.items[0].contentDetails.regionRestriction) {232 if (result.items[0].contentDetails.regionRestriction.allowed) {233 if (result.items[0].contentDetails.regionRestriction.allowed.length) {234 if (!result.items[0].contentDetails.regionRestriction.allowed.includes("US")) {235 //blocked in US.... SKIP!236 isBroken = true;237 } else {238 //not blocked in US...239 }240 }241 }242 if (result.items[0].contentDetails.regionRestriction.blocked) {243 if (result.items[0].contentDetails.regionRestriction.blocked.length) {244 //there's some BLOCKED guys245 if (result.items[0].contentDetails.regionRestriction.blocked.includes("US")) {246 //blocked in US.... SKIP!247 isBroken = true;248 } else {249 //not blocked in US...250 }251 }252 }253 }254 }255 return isBroken;256};257var ytAgeRestrictionCheck = function(result) {258 var isRestricted = false;259 if (result.items[0].contentDetails) {260 if (result.items[0].contentDetails.contentRating) {261 if (result.items[0].contentDetails.contentRating.ytRating) {262 if (result.items[0].contentDetails.contentRating.ytRating == "ytAgeRestricted") {263 isRestricted = true;264 }265 }266 }267 }268 return isRestricted;269};270var newMusicCheck = function(data) {271 var daysAgo;272 var isNew = false;273 var playcount = 0;274 if (data.playcount) playcount = parseInt(data.playcount);275 if (data) {276 var dif = Date.now() - data.postedDate;277 daysAgo = Math.floor(dif / 1000 / 60 / 60 / 24);278 if (daysAgo <= 30 && !playcount) {279 isNew = true;280 }281 }282 return isNew;283};284var updateThings = function() {285 updateTable();286 updateWaitlist();287 updatePlaydex();288 updateLimit();289};290var nextSong = function(noPrevPlay) {291 //we need to remove this song that just played to the bottom of dj's queue292 playDex++; //shift the spotlight to the right293 if (queue.length && theDJ) {294 if (theDJ.removeAfter) {295 removePerson(theDJ.id);296 } else if (theDJ.plays >= playlimit) {297 var foundDJ = removePerson(theDJ.id);298 if (foundDJ && !theDJ.removeAfter) {299 //re-add this DJ to waitlist300 //if we didn't find them then I assume they left mid song?idk301 theDJ.plays = 0;302 queue.push(theDJ);303 }304 }305 } else if (theDJ) {306 if (theDJ.removeAfter) removePerson(theDJ.id);307 }308 startSong(noPrevPlay);309};310var startSong = function(noPrevPlay) {311 console.log(table.length);312 firelevel.clear();313 var danceref = firebase.database().ref("dance");314 danceref.set(false);315 robotsDancing = false;316 cardGiftedThisSong = false;317 if (song && !noPrevPlay) {318 if (song.cid != 0) {319 var newEntry = {320 artist: song.artist,321 title: song.title,322 dj: theDJ.name,323 djid: theDJ.id,324 type: song.type,325 duration: song.duration,326 url: song.url,327 cid: song.cid,328 colors: colors,329 when: song.started,330 postedDate: song.postedDate,331 img: song.image332 };333 if (song.adamid) newEntry.adamid = song.adamid;334 if (song.playcount) newEntry.playcount = song.playcount;335 var recentz = firebase.database().ref("songHistory");336 recentz.push(newEntry);337 recentz.once("value", function(snapshot) {338 var rdata = snapshot.val();339 var allRecents = [];340 for (var okey in rdata) {341 if (rdata.hasOwnProperty(okey)) {342 allRecents.push(okey);343 }344 }345 if (allRecents.length > 50) {346 var shave = allRecents.length - 50;347 for (var ayy = 0; ayy < shave; ayy++) {348 recentz.child(allRecents[ayy]).remove();349 }350 }351 });352 var isNew = newMusicCheck(newEntry);353 if (isNew) {354 // NEW MUSIC355 var newMusic = firebase.database().ref("newMusic");356 newMusic.push(newEntry);357 newMusic.once("value", function(snapshot) {358 var rdata = snapshot.val();359 var allNew = [];360 for (var okey in rdata) {361 if (rdata.hasOwnProperty(okey)) {362 allNew.push(okey);363 }364 }365 if (allNew.length > 100) {366 var shave = allNew.length - 100;367 for (var ayy = 0; ayy < shave; ayy++) {368 newMusic.child(allNew[ayy]).remove();369 }370 }371 });372 }373 }374 }375 if (songtimer != null) {376 clearTimeout(songtimer);377 songtimer = null;378 }379 if (!table.length) {380 console.log("no length");381 var s2p = firebase.database().ref("songToPlay");382 var now = Date.now();383 var songInfo = {384 type: 1,385 cid: 0,386 title: "Nothing Is Playing",387 started: now,388 url: null,389 duration: 0,390 image: "img/idlogo.png",391 artist: "You could (should) queue something!"392 };393 song = songInfo;394 s2p.set(songInfo);395 var clrs = "#fff";396 var textcol = "#fff";397 var colref = firebase.database().ref("colors");398 var thecolors = {399 color: clrs,400 txt: textcol401 };402 colref.set(thecolors);403 colors = thecolors;404 updateThings();405 return false;406 };407 maxindex = table.length - 1;408 if (playDex > maxindex) {409 playDex = 0;410 }411 theDJ = table[playDex];412 table[playDex].plays = table[playDex].plays + 1;413 updateThings();414 if (users[theDJ.id].selectedList) {415 if (users[theDJ.id].selectedList == "0") {416 queueRef = firebase.database().ref("queues/" + theDJ.id);417 } else {418 queueRef = firebase.database().ref("playlists/" + theDJ.id + "/" + users[theDJ.id].selectedList + "/list");419 }420 } else {421 queueRef = firebase.database().ref("queues/" + theDJ.id);422 }423 queueRef.once("value").then(function(snapshot) {424 var data = snapshot.val();425 var goodTrack = null;426 for (var key in data) {427 if (data[key]) {428 if (!data[key].flagged) {429 goodTrack = key;430 break;431 }432 }433 }434 if (goodTrack) {435 var nextSongkey = goodTrack;436 if (data[nextSongkey].type == 1) {437 youTube.getById(data[nextSongkey].cid, function(error, result) {438 if (error || !result.items) {439 console.log(error);440 //SONG DOES NOT EXIST ON YT441 var removeThis = queueRef.child(nextSongkey);442 removeThis.remove()443 .then(function() {444 console.log("song remove went great.");445 var songBack = {446 cid: data[nextSongkey].cid,447 name: data[nextSongkey].name,448 type: data[nextSongkey].type,449 flagged: {450 date: Date.now(),451 code: 1452 }453 };454 queueRef.push(songBack);455 })456 .catch(function(error) {457 console.log("Song Remove failed: " + error.message);458 });459 talk("@" + theDJ.name + " you tried to play a broken song. Letting you play whatever is next in your queue instead... Clean up your queue please thanks.");460 setTimeout(function() {461 startSong(true); //try again with SAME DJ462 }, 3000);463 } else {464 console.log(result);465 if (!result.items.length) {466 var removeThis = queueRef.child(nextSongkey);467 removeThis.remove()468 .then(function() {469 console.log("song remove went great.");470 var songBack = {471 cid: data[nextSongkey].cid,472 name: data[nextSongkey].name,473 type: data[nextSongkey].type,474 flagged: {475 date: Date.now(),476 code: 2477 }478 };479 queueRef.push(songBack);480 })481 .catch(function(error) {482 console.log("Song Remove failed: " + error.message);483 });484 talk("@" + theDJ.name + " you tried to play a broken song. Letting you play whatever is next in your queue instead... Clean up your queue please thanks.");485 setTimeout(function() {486 startSong(true); //try again with SAME DJ487 }, 3000);488 } else if (ytVideoCheck(result)) {489 var removeThis = queueRef.child(nextSongkey);490 removeThis.remove()491 .then(function() {492 console.log("song remove went great.");493 var songBack = {494 cid: data[nextSongkey].cid,495 name: data[nextSongkey].name,496 type: data[nextSongkey].type,497 flagged: {498 date: Date.now(),499 code: 3500 }501 };502 queueRef.push(songBack);503 })504 .catch(function(error) {505 console.log("Song Remove failed: " + error.message);506 });507 talk("Hey @" + theDJ.name + ", looks like https://www.youtube.com/watch?v=" + data[nextSongkey].cid + " is blocked in the US. Letting you play whatever is next in your queue instead.");508 setTimeout(function() {509 startSong(true); //try again with SAME DJ510 }, 3000);511 } else if (ytAgeRestrictionCheck(result)) {512 var removeThis = queueRef.child(nextSongkey);513 removeThis.remove()514 .then(function() {515 console.log("song remove went great.");516 var songBack = {517 cid: data[nextSongkey].cid,518 name: data[nextSongkey].name,519 type: data[nextSongkey].type,520 flagged: {521 date: Date.now(),522 code: 7523 }524 };525 queueRef.push(songBack);526 })527 .catch(function(error) {528 console.log("Song Remove failed: " + error.message);529 });530 talk("Hey @" + theDJ.name + ", looks like https://www.youtube.com/watch?v=" + data[nextSongkey].cid + " is age restricted and can't be played outside of Youtube.com. Letting you play whatever is next in your queue instead.");531 setTimeout(function() {532 startSong(true); //try again with SAME DJ533 }, 3000);534 } else {535 var s2p = firebase.database().ref("songToPlay");536 var yargo = data[nextSongkey].name.split(" - ");537 var sartist = yargo[0];538 var stitle = yargo[1];539 var input = result.items[0].contentDetails.duration;540 var reptms = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/;541 var hours = 0,542 minutes = 0,543 seconds = 0,544 totalseconds;545 if (reptms.test(input)) {546 var matches = reptms.exec(input);547 if (matches[1]) hours = Number(matches[1]);548 if (matches[2]) minutes = Number(matches[2]);549 if (matches[3]) seconds = Number(matches[3]);550 totalseconds = hours * 3600 + minutes * 60 + seconds;551 } else {552 totalseconds = 10 * 60;553 }554 lastfm.duration = totalseconds;555 lastfm.songStart = Math.floor((new Date()).getTime() / 1000);556 if (songtimer != null) {557 clearTimeout(songtimer);558 songtimer = null;559 }560 songtimer = setTimeout(function() {561 songtimer = null;562 if (lastfm.key) lastfm.scrobble();563 }, (totalseconds * 1000) - 3000);564 if (!stitle) {565 stitle = sartist;566 if (result.items[0].snippet.channelTitle == "Various Artists - Topic") { // this youtube channel name is a lie...567 sartist = "Unknown";568 } else {569 sartist = result.items[0].snippet.channelTitle.replace(" - Topic", "");570 }571 } else if (sartist == "Unknown") {572 sartist = result.items[0].snippet.channelTitle.replace(" - Topic", "");573 }574 var thedate = new Date(result.items[0].snippet.publishedAt);575 var postedDate = thedate.getTime();576 var now = Date.now();577 var songInfo = {578 type: data[nextSongkey].type,579 cid: data[nextSongkey].cid,580 title: stitle,581 started: now,582 duration: totalseconds,583 url: "https://www.youtube.com/watch?v=" + data[nextSongkey].cid,584 artist: sartist,585 image: result.items[0].snippet.thumbnails.medium.url,586 djid: theDJ.id,587 postedDate: postedDate,588 djname: theDJ.name,589 key: nextSongkey590 };591 var clrs = "#fff";592 var textcol = "#fff";593 var moreColors = {};594 var colref = firebase.database().ref("colors");595 if (!songInfo.image) {596 songInfo.image = "img/idlogo.png";597 var clrs1 = {598 color: clrs,599 txt: textcol600 };601 colref.set(clrs1);602 colors = clrs1;603 } else {604 Vibrant.from(songInfo.image).getPalette(function(err, palette) {605 console.log(palette);606 if (palette.Vibrant) {607 clrs = palette.Vibrant.getHex();608 textcol = palette.Vibrant.getBodyTextColor();609 }610 if (palette.LightVibrant) {611 moreColors.lightVibrant = {612 color: palette.LightVibrant.getHex(),613 txt: palette.LightVibrant.getBodyTextColor()614 };615 }616 if (palette.DarkVibrant) {617 moreColors.darkVibrant = {618 color: palette.DarkVibrant.getHex(),619 txt: palette.DarkVibrant.getBodyTextColor()620 };621 }622 if (palette.Muted) {623 moreColors.muted = {624 color: palette.Muted.getHex(),625 txt: palette.Muted.getBodyTextColor()626 };627 }628 if (palette.LightMuted) {629 moreColors.lightMuted = {630 color: palette.LightMuted.getHex(),631 txt: palette.LightMuted.getBodyTextColor()632 };633 }634 if (palette.DarkMuted) {635 moreColors.darkMuted = {636 color: palette.DarkMuted.getHex(),637 txt: palette.DarkMuted.getBodyTextColor()638 };639 }640 var thecolors = {641 color: clrs,642 txt: textcol,643 altColors: moreColors644 };645 colref.set(thecolors);646 colors = thecolors;647 });648 }649 song = songInfo;650 s2p.set(songInfo);651 if (lastfm.key) lastfm.nowPlaying();652 var removeThis = queueRef.child(song.key);653 removeThis.remove()654 .then(function() {655 console.log("song remove went great.");656 var sname = song.artist + " - " + song.title;657 var songBack = {658 cid: song.cid,659 name: sname,660 type: song.type661 };662 queueRef.push(songBack);663 var adamString = song.artist + " - " + song.title;664 if (process.env.ADAM_URL) adam.np(adamString, theDJ.name, song.cid, song.type);665 })666 .catch(function(error) {667 console.log("Song Remove failed: " + error.message);668 });669 // set the timeout to move forward at end of song670 if (songTimeout != null) {671 clearTimeout(songTimeout);672 songTimeout = null;673 }674 songTimeout = setTimeout(function() {675 songTimeout = null;676 nextSong(); //NEEEEEEXT677 }, totalseconds * 1000);678 }679 }680 });681 } else if (data[nextSongkey].type == 2) {682 /*683begin sc check684 */685 request('https://api-widget.soundcloud.com/resolve?url=https%3A//api.soundcloud.com/tracks/' + data[nextSongkey].cid + '&format=json&client_id=LBCcHmRB8XSStWL6wKH2HPACspQlXg2P', function cbfunc(error, response, body) {686 //If call returned correctly, continue687 if (!error && response.statusCode == 200) {688 var tracks = [JSON.parse(body)];689 console.log(tracks);690 if (tracks) {691 if (tracks.length) {692 //exists!693 console.log(tracks[0]);694 var totalseconds = Math.floor(tracks[0].duration / 1000);695 lastfm.duration = totalseconds;696 lastfm.songStart = Math.floor((new Date()).getTime() / 1000);697 if (songtimer != null) {698 clearTimeout(songtimer);699 songtimer = null;700 }701 songtimer = setTimeout(function() {702 songtimer = null;703 if (lastfm.key) lastfm.scrobble();704 }, (totalseconds * 1000) - 3000);705 var s2p = firebase.database().ref("songToPlay");706 var yargo = data[nextSongkey].name.toString().split(" - ");707 var sartist = yargo[0];708 var stitle = yargo[1];709 if (sartist == "Unknown" && !stitle) {710 var cutetags = tracks[0].title.toString().split(" - ");711 var sartist = cutetags[0];712 var stitle = cutetags[1];713 }714 if (!stitle) {715 stitle = sartist;716 sartist = tracks[0].user.username;717 }718 if (sartist == "Unknown") sartist = tracks[0].user.username;719 var thedate = new Date(tracks[0].created_at);720 var postedDate = thedate.getTime();721 var now = Date.now();722 var songInfo = {723 type: data[nextSongkey].type,724 cid: data[nextSongkey].cid,725 title: stitle,726 started: now,727 url: tracks[0].permalink_url,728 duration: totalseconds,729 artist: sartist,730 image: tracks[0].artwork_url,731 postedDate: postedDate,732 djid: theDJ.id,733 djname: theDJ.name,734 key: nextSongkey735 };736 var colref = firebase.database().ref("colors");737 var clrs = "#fff";738 var textcol = "#fff";739 var moreColors = {};740 var colref = firebase.database().ref("colors");741 if (!songInfo.image) {742 songInfo.image = "img/idlogo.png";743 var clrs1 = {744 color: clrs,745 txt: textcol746 };747 colref.set(clrs1);748 colors = clrs1;749 } else {750 Vibrant.from(songInfo.image).getPalette(function(err, palette) {751 console.log(palette);752 if (palette.Vibrant) {753 clrs = palette.Vibrant.getHex();754 textcol = palette.Vibrant.getBodyTextColor();755 }756 if (palette.LightVibrant) {757 moreColors.lightVibrant = {758 color: palette.LightVibrant.getHex(),759 txt: palette.LightVibrant.getBodyTextColor()760 };761 }762 if (palette.DarkVibrant) {763 moreColors.darkVibrant = {764 color: palette.DarkVibrant.getHex(),765 txt: palette.DarkVibrant.getBodyTextColor()766 };767 }768 if (palette.Muted) {769 moreColors.muted = {770 color: palette.Muted.getHex(),771 txt: palette.Muted.getBodyTextColor()772 };773 }774 if (palette.LightMuted) {775 moreColors.lightMuted = {776 color: palette.LightMuted.getHex(),777 txt: palette.LightMuted.getBodyTextColor()778 };779 }780 if (palette.DarkMuted) {781 moreColors.darkMuted = {782 color: palette.DarkMuted.getHex(),783 txt: palette.DarkMuted.getBodyTextColor()784 };785 }786 var thecolors = {787 color: clrs,788 txt: textcol,789 altColors: moreColors790 };791 colref.set(thecolors);792 colors = thecolors;793 });794 }795 song = songInfo;796 s2p.set(songInfo);797 if (lastfm.key) lastfm.nowPlaying();798 var removeThis = queueRef.child(song.key);799 removeThis.remove()800 .then(function() {801 console.log("song remove went great.");802 var sname = song.artist + " - " + song.title;803 var songBack = {804 cid: song.cid,805 name: sname,806 type: song.type807 };808 queueRef.push(songBack);809 var adamString = song.artist + " - " + song.title;810 if (process.env.ADAM_URL) adam.np(adamString, theDJ.name, song.cid, song.type);811 })812 .catch(function(error) {813 console.log("Song Remove failed: " + error.message);814 });815 // set the timeout to move forward at end of song816 if (songTimeout != null) {817 clearTimeout(songTimeout);818 songTimeout = null;819 }820 songTimeout = setTimeout(function() {821 songTimeout = null;822 nextSong(); //NEEEEEEXT823 }, totalseconds * 1000);824 } else {825 //does not exist826 var removeThis = queueRef.child(nextSongkey);827 removeThis.remove()828 .then(function() {829 console.log("song remove went great.");830 var songBack = {831 cid: data[nextSongkey].cid,832 name: data[nextSongkey].name,833 type: data[nextSongkey].type,834 flagged: {835 date: Date.now(),836 code: 4837 }838 };839 queueRef.push(songBack);840 })841 .catch(function(error) {842 console.log("Song Remove failed: " + error.message);843 });844 talk("@" + theDJ.name + " you tried to play a broken song. Letting you play whatever is next in your queue instead... Clean up your queue please thanks.");845 setTimeout(function() {846 startSong(true); //try again with SAME DJ847 }, 3000);848 }849 } else {850 //does not exist851 var removeThis = queueRef.child(nextSongkey);852 removeThis.remove()853 .then(function() {854 console.log("song remove went great.");855 var songBack = {856 cid: data[nextSongkey].cid,857 name: data[nextSongkey].name,858 type: data[nextSongkey].type,859 flagged: {860 date: Date.now(),861 code: 5862 }863 };864 queueRef.push(songBack);865 })866 .catch(function(error) {867 console.log("Song Remove failed: " + error.message);868 });869 talk("@" + theDJ.name + " you tried to play a broken song. Letting you play whatever is next in your queue instead... Clean up your queue please thanks.");870 setTimeout(function() {871 startSong(true); //try again with SAME DJ872 }, 3000);873 }874 } else {875 // ERROR876 //does not exist877 var removeThis = queueRef.child(nextSongkey);878 removeThis.remove()879 .then(function() {880 console.log("song remove went great.");881 var songBack = {882 cid: data[nextSongkey].cid,883 name: data[nextSongkey].name,884 type: data[nextSongkey].type,885 flagged: {886 date: Date.now(),887 code: 5888 }889 };890 queueRef.push(songBack);891 })892 .catch(function(error) {893 console.log("Song Remove failed: " + error.message);894 });895 talk("@" + theDJ.name + " you tried to play a broken song. Letting you play whatever is next in your queue instead... There might also be a Soundcloud api issue right now...");896 setTimeout(function() {897 startSong(true); //try again with SAME DJ898 }, 3000);899 }900 });901 /*902end sc check903 */904 }905 } else {906 console.log("no songs in queue... remove this DJ");907 removePerson(theDJ.id);908 nextSong(true);909 console.log("ok?")910 }911 });912};913var printCard = function(userid) {914 if (cardGen) return;915 cardGen = userid;916 var now = Date.now();917 var cardCount = firebase.database().ref("cardCount");918 cardCount.once("value").then(function(snapshot) {919 var cdata = snapshot.val();920 if (!cdata) {921 //no cards yet922 totalCards = 1;923 cardCount.set(1);924 } else {925 totalCards = cdata + 1;926 cardCount.set(totalCards);927 }928 var thenum = Math.floor(Math.random() * 9) + 1;929 var tempWeighter = Math.floor(Math.random() * 100) + 1;930 var max;931 var min;932 if (tempWeighter <= 75) {933 max = 130;934 min = 110;935 } else if (tempWeighter <= 95) {936 max = 230;937 min = 131;938 } else {939 min = 231;940 max = 420;941 }942 var thetemp = Math.floor(Math.random() * (max - min)) + min;943 var cardData = {944 djname: theDJ.name,945 djid: theDJ.id,946 cid: song.cid,947 num: thenum,948 temp: thetemp,949 colors: colors,950 cardnum: totalCards,951 title: song.title,952 artist: song.artist,953 image: song.image,954 date: now,955 special: cardSpecial,956 owner: false957 };958 var ref = firebase.database().ref("cards");959 var cuteCard = ref.push(cardData, function() {960 cardForGrabs = cuteCard.key;961 talk("A new trading card has been printed. Type !grab to grab it for yourself!");962 });963 });964};965var giveCard = function(id, name) {966 if (!cardForGrabs) return;967 var cardid = cardForGrabs;968 cardForGrabs = null;969 var ref = firebase.database().ref("cards/" + cardid + "/owner");970 ref.set(id);971 talk("good job @" + name + " you got the card.", cardid);972};973var themevote = {974 active: false,975 params: null,976 go: function(txt, name) {977 themevote.active = true;978 var requiredVotes = 4;979 talk("@everyone " + name + " wants to change the theme to '" + txt + "'. Needs " + requiredVotes + " vote(s) to change. Say 1 to vote yes.");980 themevote.params = {981 votes: {},982 guy: name,983 required: requiredVotes,984 votingfor: txt985 };986 setTimeout(function() {987 themevote.end();988 }, 60 * 1000);989 },990 size: function(obj) {991 var size = 0;992 for (var key in obj) {993 if (obj.hasOwnProperty(key)) size++;994 }995 return size;996 },997 end: function() {998 var votes = themevote.size(themevote.params.votes);999 if (votes >= themevote.params.required) {1000 setTheme(themevote.params.votingfor);1001 talk(votes + " vote(s). The theme is now " + theme + "!");1002 } else if (theme) {1003 talk("Sorry. We're staying with " + theme + ".");1004 } else {1005 talk("Sorry. Not enough votes to set theme.");1006 }1007 themevote.params = null;1008 themevote.active = false;1009 }1010};1011var setTheme = function(themeIdea) {1012 theme = themeIdea;1013 var ref = firebase.database().ref("theme");1014 ref.set(theme);1015};1016var removeMe = function(id) {1017 for (var i = 0; i < queue.length; i++) {1018 if (queue[i].id == id) {1019 queue.splice(i, 1);1020 updateWaitlist();1021 return true;1022 }1023 }1024 for (var i = 0; i < table.length; i++) {1025 if (table[i].id == id) {1026 table.splice(i, 1);1027 if (queue.length) {1028 //now, let's fill the empty seat1029 var nextUp = queue[0];1030 table.push(nextUp);1031 queue.shift();1032 updateWaitlist();1033 }1034 updateTable();1035 if (i <= playDex) {1036 //shift spotlight to the left if a dj to the left of it leaves1037 playDex = playDex - 1;1038 updatePlaydex();1039 }1040 if (id == theDJ.id) {1041 nextSong();1042 }1043 return true;1044 }1045 }1046 return false;1047};1048var isAlphaNumeric = function(str) {1049 var code, i, len;1050 for (i = 0, len = str.length; i < len; i++) {1051 code = str.charCodeAt(i);1052 if (!(code > 47 && code < 58) && // numeric (0-9)1053 !(code > 64 && code < 91) && // upper alpha (A-Z)1054 !(code > 96 && code < 123)) { // lower alpha (a-z)1055 return false;1056 }1057 }1058 return true;1059};1060var removePerson = function(id) {1061 for (var i = 0; i < table.length; i++) {1062 if (table[i].id == id) {1063 table.splice(i, 1);1064 if (queue.length) {1065 //now, let's fill the empty seat1066 var nextUp = queue[0];1067 table.push(nextUp);1068 queue.shift();1069 }1070 if (i < playDex && i != 3) {1071 //shift spotlight to the left if a dj to the left of it leaves1072 playDex = playDex - 1;1073 }1074 return true;1075 }1076 }1077 return false;1078};1079var addCheck = function(id, hereCheck) {1080 if (!users[id].status && hereCheck) return 3;1081 for (var i = 0; i < queue.length; i++) {1082 if (queue[i].id == id) {1083 return 1;1084 }1085 }1086 for (var i = 0; i < table.length; i++) {1087 if (table[i].id == id) {1088 return 2;1089 }1090 }1091 return false;1092};1093var ref2 = firebase.database().ref("users");1094ref2.on('value', function(dataSnapshot) {1095 var okdata = dataSnapshot.val();1096 users = okdata;1097 if (botid) {1098 if (!okdata[botid].status) {1099 var statusref = firebase.database().ref("users/" + botid + "/status");1100 statusref.set(true);1101 }1102 }1103});1104var refCardSpecial = firebase.database().ref("cardSpecial");1105refCardSpecial.on('value', function(dataSnapshot) {1106 var resultActual = dataSnapshot.val();1107 if (resultActual) {1108 cardSpecial = resultActual;1109 } else {1110 cardSpecial = false;1111 }1112});1113var themepeek = firebase.database().ref("theme");1114themepeek.once("value").then(function(snapshot) {1115 var data = snapshot.val();1116 if (!data) {1117 theme = null;1118 } else {1119 theme = data;1120 }1121});1122var lookupChatData = function(chatID, callback) {1123 var chatData = firebase.database().ref("chatData/" + chatID);1124 chatData.once('value')1125 .then(function(snap) {1126 var data = snap.val();1127 return callback(data);1128 });1129};1130var ref = firebase.database().ref("chatFeed");1131ref.on('child_added', function(childSnapshot, prevChildKey) {1132 var feedData = childSnapshot.val();1133 var chatID = feedData.chatID;1134 if (!ignoreChats) {1135 lookupChatData(chatID, function(chatData) {1136 var namebo = chatData.id;1137 if (users[chatData.id]) {1138 if (users[chatData.id].username) namebo = users[chatData.id].username;1139 }1140 console.log(namebo + ": " + chatData.txt);1141 var matches = chatData.txt.match(/^(?:[!])(\w+)\s*(.*)/i);1142 if (matches && botid !== chatData.id && started) {1143 var command = matches[1].toLowerCase();1144 var args = matches[2];1145 console.log("COMMAND:", command);1146 if (command == "addme") {1147 var check = addCheck(chatData.id);1148 if (!check) {1149 var pson = {1150 name: namebo,1151 id: chatData.id,1152 plays: 01153 };1154 if (table.length >= 4) {1155 // table full. time to be on the waitlist now k1156 queue.push(pson);1157 talk(namebo + " added to waitlist. Length is now " + queue.length);1158 updateWaitlist();1159 updateLimit();1160 } else {1161 //table has room. add to table directly1162 if (table.length == 0) {1163 table.push(pson);1164 console.log(table);1165 playDex = 0;1166 startSong();1167 } else {1168 table.push(pson);1169 console.log(table);1170 updateTable();1171 updateLimit();1172 }1173 }1174 } else {1175 if (check == 1) {1176 talk("You are already in the waitlist.");1177 } else if (check == 2) {1178 talk("You are already on deck.");1179 }1180 }1181 } else if (command == "removeme") {1182 var removed = removeMe(chatData.id);1183 if (!removed) talk(namebo + ", you aren't even DJing...");1184 } else if (command == "removemeafter" || command == "removeafter" || command == "gottacatchmybus") {1185 var check = addCheck(chatData.id);1186 if (!check) {1187 talk(namebo + ", you aren't even DJing...");1188 } else if (check == 1) {1189 //user in waitlist1190 for (var i = 0; i < queue.length; i++) {1191 if (queue[i].id == chatData.id) {1192 queue[i].removeAfter = true;1193 updateWaitlist();1194 talk(namebo + ", I'll remove you after your next song.");1195 break;1196 }1197 }1198 } else if (check == 2) {1199 //user on deck1200 if (chatData.id == theDJ.id) {1201 // user is current dj1202 talk(namebo + ", I'll remove you at the end of this song.");1203 theDJ.removeAfter = true;1204 } else {1205 // user is not current dj1206 talk(namebo + ", I'll remove you after your next song.");1207 }1208 for (var i = 0; i < table.length; i++) {1209 if (table[i].id == chatData.id) {1210 table[i].removeAfter = true1211 updateTable();1212 break;1213 }1214 }1215 }1216 } else if (command == "dontremovemeafter" || command == "dontremoveafter" || command == "dontremoveme" || command == "dontremove") {1217 var check = addCheck(chatData.id);1218 if (!check) {1219 talk(namebo + ", you aren't even DJing...");1220 } else if (check == 1) {1221 //user in waitlist1222 for (var i = 0; i < queue.length; i++) {1223 if (queue[i].id == chatData.id) {1224 queue[i].removeAfter = false;1225 updateWaitlist();1226 talk(namebo + ", I will be sure to not remove you after your next track.");1227 break;1228 }1229 }1230 } else if (check == 2) {1231 //user on deck1232 if (chatData.id == theDJ.id) {1233 // user is current dj1234 talk(namebo + ", I will NOT remove you after this song.");1235 theDJ.removeAfter = false;1236 } else {1237 // user is not current dj1238 talk(namebo + ", I will NOT remove you after your next song.");1239 }1240 for (var i = 0; i < table.length; i++) {1241 if (table[i].id == chatData.id) {1242 table[i].removeAfter = false;1243 updateTable();1244 break;1245 }1246 }1247 }1248 } else if (command == "skip") {1249 if (users[chatData.id].mod || users[chatData.id].supermod || (chatData.id == theDJ.id)) {1250 nextSong();1251 }1252 } else if (command == "theme") {1253 if (theme) {1254 talk("The current theme is: " + theme);1255 } else {1256 talk("There is no theme at the moment. `!suggest` one if you'd like.")1257 }1258 } else if (command == "suggest") {1259 if (!themevote.active) {1260 themevote.go(args, namebo);1261 } else {1262 talk("We are already voting for " + themevote.params.votingfor + ". Let's wait for that to finish first.");1263 }1264 } else if (command == "settheme") {1265 if (users[chatData.id].supermod) {1266 if (args == "none") {1267 setTheme(null);1268 talk("There is no theme.");1269 } else {1270 setTheme(args);1271 talk("Theme has been set to: " + args);1272 }1273 } else {1274 talk("i will absolutely not do that " + namebo);1275 }1276 } else if (command == "printcard") {1277 if (users[chatData.id].supermod) {1278 printCard();1279 } else {1280 talk("i will absolutely not do that " + namebo);1281 }1282 } else if (command == "giftcard") {1283 if (chatData.card && theDJ) {1284 var ccref = firebase.database().ref("cards/" + chatData.card + "/owner");1285 ccref.set(theDJ.id);1286 talk(":white_check_mark: Card has been transfered from " + namebo + " to @" + theDJ.name);1287 if (chatData.id !== theDJ.id) cardGiftedThisSong = true;1288 }1289 } else if (command == "grab") {1290 if (cardForGrabs) giveCard(chatData.id, namebo);1291 } else if (command == "upbot") {1292 if (users[chatData.id].mod || users[chatData.id].supermod) {1293 var namebo2 = botid;1294 if (users[botid]) {1295 if (users[botid].username) namebo2 = users[botid].username;1296 }1297 var check = addCheck(botid);1298 if (!check) {1299 var pson = {1300 name: namebo2,1301 id: botid,1302 plays: 01303 };1304 if (table.length >= 4) {1305 // table full. time to be on the waitlist now k1306 queue.push(pson);1307 talk(namebo2 + " (that's me) added to waitlist. Length is now " + queue.length);1308 updateWaitlist();1309 updateLimit();1310 } else {1311 //table has room. add to table directly1312 talk("OK! I will DJ.");1313 if (table.length == 0) {1314 table.push(pson);1315 console.log(table);1316 playDex = 0;1317 startSong();1318 } else {1319 table.push(pson);1320 console.log(table);1321 updateTable();1322 updateLimit();1323 }1324 }1325 } else {1326 if (check == 1) {1327 talk("I am already in the waitlist.");1328 } else if (check == 2) {1329 talk("I am already on deck.");1330 }1331 }1332 }1333 } else if (command == "downbot") {1334 if (users[chatData.id].mod || users[chatData.id].supermod) {1335 var removed = removeMe(botid);1336 if (!removed) {1337 talk(namebo + ", I am not even DJing...");1338 } else {1339 talk("OK! I will not DJ.");1340 }1341 }1342 } else if (command == "screen" || command == "screendown") {1343 if (users[chatData.id].mod || users[chatData.id].supermod) {1344 talk("activating the screen.");1345 var thescreen = firebase.database().ref("thescreen");1346 thescreen.set(true);1347 }1348 } else if (command == "killscreen" || command == "screenup") {1349 if (users[chatData.id].mod || users[chatData.id].supermod) {1350 talk("ok.");1351 var thescreen = firebase.database().ref("thescreen");1352 thescreen.set(false)1353 }1354 } else if (command == "flag") {1355 if (users[chatData.id].mod || users[chatData.id].supermod) {1356 // do the flag thing1357 var code = false;1358 if (args == "broken" || args == "8") {1359 code = 8;1360 } else if (args == "bitrate" || args == "quality" || args == "incomplete" || args == "9") {1361 code = 9;1362 } else if (args == "offtheme" || args == "10") {1363 code = 10;1364 }1365 if (song.cid && queueRef) {1366 if (code) {1367 var flag = {1368 date: Date.now(),1369 code: code1370 };1371 queueRef.orderByChild('cid').equalTo(song.cid).once("value")1372 .then(function(snapshot) {1373 var data = snapshot.val();1374 if (data) {1375 for (var key in data) {1376 if (data[key].type == song.type) {1377 newData = data[key];1378 newData.flagged = flag;1379 queueRef.child(key).set(newData);1380 }1381 }1382 }1383 talk(":triangular_flag_on_post: FLAGGED (CODE " + code + ")");1384 });1385 } else {1386 talk("Please specify a valid flag reason (ex: !flag broken, !flag offtheme, !flag quality)");1387 }1388 } else {1389 talk("I just reloaded... I don't remember where in the DJ's lists I got this from.");1390 }1391 }1392 } else if (command == "remove") {1393 if (users[chatData.id].mod || users[chatData.id].supermod) {1394 var prsnToRemove = uidLookup(args);1395 if (prsnToRemove) {1396 var removed = removeMe(prsnToRemove);1397 if (!removed) talk("Can not remove " + args + " because they are not on the table or in the waitlist. Thanks.");1398 } else {1399 talk("who is that");1400 }1401 }1402 } else if (command == "add") {1403 if (users[chatData.id].mod || users[chatData.id].supermod) {1404 var prsnToAdd = uidLookup(args);1405 if (prsnToAdd) {1406 var check = addCheck(prsnToAdd, true);1407 if (!check) {1408 var pson = {1409 name: users[prsnToAdd].username,1410 id: prsnToAdd,1411 plays: 01412 };1413 if (table.length >= 4) {1414 // table full. time to be on the waitlist now k1415 queue.push(pson);1416 talk(users[prsnToAdd].username + " added to waitlist. Length is now " + queue.length);1417 updateWaitlist();1418 updateLimit();1419 } else {1420 //table has room. add to table directly1421 if (table.length == 0) {1422 table.push(pson);1423 console.log(table);1424 playDex = 0;1425 startSong();1426 } else {1427 table.push(pson);1428 console.log(table);1429 updateTable();1430 updateLimit();1431 }1432 }1433 } else {1434 if (check == 1) {1435 talk(users[prsnToAdd].username + " is already in the waitlist.");1436 } else if (check == 2) {1437 talk(users[prsnToAdd].username + " is already on deck.");1438 } else if (check == 3) {1439 talk(users[prsnToAdd].username + " is almost for sure not here.");1440 }1441 }1442 } else {1443 talk("who is that");1444 }1445 }1446 } else if (command == "become") {1447 talk("i do not remember how to do that.")1448 } else if (command == "wait") {1449 talk("wait");1450 } else if (command == "hot") {1451 firelevel.hot(chatData.id, namebo);1452 } else if (command == "storm") {1453 firelevel.storm(chatData.id, namebo);1454 } else if (command == "link") {1455 if (song) {1456 if (song.url) {1457 talk(song.url);1458 } else {1459 talk("Nothing is playing...");1460 }1461 }1462 } else if (command == "dance") {1463 if (cardGiftedThisSong) {1464 if (!robotsDancing) {1465 var danceref = firebase.database().ref("dance");1466 danceref.set(true);1467 robotsDancing = true;1468 talk(":artificial_satellite: D.A.N.C.E satellite: `GLOBAL DANCE SEQUENCE NO. 1 HAS BEEN INITIATED.`");1469 } else {1470 talk(":artificial_satellite: D.A.N.C.E satellite: `already broadcasting dance signal thanks`");1471 }1472 } else {1473 talk(":red_circle::satellite: unable to communicate with the D.A.N.C.E. satellite... if you gift the DJ a h0t new card, i'm sure they'll help boost your signal");1474 }1475 }1476 } else if (chatData.txt == "🔥" || chatData.txt == ":fire:") {1477 firelevel.hot(chatData.id, namebo);1478 } else if (chatData.txt == "🌧" || chatData.txt == ":cloud_with_rain:") {1479 firelevel.storm(chatData.id, namebo);1480 } else if (chatData.txt == "1" && themevote.active) {1481 themevote.params.votes[chatData.id] = 1;1482 }1483 });1484 }1485});1486var adam = {1487 np: function(song_name, dj, link, source) {1488 if (!process.env.ADAM_URL) return;1489 var thesource = "youtube";1490 if (source == 2) {1491 thesource = "soundcloud"1492 }1493 var adam_data = {1494 data: {1495 song_name: song_name,1496 dj: dj,1497 link: link,1498 source: thesource1499 }1500 };1501 // try posting to ADAM1502 var options = {1503 method: "POST",1504 url: process.env.ADAM_URL + "/new_song",1505 headers: {1506 "Content-Type": "text/html;charset=utf-8"1507 },1508 form: adam_data1509 };1510 request(options, function(err1, res1, body1) {1511 if (err1) console.log(err1);1512 console.log(body1);1513 if (body1) {1514 try {1515 var adm = JSON.parse(body1);1516 adam_last = adm;1517 console.log(adm);1518 if (adm) {1519 if (adm.track_name) {1520 //if no track name, adam tags bad... dont use.1521 if (adm.artist) {1522 if (adm.artist !== "Unknown") {1523 song.artist = adm.artist;1524 song.title = adm.track_name;1525 } else {1526 // if ADAM thinks the artist's name is UNKNOWN, overwrite with whatever hostbot came up with1527 adam.fix_tags(adm.track_id, song.artist + " - " + song.title);1528 }1529 }1530 } else {1531 //NO TRACK NAME... if we have enough data, let's tell ADAM what we know1532 adam.fix_tags(adm.track_id, song.artist + " - " + song.title);1533 }1534 if (adm.track_id) song.adamid = adm.track_id;1535 if (adm.playcount) song.playcount = adm.playcount;1536 var tagUpdate = firebase.database().ref("tagUpdate");1537 var tagFixData = {1538 adamData: adm,1539 cid: song.cid1540 };1541 // send tag update to clients1542 tagUpdate.set(tagFixData);1543 // update the dj's playlist with updated tags1544 queueRef.orderByChild('cid').equalTo(song.cid).once("value")1545 .then(function(snapshot) {1546 var data = snapshot.val();1547 if (data) {1548 for (var key in data) {1549 if (data[key].type == song.type) {1550 newData = data[key];1551 newData.name = song.artist + " - " + song.title;1552 queueRef.child(key).set(newData);1553 }1554 }1555 }1556 });1557 }1558 } catch (e) {1559 console.log(e);1560 }1561 }1562 });1563 },1564 fix_tags: function(adamid, args) {1565 var song_data = args.split(' - ')1566 if (song_data.length < 2) {1567 //bad format1568 } else {1569 var artist0 = song_data[0].replace(/&amp;/g, '&');1570 var title0 = song_data[1].replace(/&amp;/g, '&');1571 var adam_data = {1572 data: {1573 artist: artist0,1574 title: title0,1575 track_id: adamid1576 }1577 };1578 var options = {1579 method: "POST",1580 url: "https://adam-indie-discotheque.herokuapp.com//fix_tags",1581 headers: {1582 "Content-Type": "text/html;charset=utf-8"1583 },1584 form: adam_data1585 };1586 request(options, function(err1, res1, body1) {1587 if (err1) console.log(err1);1588 console.log(body1);1589 if (body1) {1590 var adm = JSON.parse(body1);1591 console.log("good tag fix");1592 }1593 });1594 }1595 }1596};1597var lastfm = {1598 sk: process.env.LASTFM_SESSIONKEY, //for last.fm user tt_discotheque1599 key: process.env.LASTFM_APIKEY,1600 songStart: null,1601 duration: null,1602 scrobble: function() {1603 var artist = song.artist;1604 var track = song.title;1605 var params = {1606 artist: artist,1607 track: track,1608 timestamp: lastfm.songStart,1609 api_key: lastfm.key,1610 sk: lastfm.sk,1611 method: "track.scrobble"1612 };1613 var sig = lastfm.getApiSignature(params);1614 params.api_sig = sig;1615 var request_url = 'https://ws.audioscrobbler.com/2.0/?' + serialize(params);1616 var request_url = 'https://ws.audioscrobbler.com/2.0/?' + serialize(params);1617 var options = {1618 method: "POST",1619 url: request_url1620 };1621 request(options, function(err1, res1, body1) {1622 if (err1) console.log(err1);1623 console.log(body1);1624 });1625 },1626 love: function() {1627 var artist = song.artist;1628 var track = song.title;1629 var params = {1630 artist: artist,1631 track: track,1632 api_key: lastfm.key,1633 sk: lastfm.sk,1634 method: "track.love"1635 };1636 var sig = lastfm.getApiSignature(params);1637 params.api_sig = sig;1638 var request_url = 'https://ws.audioscrobbler.com/2.0/?' + serialize(params);1639 var options = {1640 method: "POST",1641 url: request_url1642 };1643 request(options, function(err1, res1, body1) {1644 if (err1) console.log(err1);1645 console.log(body1);1646 });1647 },1648 _onAjaxError: function(xhr, status, error) {1649 console.log(xhr);1650 console.log(status);1651 console.log(error);1652 },1653 nowPlaying: function() {1654 var artist = song.artist;1655 var track = song.title;1656 var params = {1657 artist: artist,1658 track: track,1659 duration: lastfm.duration,1660 api_key: lastfm.key,1661 sk: lastfm.sk,1662 method: "track.updateNowPlaying"1663 };1664 var sig = lastfm.getApiSignature(params);1665 params.api_sig = sig;1666 var request_url = 'https://ws.audioscrobbler.com/2.0/?' + serialize(params);1667 var request_url = 'https://ws.audioscrobbler.com/2.0/?' + serialize(params);1668 var options = {1669 method: "POST",1670 url: request_url1671 };1672 request(options, function(err1, res1, body1) {1673 if (err1) console.log(err1);1674 console.log(body1);1675 });1676 },1677 getApiSignature: function(params) {1678 var i, key, keys, max, paramString;1679 keys = [];1680 paramString = "";1681 for (key in params) {1682 if (params.hasOwnProperty(key)) {1683 keys.push(key);1684 }1685 }1686 keys.sort();1687 for (i = 0, max = keys.length; i < max; i += 1) {1688 key = keys[i];1689 paramString += key + params[key];1690 }1691 return calcMD5(paramString + "e036a3702ce27990966173ce591fe14c");1692 }1693};1694setTimeout(function() {1695 ignoreChats = false;1696 console.log("Listening now.");1697}, 5000);1698setInterval(function() {1699 //keep stored chat history at 20 chats.1700 console.log("hi");1701 var ref = firebase.database().ref("chatFeed");1702 ref.once("value").then(function(snapshot) {1703 var data = snapshot.val();1704 var chats = [];1705 for (var key in data) {1706 chats.push({1707 feed: key,1708 data: data[key].chatID1709 });1710 }1711 console.log(chats.length);1712 if (chats.length > 20) {1713 var shave = chats.length - 21;1714 for (var i = 0; i <= shave; i++) {1715 console.log(chats[i]);1716 var removeThis = firebase.database().ref('chatFeed/' + chats[i].feed);1717 var removeData = firebase.database().ref('chatData/' + chats[i].data);1718 removeThis.remove();1719 removeData.remove();1720 }1721 }1722 });1723}, 5 * 60000);1724setInterval(function() {1725 // check every two minutes to see if people in the waitlist and table are here1726 // one warning if not here the first check, removed after second check.1727 for (var i = 0; i < table.length; i++) {1728 if (!users[table[i].id].status) {1729 if (!removalPending[table[i].id]) {1730 removalPending[table[i].id] = true;1731 console.log(table[i].id + " removal pending.");1732 } else {1733 removalPending[table[i].id] = null;1734 console.log(table[i].id + " removed");1735 removeMe(table[i].id);1736 }1737 }1738 }1739 for (var i = 0; i < queue.length; i++) {1740 if (!users[queue[i].id].status) {1741 if (!removalPending[queue[i].id]) {1742 removalPending[queue[i].id] = true;1743 console.log(queue[i].id + " removal pending.");1744 } else {1745 removalPending[queue[i].id] = null;1746 console.log(queue[i].id + " removed");1747 removeMe(queue[i].id);1748 }1749 }1750 }1751 var pendings = removalPending;1752 for (key in pendings) {1753 if (pendings.hasOwnProperty(key)) {1754 if (users[key].status && removalPending[key]) {1755 console.log("removal for " + key + " aborted");1756 removalPending[key] = null;1757 }1758 }1759 }1760}, 2 * 60000);1761/*1762 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message1763 * Digest Algorithm, as defined in RFC 1321.1764 * Copyright (C) Paul Johnston 1999 - 2000.1765 * Updated by Greg Holt 2000 - 2001.1766 * See http://pajhome.org.uk/site/legal.html for details.1767 */1768/*1769 * Convert a 32-bit number to a hex string with ls-byte first1770 */1771var hex_chr = "0123456789abcdef";1772function rhex(num) {1773 str = "";1774 for (j = 0; j <= 3; j++)1775 str += hex_chr.charAt((num >> (j * 8 + 4)) & 0x0F) +1776 hex_chr.charAt((num >> (j * 8)) & 0x0F);1777 return str;1778}1779/*1780 * Convert a string to a sequence of 16-word blocks, stored as an array.1781 * Append padding bits and the length, as described in the MD5 standard.1782 */1783function str2blks_MD5(str) {1784 nblk = ((str.length + 8) >> 6) + 1;1785 blks = new Array(nblk * 16);1786 for (i = 0; i < nblk * 16; i++) blks[i] = 0;1787 for (i = 0; i < str.length; i++)1788 blks[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8);1789 blks[i >> 2] |= 0x80 << ((i % 4) * 8);1790 blks[nblk * 16 - 2] = str.length * 8;1791 return blks;1792}1793/*1794 * Add integers, wrapping at 2^32. This uses 16-bit operations internally1795 * to work around bugs in some JS interpreters.1796 */1797function add(x, y) {1798 var lsw = (x & 0xFFFF) + (y & 0xFFFF);1799 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);1800 return (msw << 16) | (lsw & 0xFFFF);1801}1802/*1803 * Bitwise rotate a 32-bit number to the left1804 */1805function rol(num, cnt) {1806 return (num << cnt) | (num >>> (32 - cnt));1807}1808/*1809 * These functions implement the basic operation for each round of the1810 * algorithm.1811 */1812function cmn(q, a, b, x, s, t) {1813 return add(rol(add(add(a, q), add(x, t)), s), b);1814}1815function ff(a, b, c, d, x, s, t) {1816 return cmn((b & c) | ((~b) & d), a, b, x, s, t);1817}1818function gg(a, b, c, d, x, s, t) {1819 return cmn((b & d) | (c & (~d)), a, b, x, s, t);1820}1821function hh(a, b, c, d, x, s, t) {1822 return cmn(b ^ c ^ d, a, b, x, s, t);1823}1824function ii(a, b, c, d, x, s, t) {1825 return cmn(c ^ (b | (~d)), a, b, x, s, t);1826}1827/*1828 * Take a string and return the hex representation of its MD5.1829 */1830function calcMD5(str) {1831 x = str2blks_MD5(str);1832 a = 1732584193;1833 b = -271733879;1834 c = -1732584194;1835 d = 271733878;1836 for (i = 0; i < x.length; i += 16) {1837 olda = a;1838 oldb = b;1839 oldc = c;1840 oldd = d;1841 a = ff(a, b, c, d, x[i + 0], 7, -680876936);1842 d = ff(d, a, b, c, x[i + 1], 12, -389564586);1843 c = ff(c, d, a, b, x[i + 2], 17, 606105819);1844 b = ff(b, c, d, a, x[i + 3], 22, -1044525330);1845 a = ff(a, b, c, d, x[i + 4], 7, -176418897);1846 d = ff(d, a, b, c, x[i + 5], 12, 1200080426);1847 c = ff(c, d, a, b, x[i + 6], 17, -1473231341);1848 b = ff(b, c, d, a, x[i + 7], 22, -45705983);1849 a = ff(a, b, c, d, x[i + 8], 7, 1770035416);1850 d = ff(d, a, b, c, x[i + 9], 12, -1958414417);1851 c = ff(c, d, a, b, x[i + 10], 17, -42063);1852 b = ff(b, c, d, a, x[i + 11], 22, -1990404162);1853 a = ff(a, b, c, d, x[i + 12], 7, 1804603682);1854 d = ff(d, a, b, c, x[i + 13], 12, -40341101);1855 c = ff(c, d, a, b, x[i + 14], 17, -1502002290);1856 b = ff(b, c, d, a, x[i + 15], 22, 1236535329);1857 a = gg(a, b, c, d, x[i + 1], 5, -165796510);1858 d = gg(d, a, b, c, x[i + 6], 9, -1069501632);1859 c = gg(c, d, a, b, x[i + 11], 14, 643717713);1860 b = gg(b, c, d, a, x[i + 0], 20, -373897302);1861 a = gg(a, b, c, d, x[i + 5], 5, -701558691);1862 d = gg(d, a, b, c, x[i + 10], 9, 38016083);1863 c = gg(c, d, a, b, x[i + 15], 14, -660478335);1864 b = gg(b, c, d, a, x[i + 4], 20, -405537848);1865 a = gg(a, b, c, d, x[i + 9], 5, 568446438);1866 d = gg(d, a, b, c, x[i + 14], 9, -1019803690);1867 c = gg(c, d, a, b, x[i + 3], 14, -187363961);1868 b = gg(b, c, d, a, x[i + 8], 20, 1163531501);1869 a = gg(a, b, c, d, x[i + 13], 5, -1444681467);1870 d = gg(d, a, b, c, x[i + 2], 9, -51403784);1871 c = gg(c, d, a, b, x[i + 7], 14, 1735328473);1872 b = gg(b, c, d, a, x[i + 12], 20, -1926607734);1873 a = hh(a, b, c, d, x[i + 5], 4, -378558);1874 d = hh(d, a, b, c, x[i + 8], 11, -2022574463);1875 c = hh(c, d, a, b, x[i + 11], 16, 1839030562);1876 b = hh(b, c, d, a, x[i + 14], 23, -35309556);1877 a = hh(a, b, c, d, x[i + 1], 4, -1530992060);1878 d = hh(d, a, b, c, x[i + 4], 11, 1272893353);1879 c = hh(c, d, a, b, x[i + 7], 16, -155497632);1880 b = hh(b, c, d, a, x[i + 10], 23, -1094730640);1881 a = hh(a, b, c, d, x[i + 13], 4, 681279174);1882 d = hh(d, a, b, c, x[i + 0], 11, -358537222);1883 c = hh(c, d, a, b, x[i + 3], 16, -722521979);1884 b = hh(b, c, d, a, x[i + 6], 23, 76029189);1885 a = hh(a, b, c, d, x[i + 9], 4, -640364487);1886 d = hh(d, a, b, c, x[i + 12], 11, -421815835);1887 c = hh(c, d, a, b, x[i + 15], 16, 530742520);1888 b = hh(b, c, d, a, x[i + 2], 23, -995338651);1889 a = ii(a, b, c, d, x[i + 0], 6, -198630844);1890 d = ii(d, a, b, c, x[i + 7], 10, 1126891415);1891 c = ii(c, d, a, b, x[i + 14], 15, -1416354905);1892 b = ii(b, c, d, a, x[i + 5], 21, -57434055);1893 a = ii(a, b, c, d, x[i + 12], 6, 1700485571);1894 d = ii(d, a, b, c, x[i + 3], 10, -1894986606);1895 c = ii(c, d, a, b, x[i + 10], 15, -1051523);1896 b = ii(b, c, d, a, x[i + 1], 21, -2054922799);1897 a = ii(a, b, c, d, x[i + 8], 6, 1873313359);1898 d = ii(d, a, b, c, x[i + 15], 10, -30611744);1899 c = ii(c, d, a, b, x[i + 6], 15, -1560198380);1900 b = ii(b, c, d, a, x[i + 13], 21, 1309151649);1901 a = ii(a, b, c, d, x[i + 4], 6, -145523070);1902 d = ii(d, a, b, c, x[i + 11], 10, -1120210379);1903 c = ii(c, d, a, b, x[i + 2], 15, 718787259);1904 b = ii(b, c, d, a, x[i + 9], 21, -343485551);1905 a = add(a, olda);1906 b = add(b, oldb);1907 c = add(c, oldc);1908 d = add(d, oldd);1909 }1910 return rhex(a) + rhex(b) + rhex(c) + rhex(d);1911}1912var serialize = function(obj, prefix) {1913 var str = [];1914 for (var p in obj) {1915 if (obj.hasOwnProperty(p)) {1916 var k = prefix ? prefix + "[" + p + "]" : p,1917 v = obj[p];1918 str.push(typeof v == "object" ?1919 serialize(v, k) :1920 encodeURIComponent(k) + "=" + encodeURIComponent(v));1921 }1922 }1923 return str.join("&");1924}1925firebase.auth().signInWithEmailAndPassword(process.env.FIRETABLE_USER, process.env.FIRETABLE_PASS).catch(function(error) {1926 console.log(error);...

Full Screen

Full Screen

nobotee.js

Source:nobotee.js Github

copy

Full Screen

1/*-------------------------2nobotee3an in-browser plug.dj bot4written specifically for plug.dj/beats-2-455@mxew6--------------------------*/7if (typeof(nobotee) == "undefined") {8 var nobotee = {9 firetrucks: {},10 media: null,11 dj: null,12 imgblacklist: {},13 botact: null,14 commands: {},15 escortme:{},16 people:{},17 streak: 0,18 entered: null,19 reloadURL: "https://854.github.io/plugdj/nobotee.js",20 lastSeen: {},21 lastchatted: {},22 theme: null,23 skiptime:false,24 defaults:{25 autovt:true,26 time_lmt:true,27 mode:"notifications",28 cmmds:true29 },30 reloaded: false,31 advanced_settings:{32 greetings: false,33 customgreeting: null,34 themeingreeting: false,35 allowthemevotes:true,36 new_song_msg: false,37 tt_mode: false,38 tt_mode_queue: false,39 djlimit: null,40 autoafk: false,41 afklimit: 30,42 custom_gdoc: "1gu2gsY690NYpd9q5ewX9HO21HVacgukME-H9tPJX-WQ"43 },44 started:false45 };46 nobotee.entered = Date.now();47}48nobotee.version = "0.06.9";49// Redefine all nobotee functions, overwritting any code on reload..50nobotee.start = function() {51 console.log("nobotee version "+this.version+" starting..");52 nobotee.started = true;53 nobotee.storage.restore();54 nobotee.init();55};56nobotee.init = function(){57 console.log("nobotee init..");58 var self = this;59 self.ui.init();60 self.api.init();61 if (nobotee.reloaded){62 nobotee.api.newversion();63 nobotee.reloaded = false;64 } 65};66nobotee.ui = {67 self: this,68 init: function() {69 if (!$("#nobotee").length) {70 console.log("nobotee building ui..");71 nobotee.ui.build();72 }73 },74 build: function(){75 $( "body" ).prepend("<link id='nbtstyles' rel='stylesheet' href='https://854.github.io/plugdj/nbtstyles.css' type='text/css'><div id='nobotee'></div>");76 $( "#nobotee" ).append("<div id='nb_contents'><h2>nobotee "+nobotee.version+"</h2></div>");77 $( "#nb_contents" ).append("<div id='nb_screen'><ul class='nbscr' id='nbscr'></ul></div>");78 if (nobotee.defaults.time_lmt){79 var t_limit = "<span class='nb_on' id='nbsc_tmlmt'>on</span>";80 } else {81 var t_limit = "<span class='nb_off' id='nbsc_tmlmt'>off</span>";82 } if (nobotee.defaults.autovt){83 var a_vote = "<span class='nb_on' id='nbsc_autovt'>on</span>";84 } else {85 var a_vote = "<span class='nb_off' id='nbsc_autovt'>off</span>";86 } if (nobotee.defaults.cmmds){87 var c_mnds = "<span class='nb_on' id='nbsc_cmmds'>on</span>";88 } else {89 var c_mnds = "<span class='nb_off' id='nbsc_cmmds'>off</span>";90 }91 $( "#nb_contents" ).append("<div id='nb_buttons'><div class='nb_btnrow'><button onclick='nobotee.buttons.clear_sc()'>clear</button> &nbsp; <button onclick='nobotee.buttons.toggle_mode()'>mode</button> <span id='nbsc_mode'>"92 +nobotee.defaults.mode+"</span></div><div class='nb_btnrow'><button onclick='nobotee.buttons.toggle_time_lmt()'>time lmt</button> "93 +t_limit+" &nbsp; <button onclick='nobotee.buttons.toggle_auto_vote()'>auto vote</button> "94 +a_vote+"</div> <div class='nb_btnrow'><button onclick='nobotee.buttons.toggle_cmmnds()'>chat commands</button> "95 +c_mnds+"</div><div class='nb_btnrow'><a class='cutelink1' onclick='nobotee.buttons.open_settings()'>advanced settings</a></div></div>");96 console.log("nobotee ui built");97 $( "body" ).append("<div id='thesettingsnbt'><div style='display: block;' class='is-preview' id='dialog-container'>::before<div class='nbtsettings'><div class='catdog'>nobotee settings<a onclick='nobotee.buttons.close_settings()' class='nbtclosethat'>[close + save]</a><div style='clear:both;'></div></div><div class='dogcat'>fetching the settings...</div></div></div></div>");98 },99 loadsettings: function(){100 $( ".dogcat" ).html("<div class='newsetting'><input type='checkbox' id='greetonentry'> greet new user on entry</div><div class='newsetting'><input type='checkbox' id='greettheme'> include theme in greeting (if there is one)</div><div class='newsetting2'>custom greeting: <input name='customgreeting' placeholder='(will automatically be prefixed with @username)' id='customgreetingbox' type='text'/></div>");101 $( ".dogcat" ).append("<div class='nbtset_divide'></div><div class='newsetting'><input type='checkbox' id='announcenewsong'> announce new song playing in chat</div>");102 $( ".dogcat" ).append("<div class='nbtset_divide'></div><div class='newsetting'><input type='checkbox' id='allowthemevotes'> allow users to vote for theme using *suggest</div>");103 $( ".dogcat" ).append("<div class='nbtset_divide'></div><div class='newsetting2'>gdoc id: <input name='customgdoc' id='customgdocbox' placeholder='leave blank to reset to default id' type='text'/></div>");104 if (nobotee.advanced_settings.greetings){105 $('#greetonentry').prop('checked', true);106 }107 if (nobotee.advanced_settings.customgreeting){108 $( "#customgreetingbox" ).val(nobotee.advanced_settings.customgreeting);109 }110 if (nobotee.advanced_settings.custom_gdoc){111 $( "#customgdocbox" ).val(nobotee.advanced_settings.custom_gdoc);112 }113 if (nobotee.advanced_settings.themeingreeting){114 $('#greettheme').prop('checked', true);115 }116 if(nobotee.advanced_settings.new_song_msg){117 $('#announcenewsong').prop('checked', true);118 }119 if(nobotee.advanced_settings.allowthemevotes){120 $('#allowthemevotes').prop('checked', true);121 }122 },123 readsettings: function(){124 if ($('#greetonentry').prop('checked')){125 nobotee.advanced_settings.greetings = true;126 } else {127 nobotee.advanced_settings.greetings = false;128 }129 if ($('#greettheme').prop('checked')){130 nobotee.advanced_settings.themeingreeting = true;131 } else {132 nobotee.advanced_settings.themeingreeting = false;133 }134 if ($('#announcenewsong').prop('checked')){135 nobotee.advanced_settings.new_song_msg = true;136 } else {137 nobotee.advanced_settings.new_song_msg = false;138 }139 if ($('#allowthemevotes').prop('checked')){140 nobotee.advanced_settings.allowthemevotes = true;141 } else {142 nobotee.advanced_settings.allowthemevotes = false;143 }144 if ($( "#customgreetingbox" ).val() == ""){145 nobotee.advanced_settings.customgreeting = null;146 } else {147 nobotee.advanced_settings.customgreeting = $( "#customgreetingbox" ).val();148 }149 if ($( "#customgdocbox" ).val() == ""){150 nobotee.advanced_settings.custom_gdoc = "1gu2gsY690NYpd9q5ewX9HO21HVacgukME-H9tPJX-WQ";151 } else {152 nobotee.advanced_settings.custom_gdoc = $( "#customgdocbox" ).val();153 }154 nobotee.storage.save();155 nobotee.scr.updt("advanced settings have been saved.",1);156 },157 destroy: function(){158 $("#nobotee").remove();159 $("#nbtstyles").remove();160 $("#thesettingsnbt").remove();161 }162};163nobotee.scr ={164 init: function(){165 if (nobotee.defaults.mode == "notifications"){166 nobotee.scr.updt("defaults loaded.<br/> nobotee v"+nobotee.version+" is a go.",1);167 } else if (nobotee.defaults.mode == "cmmd_list"){168 nobotee.scr.gen_list();169 } else if (nobotee.defaults.mode == "song_length"){170 nobotee.scr.song_length();171 }172 },173 updt: function(txt,num){174 if ((nobotee.defaults.mode == "notifications") && (num == 1)){175 $( "#nbscr" ).append("<li class='nb_nt'>"+txt+"</li>");176 $('#nb_screen').scrollTop($('#nb_screen')[0].scrollHeight);177 }178 },179 clear: function(){180 $( "#nbscr" ).empty();181 },182 mode: function(mode){183 nobotee.defaults.mode = mode;184 $( "#nbsc_mode" ).replaceWith( "<span id='nbsc_mode'>"+mode+"</span>" );185 nobotee.scr.clear();186 if (mode == "cmmd_list"){187 nobotee.scr.gen_list();188 } else if (mode == "song_length"){189 nobotee.scr.song_length();190 }191 nobotee.storage.save();192 },193 gen_list: function(){194 //TODO: automate this195 var gdoc_commands = nobotee.api.listcommands();196 var the_list = "public commands<br/>------<br/>*help<br/>*img [something]<br/>*limit<br/>*theme<br/>*removemeafter [#]</br>*idle [username]<br/>*lastchatted [username]<br/>*streak<br/>*suggest [topic idea]<br/>*songlink<br/>"+gdoc_commands+"------------<br/>bouncer+ commands<br/>------<br/>*togglelimit<br/>*toggleautovote<br/>*settheme<br/>*notheme<br/>*gdoc";197 $( "#nbscr" ).html("<li class='nb_nt'>"+the_list+"</li>");198 },199 song_length: function(){200 var length = Math.round(nobotee.media.duration);201 var dj = nobotee.dj.username;202 if (length > 320) {203 var descrip = "WAY TOO LONG. SKIPPING REQUIRED.";204 } else if ((length > 183) && (length <= 320)) {205 var descrip = "TOO LONG. No action required.";206 } else if ((length > 120) && (length <= 183)) {207 var descrip = "Ok.";208 } else if ((length > 60) && (length <= 120)) {209 var descrip = "Perfect!";210 } else if (length <= 60) {211 var descrip = "BONUSSS!";212 }213 var report = "DJ: "+dj+"<br/>LENGTH: "+nobotee.secondsToTime(length)+"<br/>"+descrip;214 $( "#nbscr" ).html("<li class='nb_nt'>"+report+"</li>");215 }216};217nobotee.buttons ={218 clear_sc: function(){219 nobotee.scr.clear();220 },221 toggle_mode: function(){222 if (nobotee.defaults.mode == "notifications"){223 nobotee.scr.mode("song_length");224 } else if (nobotee.defaults.mode == "song_length"){225 nobotee.scr.mode("cmmd_list");226 } else if (nobotee.defaults.mode == "cmmd_list"){227 nobotee.scr.mode("notifications");228 }229 nobotee.storage.save();230 },231 toggle_time_lmt: function(){232 if (nobotee.defaults.time_lmt){233 nobotee.defaults.time_lmt = false;234 $( "#nbsc_tmlmt" ).replaceWith( "<span class='nb_off' id='nbsc_tmlmt'>off</span>" );235 } else {236 nobotee.defaults.time_lmt = true;237 $( "#nbsc_tmlmt" ).replaceWith( "<span class='nb_on' id='nbsc_tmlmt'>on</span>" );238 }239 nobotee.storage.save();240 },241 toggle_auto_vote: function(){242 if (nobotee.defaults.autovt){243 nobotee.defaults.autovt = false;244 $( "#nbsc_autovt" ).replaceWith( "<span class='nb_off' id='nbsc_autovt'>off</span>" );245 } else {246 nobotee.defaults.autovt = true;247 $( "#nbsc_autovt" ).replaceWith( "<span class='nb_on' id='nbsc_autovt'>on</span>" );248 }249 nobotee.storage.save();250 },251 toggle_cmmnds: function(){252 if (nobotee.defaults.cmmds){253 nobotee.defaults.cmmds = false;254 $( "#nbsc_cmmds" ).replaceWith( "<span class='nb_off' id='nbsc_cmmds'>off</span>" );255 } else {256 nobotee.defaults.cmmds = true;257 $( "#nbsc_cmmds" ).replaceWith( "<span class='nb_on' id='nbsc_cmmds'>on</span>" );258 }259 nobotee.storage.save();260 },261 close_settings: function(){262 nobotee.ui.readsettings();263 $( "#thesettingsnbt" ).hide();264 },265 open_settings: function(){266 $( "#thesettingsnbt" ).show();267 nobotee.ui.loadsettings();268 }269};270nobotee.api = {271 self:this,272 init:function() {273 console.log("nobotee setting up event listeners..");274 nobotee.api.populate_media();275 if (nobotee.advanced_settings.custom_gdoc) nobotee.commands = nobotee.api.get_commands();276 API.on(API.CHAT, nobotee.api.newchat);277 API.on(API.ADVANCE, nobotee.api.newsong);278 API.on(API.USER_JOIN, nobotee.api.newuser);279 API.on(API.USER_LEAVE, nobotee.api.newexit);280 API.on(API.VOTE_UPDATE, nobotee.api.newvote);281 API.on(API.GRAB_UPDATE, nobotee.api.newheart);282 API.on(API.WAIT_LIST_UPDATE, nobotee.api.waitlistupdate);283 nobotee.scr.init();284 },285 populate_media: function(){286 var media1 = API.getMedia();287 var dj1 = API.getDJ();288 var thebot = API.getUser();289 nobotee.botact = thebot;290 nobotee.media = media1;291 nobotee.dj = dj1;292 },293 woot: function(){294 $("#woot").click();295 },296 waitlistupdate: function(users){297 //298 },299 newversion: function(){300 nobotee.talk("nobotee is now v"+nobotee.version);301 },302 newchat: function(data){303 console.log(data);304 var name = data.un;305 var id = data.uid;306 var msg = data.message;307 var lan = data.language;308 nobotee.timer.justSaw(id,true);309 var matches = data.message.match(/^(?:[!*#\/])(\w+)\s*(.*)/);310 if (matches && nobotee.defaults.cmmds) {311 var command = matches[1];312 var args = matches[2];313 if ((nobotee.commands[command]) && (command !== "gdoc") && (id !== nobotee.botact.id)){314 nobotee.talk(nobotee.commands[command]);315 } else if (command == "help"){316 nobotee.talk("help");317 } else if (command == "streak"){318 var response = "room streak is "+nobotee.streak;319 if (!args){320 if (nobotee.people[id]) response += " | "+name+" streak is "+nobotee.people[id];321 } else {322 var prsn = nobotee.getid(args);323 if (prsn){324 if (nobotee.people[prsn]) response += " | "+args+" streak is "+nobotee.people[prsn];325 }326 }327 nobotee.talk(response);328 } else if (command == "theme"){329 if (nobotee.theme){330 nobotee.talk("current theme is '"+nobotee.theme+"'");331 } else {332 nobotee.talk("there is no theme at the moment");333 }334 } else if (command == "img"){ 335 if (args){336 if (!nobotee.imgblacklist[id]) nobotee.api.get_img(args,name);337 }338 } else if (command == "songlink"){339 nobotee.api.song_link(name);340 } else if (command == "removemeafter"){341 var isdjing = nobotee.api.isdjing(id);342 if (isdjing){343 if (id == nobotee.dj.id){344 var playcount = 1;345 } else {346 var playcount = 0;347 }348 if (args){349 var goal = parseInt(args);350 nobotee.escortme[id] = {351 name: name,352 plays: playcount,353 goal: goal354 };355 } else {356 nobotee.escortme[id] = {357 name: name,358 plays: playcount,359 goal: 1360 };361 }362 if (playcount == 1 && nobotee.escortme[id].goal == 1){363 nobotee.talk(nobotee.atmessage(name)+" i'll take you down after this song.");364 } else {365 nobotee.talk(nobotee.atmessage(name)+" i'll take you down after "+nobotee.escortme[id].goal+" plays");366 }367 } else {368 nobotee.talk(nobotee.atmessage(name)+" you aren't even djing");369 }370 } else if (command == "dontremoveme"){371 if (nobotee.escortme[id]){372 delete nobotee.escortme[id];373 nobotee.talk(nobotee.atmessage(name)+" ok I won't.");374 } else {375 nobotee.talk(nobotee.atmessage(name)+" I didn't plan on it");376 }377 } else if (command == "idle"){378 if (args){379 nobotee.timer.idleCheck(args);380 } else {381 nobotee.timer.djCheck();382 }383 } else if (command == "lastchatted"){384 if (args){385 nobotee.timer.idleCheck(args,true);386 } else {387 nobotee.timer.djCheck(true);388 }389 } else if ((command == "suggest") && (args) && (nobotee.advanced_settings.allowthemevotes)){390 if (!nobotee.themevote.active){391 nobotee.themevote.go(args,name);392 } else {393 nobotee.talk("we are already voting for '"+nobotee.themevote.params.votingfor+"'. let's wait for that to finish first.");394 }395 } else if (command == "limit"){396 if (nobotee.defaults.time_lmt){397 nobotee.talk("there is a limit to song length. try to keep it under 2:45.");398 } else {399 nobotee.talk("there is no limit to song length at this time.");400 }401 //moderator commands402 } else if (API.hasPermission(id, API.ROLE.BOUNCER)){403 if (command == "togglelimit"){404 if (nobotee.defaults.time_lmt){405 nobotee.defaults.time_lmt = false;406 nobotee.talk("the song length limit is now off");407 $( "#nbsc_tmlmt" ).replaceWith( "<span class='nb_off' id='nbsc_tmlmt'>off</span>" );408 } else {409 nobotee.defaults.time_lmt = true;410 nobotee.talk("the song length limit is now on");411 $( "#nbsc_tmlmt" ).replaceWith( "<span class='nb_on' id='nbsc_tmlmt'>on</span>" );412 }413 nobotee.storage.save();414 } else if (command == "toggleautovote"){415 if (nobotee.defaults.autovt){416 nobotee.defaults.autovt = false;417 nobotee.talk("autovote is now off");418 $( "#nbsc_autovt" ).replaceWith( "<span class='nb_off' id='nbsc_autovt'>off</span>" );419 } else {420 nobotee.defaults.autovt = true;421 nobotee.talk("autovote has been activated");422 $( "#nbsc_autovt" ).replaceWith( "<span class='nb_on' id='nbsc_autovt'>on</span>" );423 }424 nobotee.storage.save();425 } else if (command == "settheme"){426 if (args){427 nobotee.theme = args;428 nobotee.talk("the theme has been set to "+args);429 nobotee.storage.save();430 }431 } else if (command == "resetstreaks"){432 nobotee.people = {};433 nobotee.streak = 0;434 nobotee.talk("user streaks and room streaks reset");435 nobotee.storage.save();436 } else if (command == "noimg"){437 if (args){438 var theid = nobotee.getid(args);439 if (theid){440 if (nobotee.imgblacklist[theid]){441 nobotee.talk(args+" is already blacklisted from the img command");442 } else {443 nobotee.imgblacklist[theid] = 1;444 nobotee.storage.save();445 nobotee.talk(args+" can't use the img command anymore.")446 }447 } else {448 nobotee.talk("who is that");449 }450 }451 } else if (command == "nonoimg"){452 if (args){453 var theid = nobotee.getid(args);454 if (theid){455 if (nobotee.imgblacklist[theid]){456 delete nobotee.imgblacklist[theid];457 nobotee.storage.save();458 nobotee.talk(args+" can use the img command again");459 } else {460 nobotee.imgblacklist[theid] = args;461 nobotee.storage.save();462 nobotee.talk(args+" can already use the img command");463 }464 } else {465 nobotee.talk("who is that");466 }467 }468 } else if (command == "reload"){469 nobotee.reloaded = true;470 nobotee.cleanUp();471 setTimeout(function() {472 var script=document.createElement('script');473 script.id='nbtbot';474 script.type='text/javascript';475 script.src=nobotee.reloadURL;476 document.body.appendChild(script);477 }, 2 * 1000);478 } else if (command == "notheme"){479 nobotee.theme = null;480 nobotee.talk("there is no theme");481 nobotee.storage.save();482 } else if (command == "gdoc"){483 if (nobotee.advanced_settings.custom_gdoc){484 nobotee.commands = nobotee.api.get_commands();485 nobotee.talk("google doc commands have been reloaded.");486 } else {487 nobotee.talk("no gdoc specified");488 }489 }490 } 491 //end of commands492 } else if (msg == "1" && nobotee.themevote.active){493 nobotee.themevote.params.votes[id] = 1;494 } else if ((msg.match(/:fire:/)) && (nobotee.defaults.cmmds)){495 nobotee.api.firetruck(id);496 }497 },498 newsong: function(data){499 console.log(data);500 if (data.media){501 if (nobotee.dj) var prevdj = nobotee.dj;502 nobotee.media = data.media;503 nobotee.dj = data.dj;504 nobotee.firetrucks = {};505 nobotee.skiptime = false;506 if (nobotee.defaults.autovt){507 nobotee.api.woot();508 }509 var fair_game = true;510 if (prevdj){511 if (nobotee.escortme[prevdj.id]){512 if (nobotee.escortme[prevdj.id].plays >= nobotee.escortme[prevdj.id].goal){513 API.moderateRemoveDJ(prevdj.id);514 nobotee.scr.updt(prevdj.username+" was escorted upon request after playing "+nobotee.escortme[prevdj.id].plays+" songs",1);515 delete nobotee.escortme[prevdj.id];516 }517 }518 }519 if (nobotee.escortme[data.dj.id]){520 nobotee.escortme[data.dj.id].plays++;521 }522 if (nobotee.advanced_settings.new_song_msg){523 nobotee.talk("/me :cd: "+nobotee.dj.username+" started playing '"+nobotee.media.title+"' by "+nobotee.media.author);524 }525 if (nobotee.defaults.mode == "song_length") nobotee.scr.song_length();526 if (nobotee.defaults.time_lmt){527 var length = data.media.duration;528 var dj = data.dj.username;529 var song = data.media.title;530 if (length > 320) {531 nobotee.talk(nobotee.atmessage(dj)+", your song is wayy too long. Please skip.");532 nobotee.skiptime = true;533 fair_game = false;534 setTimeout(function () {535 if (nobotee.skiptime == true) {536 API.moderateForceSkip();537 nobotee.scr.updt(dj+" played '"+song+"' and was skipped due to song time limit.",1);538 }539 }, 5000);540 } else if ((length > 183) && (length <= 320)) {541 nobotee.talk(nobotee.atmessage(dj)+", TOO LONG!");542 fair_game = false;543 } else if ((length > 120) && (length <= 183)) {544 //545 } else if ((length > 60) && (length <= 120)) {546 //547 } else if (length <= 60) {548 nobotee.talk(nobotee.atmessage(dj)+", BONUS :sparkles:");549 }550 var old_dj = 0;551 var old_streak = 0;552 if (!nobotee.people[data.dj.id]){553 if (fair_game){554 nobotee.people[data.dj.id] = 1;555 } else {556 old_dj = 0;557 nobotee.people[data.dj.id] = 0;558 }559 } else {560 if (fair_game){561 nobotee.people[data.dj.id] = nobotee.people[data.dj.id] + 1;562 } else {563 old_dj = nobotee.people[data.dj.id];564 nobotee.people[data.dj.id] = 0;565 }566 }567 if (fair_game){568 nobotee.streak++;569 } else {570 old_streak = nobotee.streak;571 nobotee.streak = 0;572 nobotee.api.display_streak(old_streak,old_dj);573 }574 nobotee.storage.save();575 }576 }577 },578 newuser: function(data){579 nobotee.timer.justSaw(data.id);580 if (nobotee.advanced_settings.greetings){581 var response = nobotee.atmessage(data.username)582 if (nobotee.advanced_settings.customgreeting){583 response += " "+nobotee.advanced_settings.customgreeting;584 } else {585 response += " hello.";586 }587 if (nobotee.advanced_settings.themeingreeting && nobotee.theme){588 response += " Current theme is "+nobotee.theme;589 }590 setTimeout(function() {591 nobotee.talk(response);592 }, 2 * 1000);593 }594 },595 newexit: function(data){596 //597 },598 newvote: function(data){599 nobotee.timer.justSaw(data.user.id);600 },601 newheart: function(data){602 nobotee.timer.justSaw(data.user.id);603 },604 get_commands: function(){605 var commands = {};606 $.ajax({607 dataType: "jsonp",608 url: "https://spreadsheets.google.com/feeds/list/"+nobotee.advanced_settings.custom_gdoc+"/od6/public/values?alt=json-in-script", 609 success: function (data){610 for (var command in data.feed.entry){611 commands[data.feed.entry[command].gsx$command.$t] = data.feed.entry[command].gsx$response.$t;612 }613 }614 });615 return commands;616 },617 song_link: function(name){618 var data = nobotee.media;619 if (data.format == 1){620 nobotee.talk(nobotee.atmessage(name)+" https://www.youtube.com/watch?v="+data.cid);621 } else if (data.format == 2) {622 $.ajax({623 dataType: "jsonp",624 url: "https://api.soundcloud.com/tracks/"+data.cid+".json?client_id=27028829630d95b0f9d362951de3ba2c", 625 success: function (response){626 nobotee.talk(nobotee.atmessage(name)+" "+response.permalink_url);627 }628 });629 }630 },631 get_img: function(term,name){632 $.ajax({633 dataType: "jsonp",634 type : "GET",635 url: "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q="+encodeURIComponent(term)+"&jsoncallback=formatted", 636 success: function (formatted){637 if (formatted.responseData.results.length){ 638 var alltheimages = formatted.responseData.results;639 var theimage = alltheimages[Math.floor(Math.random() * (alltheimages.length))];640 nobotee.talk(nobotee.atmessage(name)+" "+theimage.unescapedUrl);641 } else {642 nobotee.talk(nobotee.atmessage(name)+" what is that?");643 }644 }645 });646 },647 firetruck: function(id){648 console.log("fired");649 if (!nobotee.firetrucks[id]){650 nobotee.firetrucks[id] = 1;651 }652 var thelength = nobotee.themevote.size(nobotee.firetrucks);653 var trucks = "";654 var i;655 for (i = 0; i < thelength; ++i) {656 trucks += ":fire_engine: ";657 }658 nobotee.talk(trucks);659 },660 display_streak: function(room,user){661 setTimeout(function() {662 nobotee.talk("room streak was :"+room+" | dj streak was:"+user);663 }, 2 * 1000);664 },665 isdjing: function(id){666 var thewaitlist = API.getWaitList();667 var isdjing = false;668 var i;669 for (i = 0; i < thewaitlist.length; ++i) {670 if (id == thewaitlist[i].id) isdjing = true;671 }672 if (id == nobotee.dj.id) isdjing = true;673 return isdjing;674 },675 listcommands: function(hats){676 var obj = nobotee.commands;677 var str = "";678 for (var key in obj) {679 if (hats){680 if (obj.hasOwnProperty(key)) str += "*"+key+", ";681 } else {682 if (obj.hasOwnProperty(key)) str += "*"+key+"<br/>";683 }684 }685 if (hats) str = str.substring(0, str.length - 2);686 return str;687 }688};689nobotee.timer = {690 getTime : function (userId,chat) {691 if (chat){692 var last = nobotee.lastchatted[userId];693 } else {694 var last = nobotee.lastSeen[userId];695 }696 var age_ms = Date.now() - last;697 var age_s = Math.floor(age_ms / 1000);698 return age_s;699 },700 defaultTime: function (){701 var last = nobotee.entered;702 var age_ms = Date.now() - last;703 var age_s = Math.floor(age_ms / 1000);704 return age_s;705 },706 justSaw : function (uid,chat) {707 var rightNow = Date.now();708 nobotee.lastSeen[uid] = rightNow;709 if (chat) nobotee.lastchatted[uid] = rightNow;710 },711 idleCheck: function(username,chat){712 var id = nobotee.getid(username);713 if (id){714 if (chat){715 if (nobotee.lastchatted[id]){716 var scnds = nobotee.timer.getTime(id,true);717 var aprox = "";718 } else {719 var scnds = nobotee.timer.defaultTime();720 var aprox = "> ";721 }722 } else {723 if (nobotee.lastSeen[id]){724 var scnds = nobotee.timer.getTime(id);725 var aprox = "";726 } else {727 var scnds = nobotee.timer.defaultTime();728 var aprox = "> ";729 }730 }731 var final_time = nobotee.secondsToTime(scnds);732 nobotee.talk(username+": "+aprox+""+final_time);733 } else {734 nobotee.talk("that user does not appear to be here");735 }736 },737 djCheck: function(chat){738 var id = nobotee.dj.id;739 if(chat){740 if (nobotee.lastchatted[id]){741 var scnds = nobotee.timer.getTime(id,true);742 var aprox = "";743 } else {744 var scnds = nobotee.timer.defaultTime();745 var aprox = "> ";746 }747 } else {748 if (nobotee.lastSeen[id]){749 var scnds = nobotee.timer.getTime(id);750 var aprox = "";751 } else {752 var scnds = nobotee.timer.defaultTime();753 var aprox = "> ";754 }755 }756 var final_time = nobotee.secondsToTime(scnds);757 nobotee.talk(nobotee.dj.username+": "+aprox+""+final_time);758 }759};760nobotee.talk= function(txt){761 API.sendChat(txt);762};763nobotee.getid = function(username){764 var i;765 var users = API.getUsers();766 var id = null;767 for (i = 0; i < users.length; ++i) {768 if (username == users[i].username){769 id = users[i].id;770 break;771 }772 }773 return id;774};775nobotee.getobj = function(username){776 var i;777 var users = API.getUsers();778 var obj = null;779 for (i = 0; i < users.length; ++i) {780 if (username == users[i].username){781 obj = users[i];782 break;783 }784 }785 return obj;786};787nobotee.atmessage = function (username) {788 if (typeof username !== "undefined") { 789 if (username.substring(0, 1).match(/^\@$/)){790 var atname = username;791 } else {792 var atname = "@"+username;793 }794 return atname;795 }796};797nobotee.secondsToTime = function(secs) {798 var hours = Math.floor(secs / (60 * 60));799 var divisor_for_minutes = secs % (60 * 60);800 var minutes = Math.floor(divisor_for_minutes / 60);801 var divisor_for_seconds = divisor_for_minutes % 60;802 var seconds = Math.ceil(divisor_for_seconds);803 var response = "";804 if (hours > 0) response += hours+"h ";805 response += minutes + "m " + seconds+"secs"806 return response;807};808nobotee.formatdate = function(d,include_time){809 var offset1 = d.getTimezoneOffset() / 60;810 var offset = - offset1;811 var month = d.getMonth() + 1;812 var day = d.getDate();813 var year = d.getFullYear();814 var hours = d.getHours() + 1;815 var minutes = d.getMinutes() + 1;816 if (minutes <= 9) minutes = "0" + minutes;817 if (hours >= 13){ var ampm = "pm"; var newhours = hours - 12; } else { var ampm = "am"; var newhours = hours;}818 var str = month+"/"+day+"/"+year;819 if (include_time) str += " @ "+newhours+":"+minutes+""+ampm+" (UTC"+offset+")"820 return str;821};822nobotee.themevote = {823 active: false,824 params: null,825 go: function(txt,name){826 nobotee.themevote.active = true;827 var usrs = API.getUsers();828 var requiredVotes = Math.floor((usrs.length - 1) / 2);829 if (requiredVotes > 4) {830 requiredVotes = 4;831 } else if (requiredVotes < 1){832 requiredVotes = 1;833 }834 nobotee.talk(name+" wants to change the theme to '"+txt+"'. needs "+requiredVotes+" vote(s) to change. say 1 to vote yes."); 835 nobotee.themevote.params = {836 votes: {},837 guy: name,838 required: requiredVotes,839 votingfor: txt840 };841 setTimeout(function() {842 nobotee.themevote.end();843 }, 30 * 1000);844 },845 size: function(obj) {846 var size = 0;847 for (var key in obj) {848 if (obj.hasOwnProperty(key)) size++;849 }850 return size;851 },852 end: function() {853 var votes = nobotee.themevote.size(nobotee.themevote.params.votes);854 if (votes >= nobotee.themevote.params.required) {855 nobotee.theme = nobotee.themevote.params.votingfor;856 nobotee.talk(votes + " vote(s). the theme is now '" + nobotee.theme + "'!");857 nobotee.storage.save();858 nobotee.scr.updt("theme was changed to '"+nobotee.theme+"' due to a vote started by "+nobotee.themevote.params.guy,1);859 } else if (nobotee.theme) {860 nobotee.talk("sorry. we're staying with '" + nobotee.theme + "'");861 } else {862 nobotee.talk("sorry. not enough votes to set theme.");863 }864 nobotee.themevote.params = null;865 nobotee.themevote.active = false;866 }867};868nobotee.cleanUp = function(){869 API.off(API.CHAT, nobotee.api.newchat);870 API.off(API.ADVANCE, nobotee.api.newsong);871 API.off(API.USER_JOIN, nobotee.api.newuser);872 API.off(API.USER_LEAVE, nobotee.api.newexit);873 API.off(API.VOTE_UPDATE, nobotee.api.newvote);874 API.off(API.CURATE_UPDATE, nobotee.api.newheart);875 API.off(API.WAIT_LIST_UPDATE, nobotee.api.waitlistupdate);876 nobotee.ui.destroy();877 $("#nbtbot").remove();878 nobotee.started = false;879};880nobotee.storage = {881 save: function(){882 var save_file = {883 defaults: nobotee.defaults,884 imgblacklist: nobotee.imgblacklist,885 theme: nobotee.theme,886 users: nobotee.people,887 streak: nobotee.streak,888 advanced_settings: nobotee.advanced_settings889 };890 var preferences = JSON.stringify(save_file);891 localStorage["nobotee"] = preferences;892 },893 restore: function(){894 var favorite = localStorage["nobotee"];895 if (!favorite) {896 return;897 }898 var preferences = JSON.parse(favorite);899 nobotee.defaults = preferences.defaults;900 nobotee.theme = preferences.theme;901 if (preferences.imgblacklist) nobotee.imgblacklist = preferences.imgblacklist;902 if (preferences.users){903 nobotee.people = preferences.users;904 } else {905 nobotee.people = {};906 }907 if (preferences.streak){908 nobotee.streak = preferences.streak;909 } else {910 nobotee.streak = 0;911 }912 if (preferences.advanced_settings) nobotee.advanced_settings = preferences.advanced_settings;913 }914};915if (!nobotee.started) {916 nobotee.start();917} else {918 nobotee.scr.updt("nobotee is already running.",1);...

Full Screen

Full Screen

spec.js

Source:spec.js Github

copy

Full Screen

1// foounit.require(':spec/spec-helper');2// Include your source file here3foounit.require('/epiceditor/js/epiceditor')4function _getIframeInnards(el) {5 return el.contentDocument || el.contentWindow.document;6}7function _createTestElement() {8 var testEl = document.createElement('div')9 , testId = 'epiceditor-' + (new Date().getTime()) + '-' + (Math.round(Math.random() * 1000));10 11 testEl.id = testId;12 document.body.appendChild(testEl);13 return testId;14}15function _randomNum() {16 return Math.round(Math.random() * 10000);17}18// Clean start19localStorage.clear();20// BEGIN THY TESTS21describe('EpicEditor.load', function () {22 var testEl = _createTestElement()23 , editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl })24 , editorIframe25 , editorInnards26 , wasLoaded = false;27 editor.on('load', function () {28 wasLoaded = this;29 });30 editor.load();31 it('check if EE returns an object reference', function () {32 expect(typeof editor).to(be, 'object');33 });34 it('make sure the load event was fired', function () {35 expect(typeof wasLoaded).to(be, 'object');36 });37 describe('check if the DOM is in place', function () {38 editorIframe = document.getElementById(testEl).getElementsByTagName('iframe');39 editorInnards = _getIframeInnards(editorIframe[0]);40 it('make sure there\'s one wrapping iframe', function () {41 expect(editorIframe.length).to(be, 1);42 });43 44 it('make sure there\'s two inner iframes', function () {45 expect(editorInnards.getElementsByTagName('iframe').length).to(be, 2);46 });47 it('check to make sure the editor frame exists', function () {48 expect(editorInnards.getElementById('epiceditor-editor-frame')).toNot(beNull);49 });50 it('check to make sure the previewer frame exists', function () {51 expect(editorInnards.getElementById('epiceditor-previewer-frame')).toNot(beNull);52 });53 it('check to make sure the utility bar exists', function () {54 expect(editorInnards.getElementById('epiceditor-utilbar')).toNot(beNull);55 });56 });57});58describe('EpicEditor.load.options', function () {59 var testEl, editor;60 before(function () {61 testEl = _createTestElement();62 });63 after(function () {64 editor.unload();65 });66 describe('when setting the container element', function () {67 it('allows the value to be a string of an ID to an element', function () {68 editor = new EpicEditor(69 { basePath: '/epiceditor/'70 , container: testEl71 }72 ).load();73 74 expect(document.getElementById(testEl).getElementsByTagName('iframe').length).to(be, 1);75 });76 it('allows the value to be a DOM object of an element', function () {77 editor = new EpicEditor({78 basePath: '/epiceditor/'79 , container: document.getElementById(testEl)80 }).load();81 expect(document.getElementById(testEl).getElementsByTagName('iframe').length).to(be, 1);82 });83 it('check that the localStorage key is correctly named for string values (IDs)', function () {84 editor = new EpicEditor({85 basePath: '/epiceditor/'86 , container: testEl87 }).load();88 expect(JSON.parse(localStorage.epiceditor)[testEl]).to(beTruthy);89 });90 it('check that the localStorage key is correctly named for DOM elements by using the ID of the element', function () {91 92 // This is all for a one off test. Creates an element with a different class name and ID93 // and we need to be able to get the name of the ID and class later94 var tempEl = document.createElement('div')95 , tempId = 'foo' + _randomNum()96 , tempClassName = 'bar' + _randomNum();97 tempEl.id = tempId;98 tempEl.className = tempClassName;99 document.body.appendChild(tempEl);100 editor = new EpicEditor({101 basePath: '/epiceditor/'102 , container: document.getElementsByClassName(tempClassName)[0]103 }).load();104 expect(JSON.parse(localStorage.epiceditor)[tempId]).to(beTruthy);105 });106 it('check that the localStorage key is correctly named for manually set file names', function () {107 var tempName = 'foo' + _randomNum();108 editor = new EpicEditor({109 basePath: '/epiceditor/'110 , container: testEl111 , file: { name: tempName }112 }).load();113 expect(JSON.parse(localStorage.epiceditor)[testEl]).to(beFalsy);114 });115 it('check that the localStorage key is correctly named when there\'s no fallback name', function () {116 var tempEl = document.createElement('div')117 , tempClassName = 'foo' + _randomNum();118 tempEl.className = tempClassName;119 document.body.appendChild(tempEl);120 editor = new EpicEditor({121 basePath: '/epiceditor/'122 , container: document.getElementsByClassName(tempClassName)[0]123 }).load();124 expect(JSON.parse(localStorage.epiceditor)['__epiceditor-untitled-1']).to(beTruthy);125 });126 });127 describe('when setting clientSideStorage', function () {128 it('check that when FALSE NO data is saved to localStorage', function () {129 editor = new EpicEditor({130 basePath: '/epiceditor/'131 , container: testEl132 , clientSideStorage: false133 }).load();134 expect(JSON.parse(localStorage['epiceditor'])[testEl]).to(be, undefined);135 });136 it('check that when TRUE data IS saved to localStorage', function () {137 editor = new EpicEditor({138 basePath: '/epiceditor/'139 , container: testEl140 , clientSideStorage: true141 }).load();142 expect(JSON.parse(localStorage['epiceditor'])[testEl]).toNot(be, undefined);143 });144 });145});146describe('EpicEditor.getElement', function () {147 var testEl = _createTestElement()148 , editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load()149 , wrapperIframe150 , innerWrapper;151 before(function () {152 wrapperIframe = document.getElementById(testEl).getElementsByTagName('iframe')[0];153 innerWrapper = _getIframeInnards(wrapperIframe);154 });155 it('check that "container" is the element given at setup', function () {156 expect(editor.getElement('container')).to(be, document.getElementById(testEl));157 });158 it('check that the "wrapper" is the div inside the wrapping iframe containing the other two iframes', function () {159 var innerWrapperDiv = innerWrapper.getElementById('epiceditor-wrapper');160 expect(editor.getElement('wrapper')).to(be, innerWrapperDiv);161 });162 it('check that the "wrapperIframe" is the iframe containing the other two iframes', function () {163 expect(editor.getElement('wrapperIframe')).to(be, wrapperIframe);164 });165 it('check that "editor" is #document of the editor iframe', function () {166 expect(editor.getElement('editor')).to(be, _getIframeInnards(innerWrapper.getElementById('epiceditor-editor-frame')));167 });168 it('check that "editorIframe" is <iframe> containing the editor', function () {169 expect(editor.getElement('editorIframe').id).to(be, 'epiceditor-editor-frame');170 });171 it('check that "previewer" is #document of the previewer iframe', function () {172 expect(editor.getElement('previewer')).to(be, _getIframeInnards(innerWrapper.getElementById('epiceditor-previewer-frame')));173 });174 it('check that "previewerIframe" is <iframe> containing the previewer', function () {175 expect(editor.getElement('previewerIframe').id).to(be, 'epiceditor-previewer-frame');176 });177});178describe('EpicEditor.getFiles', function () {179 var testEl, editor, fooFile, barFile;180 before(function () {181 localStorage.clear();182 testEl = _createTestElement();183 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();184 fooFile = 'foo' + _randomNum();185 barFile = 'bar' + _randomNum();186 editor.importFile(fooFile, 'foo');187 editor.importFile(barFile, 'bar');188 });189 after(function () {190 editor.unload();191 });192 it('check to see if the correct number of files is returned when asking for all files', function () {193 var fileCount = 0;194 for (var x in editor.getFiles()) {195 fileCount++;196 }197 expect(fileCount).to(be, 3);198 });199 it('check to see if a single (and correct) file is returned when the name param is specified', function () {200 expect(editor.getFiles(fooFile).content).to(be, 'foo');201 });202});203describe('EpicEditor.open', function () {204 var testEl, editor, openMeFile, openMeLaterFile, eventWasFired, createEventWasFired, fooFile;205 before(function () {206 testEl = _createTestElement();207 openMeFile = 'openMe' + _randomNum();208 openMeLaterFile = 'openMeLater' + _randomNum();209 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();210 editor.importFile(openMeLaterFile, 'open me later').importFile(openMeFile, 'open this file');211 212 createEventWasFired = false;213 fooFile = 'foo' + _randomNum();214 eventWasFired = false;215 editor.on('open', function () {216 eventWasFired = true;217 });218 });219 after(function () {220 editor.unload();221 });222 it('check that the openMe file was created successfully', function () {223 expect(editor.exportFile(openMeFile)).to(be, 'open this file');224 });225 it('check that the openMeLater file was created successfully', function () {226 expect(editor.exportFile(openMeLaterFile)).to(be, 'open me later');227 });228 229 it('check that the file is open in the editor', function () {230 expect(editor.getElement('editor').body.innerHTML).to(be, 'open this file');231 });232 it('check that openMeLater opens into the editor after calling .open', function () {233 editor.open(openMeLaterFile);234 expect(editor.getElement('editor').body.innerHTML).to(be, 'open me later');235 });236 it('check that the open event is called when the open method is run', function () {237 editor.open();238 expect(eventWasFired).to(be, true);239 });240 it('check that the create event fires for a new file created with open()', function () {241 editor.on('create', function () {242 createEventWasFired = true;243 });244 editor.open(fooFile);245 expect(createEventWasFired).to(beTrue);246 });247 it('check that the create event DOES NOT fire for an existing file with open', function () {248 editor.open(fooFile); // change the file from "testEl"249 editor.on('create', function () {250 createEventWasFired = true;251 });252 editor.open(testEl);253 expect(createEventWasFired).to(beFalse);254 });255 it('check that the read event fires when a file is read with open()', function () {256 editor.on('read', function () {257 eventWasFired = true;258 });259 editor.open(fooFile); // change the file (should fired create)260 261 editor.open(testEl); // this one should fire read262 expect(eventWasFired).to(be, true);263 });264});265describe('EpicEditor.importFile', function () {266 var testEl, editor, fooFile, eventWasFired;267 before(function () {268 testEl = _createTestElement();269 editor = new EpicEditor(270 { basePath: '/epiceditor/'271 , container: testEl272 }).load();273 fooFile = 'foo' + _randomNum();274 eventWasFired = false;275 });276 after(function () {277 editor.unload();278 });279 it('check that the content is currently blank', function () {280 expect(editor.exportFile()).to(be, '');281 });282 it('check that importFile(\'foo\',\'#bar\') is imported and can be received', function () {283 var importFileTest = 'importFileTest' + _randomNum();284 editor.importFile(importFileTest, '#bar');285 expect(editor.exportFile(importFileTest)).to(be, '#bar');286 });287 it('check that setting the file name as null imports content into the currently open file', function () {288 editor.importFile(null, 'foo');289 expect(editor.exportFile(testEl)).to(be, 'foo');290 });291 292 it('check that importFile fires a create an event when importing a new file', function () {293 editor.on('create', function () {294 eventWasFired = true;295 });296 editor.importFile(fooFile);297 expect(eventWasFired).to(beTrue);298 });299 it('check that importFile fires an update event when modifying an existing file', function () {300 editor.on('update', function () {301 eventWasFired = true;302 });303 editor.importFile(null, 'new text');304 expect(eventWasFired).to(beTrue);305 });306 it('check that importFile DOES NOT fire an update event when creating a file', function () {307 editor.on('update', function () {308 eventWasFired = true;309 });310 editor.importFile(fooFile);311 expect(eventWasFired).to(beFalse);312 });313 // TODO: Tests for importFile's kind parameter when implemented314 // TODO: Tests for importFile's meta parameter when implemented315});316describe('EpicEditor.exportFile', function () {317 var testEl, contents, editor;318 before(function () {319 testEl = _createTestElement();320 321 editor = new EpicEditor(322 { basePath: '/epiceditor/'323 , file: { defaultContent: '#foo\n\n##bar' }324 , container: testEl325 }).load();326 });327 after(function () {328 editor.unload();329 });330 it('check that exportFile will work without parameters by outputting the current file as raw text', function () {331 contents = editor.exportFile();332 expect(contents).to(match, /#foo\r?\n\r?\n##bar/);333 });334 it('check that exportFile will export the current file as HTML with a null parameter as it\'s first', function () {335 contents = editor.exportFile(null, 'html');336 expect(contents).to(be, '<h1>foo</h1>\n<h2>bar</h2>\n');337 });338 it('check that exporting a file that doesn\'t exist returns as undefined', function () {339 contents = editor.exportFile('doesntExist' + _randomNum());340 expect(contents).to(beUndefined);341 });342 it('check that export file can open non-currently open files', function () {343 var exportFileTest = 'exportFileTest' + _randomNum();344 editor.importFile(exportFileTest, 'hello world'); // import and open a file345 editor.open(testEl); // open the original again346 expect(editor.exportFile(exportFileTest)).to(be, 'hello world');347 });348});349describe('EpicEditor.rename', function () {350 var testEl, editor, oldName, newName;351 before(function () {352 testEl = _createTestElement()353 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();354 oldName = 'foo' + _randomNum();355 newName = 'bar' + _randomNum();356 editor.importFile(oldName, 'testing...');357 });358 after(function () {359 editor.unload();360 });361 it('check to see if the foo file exists before trying to rename', function () {362 expect(editor.exportFile(oldName)).to(be, 'testing...');363 });364 it('check that renaming a file actually renames the file by exporting by the new files name', function () {365 editor.rename(oldName, newName);366 expect(editor.exportFile(newName)).to(be, 'testing...');367 });368 it('check that foo no longer exists', function () {369 editor.rename(oldName, newName);370 expect(editor.exportFile(oldName)).to(beUndefined);371 });372});373describe('EpicEditor.remove', function () {374 375 var testEl, editor, removeMeFile, dontRemoveMeFile, eventWasFired;376 before(function () {377 testEl = _createTestElement();378 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();379 removeMeFile = 'removeMe' + _randomNum();380 dontRemoveMeFile = 'dontRemoveMe' + _randomNum();381 editor.importFile(removeMeFile, 'hello world').importFile(dontRemoveMeFile, 'foo bar');382 });383 384 after(function () {385 editor.unload();386 });387 it('check that the foo file was imported', function () {388 expect(editor.exportFile(removeMeFile)).to(be, 'hello world');389 });390 it('check that after removing the file exportFile returns false', function () {391 editor.remove(removeMeFile);392 expect(editor.exportFile(removeMeFile)).to(beUndefined);393 });394 it('check that other files weren\'t removed', function () {395 expect(editor.exportFile(dontRemoveMeFile)).to(be, 'foo bar');396 });397 it('check that the remove event fires when a file is deleted', function () {398 editor.on('remove', function () {399 eventWasFired = true;400 });401 editor.open(removeMeFile);402 editor.remove(removeMeFile);403 expect(eventWasFired).to(beTrue);404 });405});406describe('EpicEditor.preview and EpicEditor.edit', function () {407 408 var testEl, editor, previewEventWasCalled, editEventWasCalled;409 before(function () {410 testEl = _createTestElement();411 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();412 413 previewEventWasCalled = false;414 editEventWasCalled = false;415 416 editor.on('preview', function () {417 previewEventWasCalled = true;418 });419 420 editor.on('edit', function () {421 editEventWasCalled = true;422 });423 });424 after(function () {425 editor.removeListener('preview');426 editor.removeListener('edit');427 editor.unload();428 });429 it('check that the editor is currently displayed and not the previewer', function () {430 expect(editor.getElement('editorIframe').style.display).to(be, '');431 });432 it('check that the previewer can be tested to be hidden', function () {433 expect(editor.getElement('previewerIframe').style.display).to(be, 'none');434 });435 it('check that calling .preview() displays the previewer', function () {436 editor.preview();437 expect(editor.getElement('previewerIframe').style.display).to(be, 'block');438 });439 it('check that the preview event fires when the preview method is called', function () {440 editor.preview();441 expect(previewEventWasCalled).to(be, true);442 });443 it('check that the edit event fires when the edit method is called', function () {444 editor.edit();445 expect(editEventWasCalled).to(be, true);446 });447 448 it('check that switching from preview back to edit makes the editor visible', function () {449 editor.preview();450 editor.edit();451 expect(editor.getElement('editorIframe').style.display).to(be, 'block');452 });453 it('check that switching from preview back to edit doesn\'t keep the previewer displayed', function () {454 editor.preview();455 editor.edit();456 expect(editor.getElement('previewerIframe').style.display).to(be, 'none');457 });458});459describe('EpicEditor.unload', function () {460 var testEl, editor, eventWasCalled;461 before(function () {462 testEl = _createTestElement()463 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl });464 editor.load();465 eventWasCalled = false;466 editor.on('unload', function () {467 eventWasCalled = true;468 });469 });470 after(function () {471 editor.removeListener('unload');472 });473 it('check the editor was actually loaded first of all', function () {474 expect(document.getElementById(testEl).innerHTML).to(beTruthy);475 });476 it('check that the unload event fires when the editor is unloaded', function () {477 editor.unload();478 expect(eventWasCalled).to(be, true);479 });480 it('check the editor was unloaded properly by checking if the editor HTML is gone from the original element', function () {481 editor.unload();482 expect(document.getElementById(testEl).innerHTML).to(beFalsy);483 });484 it('check the editor\'s getElement method returns null for selected elements because they no longer exist', function () {485 editor.unload();486 expect(editor.getElement('editor')).to(beFalsy);487 });488 it('check that unload can\'t be run twice', function () {489 editor.unload();490 expect(function () { editor.unload(); }).to(throwError, 'Editor isn\'t loaded');491 });492 it('check that unload and reloading and then requesting getElement doesn\'t return null as if it were unloaded', function () {493 editor.unload();494 editor.load();495 expect(editor.getElement('editor')).to(beTruthy);496 });497});498describe('EpicEditor.save', function () {499 500 var testEl, editor, eventWasFired;501 502 before(function () {503 testEl = _createTestElement();504 editor = new EpicEditor(505 { basePath: '/epiceditor/'506 , container: testEl507 , file:508 { defaultContent: 'foo'509 , autoSave: false510 }511 }).load();512 eventWasFired = false;513 });514 after(function () {515 editor.unload();516 });517 it('check that foo is the default content in the editor', function () {518 expect(editor.getElement('editor').body.innerHTML).to(be, 'foo');519 });520 it('check to make sure new file contents are saved after value is changed in the editor and save is called', function () {521 editor.getElement('editor').body.innerHTML = 'bar';522 editor.save();523 expect(JSON.parse(localStorage['epiceditor'])[testEl].content).to(be, 'bar');524 });525 it('check that the save event is called when the save method is run', function () {526 editor.on('save', function () {527 eventWasFired = true;528 });529 editor.save();530 expect(eventWasFired).to(be, true);531 });532 it('check that the update event fires when the content changes', function () {533 editor.on('update', function () {534 eventWasFired = true;535 });536 editor.getElement('editor').body.innerHTML = 'bar';537 editor.save();538 expect(eventWasFired).to(beTrue);539 });540 it('check that the update event DOES NOT fire when the content is the same', function () {541 editor.on('update', function () {542 eventWasFired = true;543 });544 editor.getElement('editor').body.innerHTML = 'foo';545 editor.save();546 expect(eventWasFired).to(beFalse);547 });548 it('check that the timestamp is updated when the content is modified', function () {549 var currentModifiedDate = JSON.parse(localStorage['epiceditor'])[testEl].modified;550 editor.on('update', function () {551 eventWasFired = true;552 });553 editor.getElement('editor').body.innerHTML = 'bar';554 editor.save();555 expect(currentModifiedDate).toNot(be, JSON.parse(localStorage['epiceditor'])[testEl].modified);556 });557});558describe('EpicEditor.on', function () {559 560 var testEl, editor, hasBeenFired;561 before(function () {562 testEl = _createTestElement();563 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();564 hasBeenFired = false;565 });566 after(function () {567 editor.removeListener('foo');568 editor.unload();569 });570 it('check that on fires on an EE event, preview', function () {571 editor.on('preview', function () {572 hasBeenFired = true;573 });574 editor.preview();575 expect(hasBeenFired).to(beTrue);576 });577 it('check that on fires for custom events', function () {578 editor.on('foo', function () {579 hasBeenFired = true;580 });581 editor.emit('foo');582 expect(hasBeenFired).to(beTrue);583 });584});585describe('EpicEditor.emit', function () {586 587 var testEl, editor, hasBeenFired;588 before(function () {589 testEl = _createTestElement();590 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();591 hasBeenFired = false;592 });593 after(function () {594 editor.removeListener('foo');595 editor.unload();596 });597 // We don't use events in EpicEditor so only custom events need to be checked598 it('check that emit triggers a callback for a custom event', function () {599 editor.on('foo', function () {600 hasBeenFired = true;601 });602 editor.emit('foo');603 expect(hasBeenFired).to(beTrue);604 });605});606describe('EpicEditor.removeListener', function () {607 var testEl, editor, hasBeenFired, baz, qux, callCount;608 before(function () {609 testEl = _createTestElement();610 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();611 hasBeenFired = false;612 callCount = 0;613 editor.on('foo', function () {614 hasBeenFired = true;615 });616 baz = function () {617 callCount++;618 };619 qux = function () {620 callCount++;621 };622 editor.on('bar', baz);623 editor.on('bar', qux);624 });625 after(function () {626 editor.unload();627 });628 it('check that the foo event can be fired', function () {629 editor.emit('foo');630 expect(hasBeenFired).to(beTrue);631 });632 it('check that removing the event WITHOUT a handler param, than emitting it doesn\'t trigger the event', function () {633 editor.removeListener('foo');634 editor.emit('foo');635 expect(hasBeenFired).to(beFalse);636 });637 it('check that removing the event WITH a handler param, than emitting it only triggers one of the two handlers', function () {638 editor.removeListener('bar', baz);639 editor.emit('bar');640 expect(callCount).to(be, 1);641 });642 it('check that removing an event WITHOUT the param removes ALL handlers of that event', function () {643 editor.removeListener('bar');644 editor.emit('bar');645 expect(callCount).to(be, 0);646 });...

Full Screen

Full Screen

error_utils_spec.js

Source:error_utils_spec.js Github

copy

Full Screen

...482 }483 function dontRemoveMe () {484 return removeMeAndAbove()485 }486 const stack = dontRemoveMe().stack487 expect(stack).to.include('dontRemoveMe')488 expect(stack).not.to.include('removeMe1')489 expect(stack).not.to.include('removeMe2')490 expect(stack).not.to.include('removeMeAndAbove')491 })492 })...

Full Screen

Full Screen

JSONFieldsTransform_spec.js

Source:JSONFieldsTransform_spec.js Github

copy

Full Screen

1import {JSONFieldsTransform} from './JSONFieldsTransform.js';2import { HasKey } from './JSONFieldsTransform.js';3import { DoRemoveKey } from './JSONFieldsTransform.js';4import { fieldsToRemove } from '../data/Constants.js';5const deepValueIn1 = require('../mock/JSONSamples1_spec').deepValueIn1;6const deepValueOut1 = require('../mock/JSONSamples1_spec').deepValueOut1;7const deepValueIn2 = require('../mock/JSONSamples1_spec').deepValueIn2;8const deepValueOut2 = require('../mock/JSONSamples1_spec').deepValueOut2;9const extraFieldsIn = require('../mock/JSONSamples1_spec').extraFieldsIn;10const extraFieldsOut = require('../mock/JSONSamples1_spec').extraFieldsOut;11const chai = require('chai');12const input = {13 "main": {14 "q1": [15 {16 "id": "ABC",17 "year": "2016",18 "val": "123"19 },20 {21 "id": "ABC",22 "year": "2016",23 "val": "124"24 }25 ]}}26const output = {27 "main": {28 "q1": [29 {30 "pnlid": "ABC",31 "year": "2016",32 "val": "123"33 },34 {35 "pnlid": "ABC",36 "year": "2016",37 "val": "124"38 }39 ]}}40const fToRemove = {41 "q1": 762,42 "q2": 842,43 "recs": [44 {45 "key": 19141,46 "value": {47 "gid": "64e9e93848d0733aa024d80ffd03b8a7",48 "gid1": "21-a04908eed57d063399b4ac00e039b3a0",49 "rt": [50 {51 "id": "XYZ"52 }53 ],54 "t": "U",55 "p": "ABC",56 "messageHeader": {57 "UUId": "c739c2b0-5db3-11e7-936a-f7e83d9a4fa1",58 "Timestamp": "2017-06-30T16:47:18.107Z",59 "prod": "RTX",60 "nullValue": null61 }62 }63 }64 ]65}66const inputFieldsToRemove = {67 "removeMe":"yes",68 "dontRemoveMe":"ok"69}70const outputFieldsToRemove = {71 "dontRemoveMe":"ok"72}73describe('Make changes to JSON', () => {74 it('Change the pnls id to pnlid', () => {75 const newJSON = JSONFieldsTransform(input, (item) =>{return item && item.id !== undefined}, 76 (item) => {Object.assign(item,{"pnlid":item.id}); delete item.id; return item});77 chai.expect(newJSON).deep.equals(output)78 })79 it('Remove Uneeded fields', () => {80 const newJSON = JSONFieldsTransform((inputFieldsToRemove), HasKey(['removeMe']), 81 DoRemoveKey(['removeMe']));82 chai.expect(newJSON).deep.equals(outputFieldsToRemove)83 })84 it('Remove Uneeded fields when JSON has values as nulls', () => {85 const newJSON = JSONFieldsTransform((fToRemove), HasKey(['removeMe']), 86 DoRemoveKey(['removeMe']));87 chai.expect(newJSON).deep.equals(fToRemove)88 })89})90describe('Pulls .value forward',()=>{91 it('should modify and recurse in the same node',()=>{92 chai.expect(JSONFieldsTransform((deepValueIn1),93 (item) =>{return item && item.value !== undefined},94 (item) => {return item.value})).to.deep.equal(deepValueOut1);95 });96 it('should modify and recurse in the same node',()=>{97 chai.expect(JSONFieldsTransform((deepValueIn2),98 (item) =>{return item && item.value !== undefined},99 (item) => {return item.value})).to.deep.equal(deepValueOut2);100 });101});102describe('Removes unwanted JSON elements', () => {103 it('should remove unwanted elements found in data/Constants.js', () => {104 chai.expect(JSONFieldsTransform((extraFieldsIn),105 HasKey(fieldsToRemove),106 DoRemoveKey(fieldsToRemove))).to.deep.equal(extraFieldsOut)107 })...

Full Screen

Full Screen

test.remove.js

Source:test.remove.js Github

copy

Full Screen

1/*global createContainer:false, removeContainer:false, rnd:false */2describe('.remove(name)', function () {3 var testEl4 , id5 , editor6 , removeMeFile7 , dontRemoveMeFile8 , eventFired;9 before(function (done) {10 id = rnd();11 testEl = createContainer(id);12 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl });13 removeMeFile = 'removeMe' + id;14 dontRemoveMeFile = 'dontRemoveMe' + id;15 editor.load();16 editor.importFile(removeMeFile, 'hello world').importFile(dontRemoveMeFile, 'foo bar');17 done();18 });19 after(function (done) {20 editor.unload();21 removeContainer(id);22 done();23 });24 it('should begin with the foo file imported correctly', function () {25 expect(editor.exportFile(removeMeFile)).to.be('hello world');26 });27 it('should cause exportFile to return false after removing the foo file', function () {28 editor.remove(removeMeFile);29 expect(editor.exportFile(removeMeFile)).to.be(undefined);30 });31 it('should not remove any file other than the fileName passed', function () {32 expect(editor.exportFile(dontRemoveMeFile)).to.be('foo bar');33 });34 it('should fire the remove event', function () {35 editor.on('remove', function () {36 eventFired = true;37 });38 editor.open(removeMeFile);39 editor.remove(removeMeFile);40 expect(eventFired).to.be(true);41 });...

Full Screen

Full Screen

0aa0b7a3125c93abf40d039eb5d87d6d10ee0474_2_2.js

Source:0aa0b7a3125c93abf40d039eb5d87d6d10ee0474_2_2.js Github

copy

Full Screen

1function () {2 3 var testEl, editor, removeMeFile, dontRemoveMeFile, eventWasFired;4 before(function () {5 testEl = _createTestElement();6 editor = new EpicEditor({ basePath: '/epiceditor/', container: testEl }).load();7 removeMeFile = 'removeMe' + _randomNum();8 dontRemoveMeFile = 'dontRemoveMe' + _randomNum();9 editor.importFile(removeMeFile, 'hello world').importFile(dontRemoveMeFile, 'foo bar');10 });11 12 it('check that the foo file was imported', function () {13 expect(editor.exportFile(removeMeFile)).to(be, 'hello world');14 });15 it('check that after removing the file exportFile returns false', function () {16 editor.remove(removeMeFile);17 expect(editor.exportFile(removeMeFile)).to(beUndefined);18 });19 it('check that other files weren\'t removed', function () {20 expect(editor.exportFile(dontRemoveMeFile)).to(be, 'foo bar');21 });22 it('check that the remove event fires when a file is deleted', function () {23 editor.on('remove', function () {24 eventWasFired = true;25 });26 editor.open(removeMeFile);27 editor.remove(removeMeFile);28 expect(eventWasFired).to(beTrue);29 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 expect(true).to.equal(true)4 })5})6describe('My First Test', function() {7 it('Does not do much!', function() {8 expect(true).to.equal(true)9 })10})11describe('My First Test', function() {12 it('Does not do much!', function() {13 expect(true).to.equal(true)14 })15})16describe('My First Test', function() {17 it('Does not do much!', function() {18 expect(true).to.equal(true)19 })20})21describe('My First Test', function() {22 it('Does not do much!', function() {23 expect(true).to.equal(true)24 })25})26describe('My First Test', function() {27 it('Does not do much!', function() {28 expect(true).to.equal(true)29 })30})31 expect(true).to.equal(true)32 expect(true).to.equal(true)33 expect(true).to.equal(true)34 expect(true).to.equal(true)

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.dontRemoveMe()2cy.dontRemoveMe()3cy.dontRemoveMe()4cy.dontRemoveMe()5cy.dontRemoveMe()6cy.dontRemoveMe()7cy.dontRemoveMe()8cy.dontRemoveMe()9cy.dontRemoveMe()10cy.dontRemoveMe()11cy.dontRemoveMe()12cy.dontRemoveMe()13cy.dontRemoveMe()14cy.dontRemoveMe()15cy.dontRemoveMe()16cy.dontRemoveMe()17cy.dontRemoveMe()18cy.dontRemoveMe()19cy.dontRemoveMe()20cy.dontRemoveMe()21cy.dontRemoveMe()22cy.dontRemoveMe()23cy.dontRemoveMe()

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.dontRemoveMe();2Cypress.dontRemoveMe = () => {3 console.log('dontRemoveMe method added to Cypress class');4};5Cypress.dontRemoveMe = () => {6 console.log('dontRemoveMe method added to Cypress class');7};8Cypress.dontRemoveMe = () => {9 console.log('dontRemoveMe method added to Cypress class');10};11Cypress.dontRemoveMe = () => {12 console.log('dontRemoveMe method added to Cypress class');13};14Cypress.dontRemoveMe = () => {15 console.log('dontRemoveMe method added to Cypress class');16};17Cypress.dontRemoveMe = () => {18 console.log('dontRemoveMe method added to Cypress class');19};20Cypress.dontRemoveMe = () => {21 console.log('dontRemoveMe method added to Cypress class');22};23Cypress.dontRemoveMe = () => {24 console.log('dontRemoveMe method added to Cypress class');25};26Cypress.dontRemoveMe = () => {27 console.log('dontRemoveMe method added to Cypress class');28};29Cypress.dontRemoveMe = () => {30 console.log('dontRemoveMe method added to Cypress class');31};32Cypress.dontRemoveMe = () => {33 console.log('dontRemoveMe method added to

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.dontRemoveMe();2import { dontRemoveMe } from 'cypress-dont-remove-me';3dontRemoveMe();4cy.dontRemoveMe();5import { dontRemoveMe } from 'cypress-dont-remove-me';6dontRemoveMe();7cy.dontRemoveMe();8MIT © [Michael Mifsud](

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.dontRemoveMe();2import "cypress-dont-remove-me";3cy.dontRemoveMe();4import "cypress-dont-remove-me";5cy.dontRemoveMe({6});7| `timeout` | Integer | 10000 | The amount of time (in milliseconds) to wait for the element to be visible before timing out (default 10000ms). |8| `interval` | Integer | 100 | The time (in milliseconds) to wait between each check of the element's visibility (default 100ms). |9[MIT](

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('dontRemoveMe', () => {2 console.log('dontRemoveMe');3});4Cypress.Commands.add('removeMe', () => {5 console.log('removeMe');6});7Cypress.Commands.add('dontRemoveMe2', () => {8 console.log('dontRemoveMe2');9});10Cypress.Commands.add('removeMe2', () => {11 console.log('removeMe2');12});13Cypress.Commands.add('dontRemoveMe3', () => {14 console.log('dontRemoveMe3');15});16Cypress.Commands.add('removeMe3', () => {17 console.log('removeMe3');18});19Cypress.Commands.add('dontRemoveMe4', () => {20 console.log('dontRemoveMe4');21});22Cypress.Commands.add('removeMe4', () => {23 console.log('removeMe4');24});25Cypress.Commands.add('dontRemoveMe5', () => {26 console.log('dontRemoveMe5');27});28Cypress.Commands.add('removeMe5', () => {29 console.log('removeMe5');30});31Cypress.Commands.add('dontRemoveMe6', () => {32 console.log('dontRemoveMe6');33});34Cypress.Commands.add('removeMe6', () => {35 console.log('removeMe6');36});37Cypress.Commands.add('dontRemoveMe7', () => {38 console.log('dontRemoveMe7');39});40Cypress.Commands.add('removeMe7', () => {41 console.log('removeMe7');42});43Cypress.Commands.add('dontRemoveMe8', () => {44 console.log('dontRemoveMe8');45});46Cypress.Commands.add('removeMe8', () => {47 console.log('removeMe8');48});49Cypress.Commands.add('dontRemoveMe9', () => {50 console.log('dontRemoveMe9');51});52Cypress.Commands.add('removeMe9', () => {53 console.log('removeMe9');54});55Cypress.Commands.add('dontRemoveMe10', () => {56 console.log('dontRemoveMe10');57});58Cypress.Commands.add('removeMe10', () => {59 console.log('removeMe10');60});61Cypress.Commands.add('dontRemoveMe11', () => {62 console.log('dontRemoveMe11');63});64Cypress.Commands.add('removeMe11', () => {65 console.log('removeMe11');66});

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful