Skip to content

Instantly share code, notes, and snippets.

@tribela
Last active December 30, 2021 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tribela/ed741d20b33bb56927c57441fe488022 to your computer and use it in GitHub Desktop.
Save tribela/ed741d20b33bb56927c57441fe488022 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Fullscreen to lights off
// @version 1
// @grant GM.xmlHttpRequest
// @grant GM.setValue
// @grant GM.getValue
// @match https://app.plex.tv/*
// @match https://watcha.com/*
// @match https://www.netflix.com/*
// @match https://www.disneyplus.com/*
// ==/UserScript==
let states = {
fullscreen: false,
playing: false,
};
let config = {};
async function getConfig(name) {
let value = await GM.getValue(name, null);
if (value === null) {
value = prompt(`Please enter ${name} for Hass`);
await GM.setValue(name, value);
}
return value;
}
async function setup() {
config.API_KEY = await getConfig('API_KEY');
config.SCENE_PLAYING = await getConfig('SCENE_PLAYING');
config.SCENE_PAUSED = await getConfig('SCENE_PAUSED');
config.SCENE_EXIT = await getConfig('SCENE_EXIT');
}
let webhook = (state) => {
let scene;
switch (state) {
case 'on':
scene = config.SCENE_PLAYING;
break;
case 'paused':
scene = config.SCENE_PAUSED;
break;
case 'off':
scene = config.SCENE_EXIT;
break;
}
try {
GM.xmlHttpRequest({
method: 'POST',
url: 'https://ha.11ac.net/api/services/scene/turn_on',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${config.API_KEY}`
},
data: JSON.stringify({
entity_id: `scene.${scene}`,
}),
onerror: (res) => {
console.error('fullscreen webhook failed');
},
});
} catch (err) {
console.log(err);
}
};
let updateStatus = () => {
if (states.fullscreen && states.playing) {
webhook('on');
} else if (states.fullscreen && !states.playing) {
webhook('paused');
} else {
webhook('off');
}
};
let playHandler = (event) => {
states.playing = event.type === 'playing';
updateStatus();
}
document.addEventListener('fullscreenchange', (event) => {
const videoElem = document.querySelector('video');
states.fullscreen = !!document.fullscreen;
states.playing = videoElem && videoElem.paused === false;
if (states.fullscreen) {
videoElem.addEventListener('playing', playHandler);
videoElem.addEventListener('pause', playHandler);
} else {
videoElem.removeEventListener('playing', playHandler);
videoElem.removeEventListener('pause', playHandler);
}
updateStatus();
});
window.addEventListener('load', setup);
// console.log(GM_info);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment