Skip to content
Snippets Groups Projects
Commit 94873a38 authored by Alpi-Laptop's avatar Alpi-Laptop
Browse files

#last changes for presentation

parent b75b50ef
No related tags found
No related merge requests found
......@@ -5,5 +5,8 @@
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="@types/chrome" level="application" />
<orderEntry type="library" name="p5ble" level="application" />
<orderEntry type="library" name="p5.js" level="application" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<file url="file://$PROJECT_DIR$" libraries="{p5.js, p5ble}" />
<file url="PROJECT" libraries="{@types/chrome}" />
<includedPredefinedLibrary name="Nashorn" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
......
let color = '#3aa757';
const title = chrome.runtime.getManifest().name;
let selected = "";
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ color });
console.log('Default background color set to %cgreen', `color: ${color}`);
chrome.runtime.onStartup.addListener(function (c){
chrome.runtime.openOptionsPage();
})
chrome.tabs.onUpdated.addListener((number,status,tab) =>{
let urlTab = tab.url
let trimURL = tab.url.split('/')[0] + '//' + tab.url.split('/')[2];
//we trim the website url to limit the API-Request
//use urlTab if all websites should be send to klazify
if(selected === undefined || selected === ''){
chrome.storage.local.get("selected", function (res){
selected = res["selected"];
})
}
if(status.status === "complete"){
chrome.storage.local.get(trimURL, function (res){
if(res[trimURL] === undefined){
console.log("First visit")
klazify(trimURL)
}else{
console.log("already in database")
addPoints(trimURL)
}
})
}
});
function messageResponse(res){
console.log(res)
}
function klazify(trimURL){
//console.log("complete, next categorize")
let urlklazify = "https://www.klazify.com/api/categorize"
fetch(urlklazify,{
"method":"POST",
"headers": {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiMGZlYjlmODczYThjMmI2YjczNjVmZTA5MjE1MWQ2YzM0MmY1YjJjMThmOWIwOTBmYmM2ZmY0MTY0ZDJkNjBkNDEwOGE5ZDk2MzZlOWI4MDIiLCJpYXQiOjE2NDI5Njc3MjQsIm5iZiI6MTY0Mjk2NzcyNCwiZXhwIjoxNjc0NTAzNzI0LCJzdWIiOiI1NjYwIiwic2NvcGVzIjpbXX0.hJuy9jHXeYEUUUbqwQjIoyEdXZerD4hwamWG5BrjAyfTvwsBtZdRMsDDMcNHoMTey6ezKY1dHE3X-cZI0g8Tbg",
"cache-control": "no-cache"
},
"body": "{\"url\":\""+trimURL+" \"}\n"
})
.then(json)
.then(function (data) {
//console.log('Request succeeded with JSON response', data.toString());
console.log(data)
let key_value={}
let arraying = data['domain']['categories']
let turned = false
for(let i=0; i<arraying.length;i++){
addPointToCategories(data['domain']['categories'][i]['name'], data['domain']['categories'][i]['confidence'])
let key_value = {};
if(data['domain']['categories'][i]['name'].includes('Food') && !turned){
turned=true
//console.log(data['domain']['categories'][i]['confidence'])
console.log("turn device")
}else{
console.log("dont turn device | already turned:"+turned)
}
}
key_value[trimURL] = data['domain']['categories']
chrome.storage.local.set(key_value, function (){})
console.log(key_value[trimURL])
})
.catch(function (error) {
console.log('Request failed', error);
});
}
function visited(trimURL){
chrome.storage.local.get(trimURL, function (res){
if(res[trimURL]===undefined){
return false
}else{
return true
}
})
}
function json(response) {
return response.json()
}
function addPoints(trimURL){
chrome.storage.local.get(trimURL, function (res){
let array = res[trimURL]
for(let i=0; i<array.length;i++){
addPointToCategories(array[i]['name'], array[i]['confidence'])
}
})
chrome.storage.local.get(trimURL, function (result){
console.log(trimURL, result[trimURL])
})
}
function addPointToCategories(categorize, points){
let keyValue = {};
categorize = categorize.split('/')[1]
chrome.storage.local.get("selected", function (sel){
chrome.storage.local.get(categorize, function (res){
if(res[categorize]===undefined){
keyValue[categorize]=points
chrome.storage.local.set(keyValue, function (){})
}else{
keyValue[categorize]=res[categorize] + points;
console.log("Categories: " + categorize + "\n Points: "+ res)
chrome.storage.local.set(keyValue, function (){})
}
if(sel["selected"] === categorize){
points = points *1000
chrome.runtime.sendMessage({turn:points}, messageResponse)//for presentation so high
}
})
})
}
Image diff could not be displayed: it is too large. Options to address this: view the blob.
<!DOCTYPE html>
<html lang="en">
<script type="text/javascript" src="libraries/p5.ble.js"></script>
<script type="text/javascript" src="libraries/p5.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<head>
<meta charset="UTF-8">
<title>Title</title>
HELLOO 123
</head>
<body>
<button id="connectBLE">Connect</button>
</body>
</html>
index.js 0 → 100644
chrome.runtime.onConnect = function (){
setupBluetooth();
buttonConnect = document.getElementById("connectBLE")
buttonConnect.addEventListener('click', connectToBle, false)
function setupBluetooth(){
console.log("Setup Bluetooth")
blueTooth = new p5ble();
console.log(blueTooth)
}
function connectToBle(){
blueTooth.connect(0xFFE0, gotCharacteristics)
}
}
This diff is collapsed.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
{
"name": "Getting Started Example",
"name": "Digital ME",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
......@@ -7,20 +7,30 @@
"service_worker": "background.js"
},
"options_page": "options.html",
"permissions": ["storage", "activeTab","declarativeContent", "scripting"],
"permissions": [
"storage",
"activeTab",
"declarativeContent",
"scripting",
"contextMenus",
"tabs",
"topSites",
"history",
"bookmarks"
],
"action": {
"default_popup": "popup.html",
"default_popup": "index.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
"16": "/images/img.png",
"32": "/images/img.png",
"48": "/images/img.png",
"128": "/images/img.png"
}
},
"icons": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
"16": "/images/img.png",
"32": "/images/img.png",
"48": "/images/img.png",
"128": "/images/img.png"
}
}
h1{
text-align: center;
}
body{
text-align: center;
}
p{
position: center;
margin-top: 250px;
text-align: center;
}
.step{
display: none;
}
.step.active{
display: block;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
<link rel="stylesheet" href="options.css">
</head>
<body>
<div id="buttonDiv">
<button id="btnConnect" style="visibility: hidden">connect to Bubble</button>
<script type="text/javascript" src="libraries/p5.ble.js"></script>
<script type="text/javascript" src="libraries/p5.min.js"></script>
<script type="text/javascript" src="options.js"></script>
<div class="step step1 active">
<p>
<button id="getStarted">get started</button>
</p>
</div>
<div>
<p>Here are the options :D </p>
<div class="step step2">
<div class="text-align-center" style="display: inline-block; text-align: left;">
<p id="your_bubble"></p>
<h1>
<b id="selectedBubble"></b>
<button id="addBubble"> add Bubble</button> <br>
<button id="deleteBubble"> delete Bubble</button> <br>
<b id="selectedBubblePoint"></b>
</h1>
</div>
</div>
<div class="step step3">
<datalist id="addBubbleData">
<option value="Arts & Entertainment"></option>
<option value="Autos & Vehicles"></option>
<option value="Beauty & Fitness"></option>
<option value="Books & Literature"></option>
<option value="Business & Industrial"></option>
<option value="Computers & Electronics"></option>
<option value="Finance"></option>
<option value="Food & Drink"></option>
<option value="Games"></option>
<option value="Health"></option>
<option value="Hobbies & Leisure"></option>
<option value="Home & Garden"></option>
<option value="Internet & Telecom"></option>
<option value="Jobs & Education"></option>
<option value="Law & Government"></option>
<option value="Online Communities"></option>
<option value="People & Society"></option>
<option value="Pets & Animals"></option>
<option value="Real Estate"></option>
<option value="Reference"></option>
<option value="Science"></option>
<option value="Shopping"></option>
<option value="Sports"></option>
<option value="Travel"></option>
</datalist>
<p>
<b id="pSelectBubble">Please Choose a new Bubble:</b>
<input list="addBubbleData" name="bubble" id="bubbleInput">
<button id="addSelectedBubble"> Add this Bubble</button>
</p>
</div>
<div class="step step4">
<p>
Pleas tab the ball at the top of the ball screen<br>
and connect to your Device
</p>
</div>
<div class="step step5">
<p>
Please insert the Ball in the device and click
<button id="btnBallInside"> HERE </button>
</p>
<br>
<p id="visited"></p>
</div>
<div class="step step6">
Thank you :)<br>
Please leave this tab open for the communication
</div>
</body>
<script src="options.js"></script>
</html>
let steps = new Array(10)
let blueTooth;
let blueToothCharacteristic;
let receivedValue = "";
let isConnected = false;
let nfcRead = false;
let waitingForNFC = false;
microActive = false;
let buttonConnect
let bookShooping = ["https://www.zalando.de/","https://www.amazon.de", "https://www.aboutYou.de", "https://www.otto.de"]
let bookSports = [""]
let bookGames;
let bookNews;
let bookTravel;
let category = ["Arts & Entertainment",
"Autos & Vehicles",
"Beauty & Fitness",
"Books & Literature",
"Business & Industrial",
"Computers & Electronics",
"Finance",
"Food & Drink",
"Games",
"Health",
"Hobbies & Leisure",
"Home & Garden",
"Internet & Telecom",
"Jobs & Education",
"Law & Government",
"News",
"Online Communities",
"People & Society",
"Pets & Animals",
"Real Estate",
"Reference",
"Science",
"Shopping",
"Sports",
"Travel",
"selected"
]
function yourBubbleScreen(){
console.log("yourBubble")
nextStep(1)
calculateBubble()
}
function nextStep(number){
let index = 0
const active = document.querySelector('.step.active');
index = steps.indexOf(active)
steps[index].classList.remove('active');
index = index+number;
steps[index].classList.add('active')
//console.log(active)
}
function backToStep(){
let index = 0;
const active = document.querySelector('.step.active');
index = steps.indexOf(active)
steps[index].classList.remove('active');
steps[1].classList.add('active')
}
function calculateBubble(){
let buffer ="Your Bubble: \n";
let totalPoints = 0;
const btnAddBubble = document.getElementById('addBubble');
const btnDeleteBubble = document.getElementById('deleteBubble');
document.getElementById("btnConnect").style.visibility = "visible"
document.getElementById("btnConnect").addEventListener('click', connectToBle,false)
chrome.storage.local.get(category, function (res){
console.log(res)
for(let i=0; i<category.length-1;i++){
if(res[category[i]] !== undefined){
totalPoints = totalPoints + res[category[i]]
}
}
console.log("totalPoints: " + totalPoints)
for(let i=0; i<category.length-1; i++){
if(res[category[i]] !== undefined && res[category[i]] !== res[category['selected']]){
buffer = buffer +" Kategorie:"+ category[i] + " | Punkte: " + Math.round(res[category[i]]/totalPoints*100) + "\n"
}
if(res[category[i]] === res["selected"]){
if(res['selected'] === undefined){
btnAddBubble.style.visibility = "visible"
btnDeleteBubble.style.visibility = "hidden"
document.getElementById("selectedBubble").innerText =
"Please Select a bubble"
}else{
document.getElementById("selectedBubble").innerText =
"Your selected bubble is: " + res['selected'];
if(res["selected"] === undefined){
document.getElementById("selectedBubblePoint").innerText =
"No Points so far"
}else{
document.getElementById("selectedBubblePoint").innerText =
""+Math.round(res[category[i]]/totalPoints*100)
}
}
}
}
document.getElementById("your_bubble").innerText = buffer
})
}
function deleteBubbleScreen(){
let retVal = confirm("You really want to delete your selected Bubble");
if(retVal === true){
chrome.storage.local.remove("selected", function (res){console.log(res)});
}
}
function addBubbleScreen() {
nextStep(1);
}
function addSelectedBubble() {
let selectedBubble = document.getElementById('bubbleInput').value
if(selectedBubble === '' ){
document.getElementById('pSelectBubble').innerText = "Please Choose a Bubble"
}else{
let keyValue = {}
keyValue["selected"] = selectedBubble
keyValue["selectedTime"] = new Date();
chrome.storage.local.set(keyValue, function (){})
addBookmark(selectedBubble);
nextStep(1)
listen();
}
}
function addBookmark(sel){
function addShopping(){
for(let i=0;i<bookShooping.length; i++){
chrome.bookmarks.create({
title: "ShoppingBubble",
url: bookShooping[i]
})
}
}
function addSports(){
for(let i=0;i<bookSports.length; i++){
chrome.bookmarks.create({
title: "GamesBubble",
url: bookShooping[i]
})
}
}
function addGames(){
for(let i=0;i<bookSports.length; i++){
chrome.bookmarks.create({
title: "GamesBubble",
url: bookShooping[i]
})
}
}
if(sel === "Shopping"){
chrome.bookmarks.create({
title: "shopping",
url: null
},function (newFolder){addShopping()});
}
if(sel === "Sports"){
chrome.bookmarks.create({
title: "sports",
url: null
},function (newFolder){addSports()});
}
}
function listen(){
navigator.mediaDevices.getUserMedia({audio:true, video:false})
.then(listenMicro);
}
window.onload=function (){
setupBluetooth()
connectToBle()
chrome.runtime.onMessage.addListener(messageReceived)
steps = Array.from(document.querySelectorAll('.step'))
const btnNext1 = document.getElementById("getStarted");
btnNext1.addEventListener('click',yourBubbleScreen, false);
writePoints();
const btnAddSelectedBubble = document.getElementById('addSelectedBubble');
btnAddSelectedBubble.addEventListener('click', addSelectedBubble, false)
try {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
window.audioContext = new AudioContext();
} catch (e) {
alert('Web Audio API not supported.');
}
//chrome.topSites.get(printTopSites);
let button = document.getElementById("btnNext");
button.addEventListener('click',readInput,false)
buttonConnect = document.getElementById("btnConnect")
buttonConnect.addEventListener('click', connectToBle, false)
let buttonRedLED = document.getElementById("btnRedLED")
buttonRedLED.addEventListener('click', sendData, false)
let buttonRedLEDOff = document.getElementById("btnRedLEDoff")
buttonRedLEDOff.addEventListener('click',turnOffRedLED, false)
blueTooth.startNotifications(blueToothCharacteristic, gotValue, 'string');
}
function writePoints(){
const btnAddBubble = document.getElementById('addBubble');
btnAddBubble.addEventListener('click',addBubbleScreen, false)
const btnDeleteBubble = document.getElementById('deleteBubble');
btnDeleteBubble.addEventListener('click', deleteBubbleScreen, false);
chrome.storage.local.get("selected", function (res){
console.log(res["selected"]);
if(res["selected"] === undefined){
//no bubble selected, hide delete bubble
btnAddBubble.style.visibility = "visible"
btnDeleteBubble.style.visibility = "hidden"
}else{
btnAddBubble.style.visibility = "hidden"
btnDeleteBubble.style.visibility = "visible"
document.getElementById("selectedBubble").innerText =
"Your selected bubble is: " + res["selected"]
chrome.storage.local.get(res['selected'], function (res2){
if(res2[res['selected']] === undefined){
document.getElementById("selectedBubblePoint").innerHTML = "No Points :(";
}else {
document.getElementById("selectedBubblePoint").innerHTML = res2[res['selected']]
}
})
}
})
}
function listenMicro(stream){
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const microphone = audioContext.createMediaStreamSource(stream);
const scriptProcessor = audioContext.createScriptProcessor(2048, 1, 1);
analyser.smoothingTimeConstant = 0.8;
analyser.fftSize = 1024;
microphone.connect(analyser);
analyser.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
scriptProcessor.onaudioprocess = function() {
const array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array);
const arraySum = array.reduce((a, value) => a + value, 0);
const average = arraySum / array.length;
console.log(Math.round(average));
// colorPids(average);
if(average>50){
scriptProcessor.disconnect();
microphone.disconnect();
analyser.disconnect();
microphone.mediaStream.getAudioTracks().forEach(function (track){track.stop();})
microActive = true;
calculateBubble();
connectToBle();
writePoints();
document.getElementById("btnConnect").style.visibility = "visible"
document.getElementById("btnConnect").addEventListener('click', connectToBle,false)
document.getElementById("btnBallInside").addEventListener('click', function (){
nextStep(1);
}, false)
}
};
}
function logHistory(historyItems){
for(let i=0;i<historyItems.length;i++){
console.log(historyItems[i].url)
}
}
function setupBluetooth(){
console.log("Setup Bluetooth")
blueTooth = new p5ble();
}
function sendData(data){
console.log("sendData")
let enc = new TextEncoder()
let value = data;
const string = "TURN ON#" + value.toString();
blueToothCharacteristic.writeValue(enc.encode(string))
}
function connectToBle(){
blueTooth.connect(0xFFE0, gotCharacteristics)
}
function gotCharacteristics(error, characteristics) {
if (error) {
console.log('error: ', error);
}
console.log('characteristics: ', characteristics);
blueToothCharacteristic = characteristics[0];
blueTooth.startNotifications(blueToothCharacteristic, gotValue, 'string');
isConnected = blueTooth.isConnected();
let enc = new TextEncoder()
const string = "NFC-READY"
blueToothCharacteristic.writeValue(enc.encode(string))
if(microActive === true){
nextStep(1);
setTimeout(function (){
backToStep()
}, 5000)
}
// Add a event handler when the device is disconnected
blueTooth.onDisconnected(onDisconnected);
}
function onDisconnected() {
console.log('Device got disconnected.');
isConnected = false;
}
function gotValue(value) {
console.log('NFC: ', value);
if(value === "NFC-READ"){
successNFT();
}
if(value === "CANCEL"){
deletePoints();
}
}
function successNFT(){
console.log("NFC Read - Ball in the machine")
backToStep()
}
function printVisits(visits){
console.log(visits)
}
function printTopSites(topSiteArray){
console.log("TEst")
let topSiteText = ""
for(let i=0; i<topSiteArray.length;i++){
console.log(topSiteArray[i])
topSiteText = topSiteText + topSiteArray[i]['title'] + "<br>"+ topSiteArray[i]['url']+ "<br><br>"
}
document.getElementById("Most").innerHTML = topSiteText
}
function readInput(){
document.getElementById("Most").innerText
= document.getElementById("Most").innerText+"<br>"
+ document.getElementById("userInput").value
}
function messageReceived(msg){
console.log(msg.turn)
savePoints(msg.turn)
sendData(msg.turn)
}
function savePoints(data){
chrome.storage.local.get("totalPoints", function (res){
let val = {};
val["totalPoints"] = res["totalPoints"] + data;
chrome.storage.local.set(val, function (){});
})
}
function deletePoints(){
let val = {};
val["totalPoints"] = 0;
chrome.storage.local.set(val, function (){})
}
<!DOCTYPE html>
<html lang="en">
<html style="min-width:300px;min-height:300px;">
<head>
<link rel="stylesheet" href="button.css">
<title>DigitalME</title>
</head>
<body>
DigitalME
<script src="popup.js"></script>
<div id="id1">-</div>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
// When the button is clicked, inject setPageBackgroundColor into current page
changeColor.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: setPageBackgroundColor,
});
});
// The body of this function will be executed as a content script inside the
// current page
function setPageBackgroundColor() {
chrome.storage.sync.get("color", ({ color }) => {
document.body.style.backgroundColor = color;
});
}
\ No newline at end of file
mode=p5.js
mode.id=processing.mode.p5js.p5jsMode
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment