Make work with Cast

This commit is contained in:
Thomas Lovén 2022-07-24 18:54:22 +00:00
parent 02c8f91690
commit 1cb64a2c8d
10 changed files with 85 additions and 18 deletions

View File

@ -338,8 +338,7 @@ const ConnectionMixin = (SuperClass) => {
this.browserEntities = {}; this.browserEntities = {};
} }
LOG(...args) { LOG(...args) {
const dt = new Date(); return;
console.log(`${dt.toLocaleTimeString()}`, ...args);
} }
fireEvent(event, detail = undefined) { fireEvent(event, detail = undefined) {
this.dispatchEvent(new CustomEvent(event, { detail })); this.dispatchEvent(new CustomEvent(event, { detail }));
@ -1964,6 +1963,8 @@ const BrowserIDMixin = (SuperClass) => {
} }
} }
get browserID() { get browserID() {
if (document.querySelector("hc-main"))
return "CAST";
if (localStorage[ID_STORAGE_KEY]) if (localStorage[ID_STORAGE_KEY])
return localStorage[ID_STORAGE_KEY]; return localStorage[ID_STORAGE_KEY];
this.browserID = ""; this.browserID = "";
@ -2032,12 +2033,12 @@ const BrowserIDMixin = (SuperClass) => {
x Title templates x Title templates
- Tweaks - Tweaks
- Quickbar tweaks (ctrl+enter)? - Quickbar tweaks (ctrl+enter)?
- Card-mod preload x Card-mod preload
- Video player? - Video player?
- Media_seek - Media_seek
- Screensavers - Screensavers
- IMPORTANT: FIX DEFAULT HIDING OF ENTITIES - IMPORTANT: FIX DEFAULT HIDING OF ENTITIES
- Check functionality with CAST - may need to add frontend part as a lovelace resource X Check functionality with CAST - may need to add frontend part as a lovelace resource
*/ */
class BrowserMod extends ServicesMixin(PopupMixin(ActivityMixin(BrowserStateMixin(CameraMixin(MediaPlayerMixin(ScreenSaverMixin(AutoSettingsMixin(FullyMixin(RequireInteractMixin(ConnectionMixin(BrowserIDMixin(EventTarget)))))))))))) { class BrowserMod extends ServicesMixin(PopupMixin(ActivityMixin(BrowserStateMixin(CameraMixin(MediaPlayerMixin(ScreenSaverMixin(AutoSettingsMixin(FullyMixin(RequireInteractMixin(ConnectionMixin(BrowserIDMixin(EventTarget)))))))))))) {
constructor() { constructor() {

View File

@ -365,12 +365,18 @@ class BrowserModRegisteredBrowsersCard extends s {
}); });
} }
}; };
window.browser_mod.showPopup("Unregister browser", `Are you sure you want to unregister browser ${browserID}?`, { window.browser_mod.showPopup("Unregister browser", `Are you sure you want to unregister Browser ${browserID}?`, {
right_button: "Yes", right_button: "Yes",
right_button_action: unregisterCallback, right_button_action: unregisterCallback,
left_button: "No", left_button: "No",
}); });
} }
register_cast() {
window.browser_mod.connection.sendMessage({
type: "browser_mod/register",
browserID: "CAST",
});
}
render() { render() {
return $ ` return $ `
<ha-card header="Registered Browsers" outlined> <ha-card header="Registered Browsers" outlined>
@ -389,6 +395,15 @@ class BrowserModRegisteredBrowsersCard extends s {
</ha-icon-button> </ha-icon-button>
</ha-settings-row>`)} </ha-settings-row>`)}
</div> </div>
${window.browser_mod.browsers["CAST"] === undefined
? $ `
<div class="card-actions">
<mwc-button @click=${this.register_cast}>
Register CAST Browser
</mwc-button>
</div>
`
: ""}
</ha-card> </ha-card>
`; `;
} }

View File

@ -2,7 +2,7 @@
"domain": "browser_mod", "domain": "browser_mod",
"name": "Browser mod", "name": "Browser mod",
"documentation": "https://github.com/thomasloven/hass-browser_mod/blob/master/README.md", "documentation": "https://github.com/thomasloven/hass-browser_mod/blob/master/README.md",
"dependencies": ["panel_custom", "websocket_api", "http", "frontend"], "dependencies": ["panel_custom", "websocket_api", "http", "frontend", "lovelace"],
"codeowners": [], "codeowners": [],
"requirements": [], "requirements": [],
"version": "2.0b0", "version": "2.0b0",

View File

@ -2,6 +2,10 @@ from homeassistant.components.frontend import add_extra_js_url
from .const import FRONTEND_SCRIPT_URL, SETTINGS_PANEL_URL from .const import FRONTEND_SCRIPT_URL, SETTINGS_PANEL_URL
import logging
_LOGGER = logging.getLogger(__name__)
async def async_setup_view(hass): async def async_setup_view(hass):
@ -28,3 +32,25 @@ async def async_setup_view(hass):
SETTINGS_PANEL_URL, SETTINGS_PANEL_URL,
hass.config.path("custom_components/browser_mod/browser_mod_panel.js"), hass.config.path("custom_components/browser_mod/browser_mod_panel.js"),
) )
# Also load Browser Mod as a lovelace resource so it's accessible to Cast
resources = hass.data["lovelace"]["resources"]
if resources:
if not resources.loaded:
await resources.async_load()
resources.loaded = True
frontend_added = False
for r in resources.async_items():
if r["url"].startswith(FRONTEND_SCRIPT_URL):
frontend_added = True
continue
# While going through the resources, also preload card-mod if it is found
if "card-mod.js" in r["url"]:
add_extra_js_url(hass, r["url"])
if not frontend_added:
await resources.async_create_item(
{
"res_type": "module",
"url": FRONTEND_SCRIPT_URL + "?automatically-added",
}
)

View File

@ -10,7 +10,7 @@ _LOGGER = logging.getLogger(__name__)
@attr.s @attr.s
class Settings: class SettingsStoreData:
hideSidebar = attr.ib(type=bool, default=None) hideSidebar = attr.ib(type=bool, default=None)
hideHeader = attr.ib(type=bool, default=None) hideHeader = attr.ib(type=bool, default=None)
defaultPanel = attr.ib(type=str, default=None) defaultPanel = attr.ib(type=str, default=None)
@ -32,12 +32,12 @@ class BrowserStoreData:
last_seen = attr.ib(type=int, default=0) last_seen = attr.ib(type=int, default=0)
enabled = attr.ib(type=bool, default=False) enabled = attr.ib(type=bool, default=False)
camera = attr.ib(type=bool, default=False) camera = attr.ib(type=bool, default=False)
settings = attr.ib(type=Settings, factory=Settings) settings = attr.ib(type=SettingsStoreData, factory=SettingsStoreData)
meta = attr.ib(type=str, default="default") meta = attr.ib(type=str, default="default")
@classmethod @classmethod
def from_dict(cls, data): def from_dict(cls, data):
settings = Settings.from_dict(data.get("settings", {})) settings = SettingsStoreData.from_dict(data.get("settings", {}))
return cls( return cls(
**( **(
data data
@ -55,8 +55,8 @@ class BrowserStoreData:
class ConfigStoreData: class ConfigStoreData:
browsers = attr.ib(type=dict[str:BrowserStoreData], factory=dict) browsers = attr.ib(type=dict[str:BrowserStoreData], factory=dict)
version = attr.ib(type=str, default="2.0") version = attr.ib(type=str, default="2.0")
settings = attr.ib(type=Settings, factory=Settings) settings = attr.ib(type=SettingsStoreData, factory=SettingsStoreData)
user_settings = attr.ib(type=dict[str:Settings], factory=dict) user_settings = attr.ib(type=dict[str:SettingsStoreData], factory=dict)
@classmethod @classmethod
def from_dict(cls, data={}): def from_dict(cls, data={}):
@ -65,9 +65,10 @@ class ConfigStoreData:
for k, v in data.get("browsers", {}).items() for k, v in data.get("browsers", {}).items()
} }
user_settings = { user_settings = {
k: Settings.from_dict(v) for k, v in data.get("user_settings", {}).items() k: SettingsStoreData.from_dict(v)
for k, v in data.get("user_settings", {}).items()
} }
settings = Settings.from_dict(data.get("settings", {})) settings = SettingsStoreData.from_dict(data.get("settings", {}))
return cls( return cls(
**( **(
data data
@ -135,10 +136,10 @@ class BrowserModStore:
await self.updated() await self.updated()
def get_user_settings(self, name): def get_user_settings(self, name):
return self.data.user_settings.get(name, Settings()) return self.data.user_settings.get(name, SettingsStoreData())
async def set_user_settings(self, name, **data): async def set_user_settings(self, name, **data):
settings = self.data.user_settings.get(name, Settings()) settings = self.data.user_settings.get(name, SettingsStoreData())
settings.__dict__.update(data) settings.__dict__.update(data)
self.data.user_settings[name] = settings self.data.user_settings[name] = settings
await self.updated() await self.updated()

View File

@ -28,7 +28,7 @@ class BrowserModRegisteredBrowsersCard extends LitElement {
window.browser_mod.showPopup( window.browser_mod.showPopup(
"Unregister browser", "Unregister browser",
`Are you sure you want to unregister browser ${browserID}?`, `Are you sure you want to unregister Browser ${browserID}?`,
{ {
right_button: "Yes", right_button: "Yes",
right_button_action: unregisterCallback, right_button_action: unregisterCallback,
@ -37,6 +37,13 @@ class BrowserModRegisteredBrowsersCard extends LitElement {
); );
} }
register_cast() {
window.browser_mod.connection.sendMessage({
type: "browser_mod/register",
browserID: "CAST",
});
}
render() { render() {
return html` return html`
<ha-card header="Registered Browsers" outlined> <ha-card header="Registered Browsers" outlined>
@ -57,6 +64,15 @@ class BrowserModRegisteredBrowsersCard extends LitElement {
</ha-settings-row>` </ha-settings-row>`
)} )}
</div> </div>
${window.browser_mod.browsers["CAST"] === undefined
? html`
<div class="card-actions">
<mwc-button @click=${this.register_cast}>
Register CAST Browser
</mwc-button>
</div>
`
: ""}
</ha-card> </ha-card>
`; `;
} }

View File

@ -21,6 +21,7 @@ export const BrowserIDMixin = (SuperClass) => {
} }
get browserID() { get browserID() {
if (document.querySelector("hc-main")) return "CAST";
if (localStorage[ID_STORAGE_KEY]) return localStorage[ID_STORAGE_KEY]; if (localStorage[ID_STORAGE_KEY]) return localStorage[ID_STORAGE_KEY];
this.browserID = ""; this.browserID = "";
return this.browserID; return this.browserID;

View File

@ -13,6 +13,7 @@ export const ConnectionMixin = (SuperClass) => {
public browserEntities = {}; public browserEntities = {};
LOG(...args) { LOG(...args) {
return;
const dt = new Date(); const dt = new Date();
console.log(`${dt.toLocaleTimeString()}`, ...args); console.log(`${dt.toLocaleTimeString()}`, ...args);
} }

View File

@ -60,12 +60,12 @@ import { BrowserIDMixin } from "./browserID";
x Title templates x Title templates
- Tweaks - Tweaks
- Quickbar tweaks (ctrl+enter)? - Quickbar tweaks (ctrl+enter)?
- Card-mod preload x Card-mod preload
- Video player? - Video player?
- Media_seek - Media_seek
- Screensavers - Screensavers
- IMPORTANT: FIX DEFAULT HIDING OF ENTITIES - IMPORTANT: FIX DEFAULT HIDING OF ENTITIES
- Check functionality with CAST - may need to add frontend part as a lovelace resource X Check functionality with CAST - may need to add frontend part as a lovelace resource
*/ */
export class BrowserMod extends ServicesMixin( export class BrowserMod extends ServicesMixin(
PopupMixin( PopupMixin(

View File

@ -2,6 +2,12 @@ default_config:
demo: demo:
http:
use_x_forwarded_for: true
trusted_proxies:
- 172.17.0.4
# Update this as needed for testing with Cast
logger: logger:
default: warning default: warning
logs: logs: