Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bring back the prefix option #731

Open
caraar12345 opened this issue Jul 23, 2024 · 6 comments
Open

Bring back the prefix option #731

caraar12345 opened this issue Jul 23, 2024 · 6 comments

Comments

@caraar12345
Copy link

caraar12345 commented Jul 23, 2024

Hello!

It looks like before Browser Mod 2, eaed9cd allowed for the browser_mod YAML config to have a prefix setting so all Browser Mod entities could start browser_mod_ for example. However, it seems that this is no longer a thing in BM2.

Was this intentional or just something that didn't make it into the rewrite?

It'd be awesome if this could be brought back. For reference, I just found a lot of Screen lights in my Apple Home that I've filtered out with the entity glob light.*_screen, but being able to filter all Browser Mod entities with *.browser_mod_* would be so much better. I could also then filter all the BM entities from recorder!

Thank you!

@tommasomeli
Copy link

tommasomeli commented Nov 12, 2024

As a workaround, I wrote this automation that adds the “browser_mod_” prefix via javascript to all entities derived from the integration, a temporary solution while hopefully waiting for the “prefix” option to be restored
[FIXED]

alias: Browser Mod entities prefix
description: ""
triggers:
  - seconds: /5
    trigger: time_pattern
actions:
  - data:
      code: |
        (function() {
            const prefix = "browser_mod_";
            // Long-Lived Access Token, alternative: JSON.parse(localStorage.getItem('hassTokens')).access_token
            const access_token = "*******************************************************************************************************"
            const headers = {
                'Authorization': `Bearer ${access_token}`,
                'Content-Type': 'application/json',
            };
            fetch('/api/states', { method: 'GET', headers }).then(response => response.json()).then(states => {
                // Check whether entity.attributes.type == 'browser_mod' is not enough to retrieve all IDs
                // const ids = states.filter(entity => (entity.attributes.type == 'browser_mod')).map(entity => entity.attributes.browserID);
                const ids = [...new Set(
                    states
                        .filter(entity => /Browser path/.test(entity.attributes.friendly_name))
                        .map(entity => entity.attributes.friendly_name.split("Browser path").shift().trim().replace(/[\s\-]/g, '_').toLowerCase())
                )].filter(Boolean);
                const browserModEntities = states.filter(entity => ids.some(id => entity.entity_id.includes(id)) && !entity.entity_id.includes(`.${prefix}`));
                browserModEntities.map(entity => {
                    const new_entity_id = entity.entity_id.replace(/^([a-zA-Z0-9_]+)\.(.+)$/, `$1.${prefix}$2`);
                    // See https://spook.boo/entities#update-an-entitys-id
                    fetch(`/api/services/homeassistant/update_entity_id`, {
                        method: 'POST',
                        headers,
                        body: JSON.stringify({ entity_id: entity.entity_id, new_entity_id })
                    }).catch(error => console.error(error));
                });
            }).catch(error => console.error(error));
            // Optional: purge orphaned entities https://spook.boo/entities#delete-all-orphaned-entities
            fetch(`/api/services/homeassistant/delete_all_orphaned_entities`, { method: 'POST', headers }).catch(error => console.error(error));
        })();
    action: browser_mod.javascript

Requirements:

  • Long-lived access token
  • Spook integration for entity_id update via API
  • Browser MOD with registered browser

Change the prefix as desired.

@caraar12345
Copy link
Author

@tommasomeli you are awesome!

Just went to see how many Browser Mod entities I've made it up to...and somehow, almost 3500! So I'll delete all of those, then set up this script. Cheers!!

Screenshot 2024-11-12 at 13 39 16

@caraar12345
Copy link
Author

@tommasomeli seems this may not work so well.... every single one of my home assistant entities now has browser_mod prefixed 😱

@tommasomeli
Copy link

@tommasomeli seems this may not work so well.... every single one of my home assistant entities now has browser_mod prefixed 😱

Very strange, could you provide me a complete entity object where attributes.friendly_name contains the substring Browser path? I have prepared this JSFiddle to perform the fetch.

@caraar12345
Copy link
Author

Sure --

{
  "entity_id": "sensor.081981c6_4877cb9f_browser_path",
  "state": "unavailable",
  "attributes": {
    "restored": true,
    "icon": "mdi:web",
    "friendly_name": "Browser path",
    "supported_features": 0
  },
  "last_changed": "2024-11-13T13:23:38.837356+00:00",
  "last_reported": "2024-11-13T13:23:38.837356+00:00",
  "last_updated": "2024-11-13T13:23:38.837356+00:00",
  "context": {
    "id": "01JCJV38PNNNYNJS9MRHZSFQQJ",
    "parent_id": null,
    "user_id": null
  }
}

@tommasomeli
Copy link

tommasomeli commented Nov 13, 2024

@caraar12345 Ok I had not considered the case where attributes.friendly_name contained only the string Browser path. In my installation, the ID is automatically prepended to attributes.friendly_name, in your case I would have expected 081981c6_4877cb9f Browser path. In the other entities where attributes.friendly_name contains Browser path do you get the ID? Meanwhile, here is the updated automation for ignoring empty IDs (and thus avoiding renaming all entities)

alias: Browser Mod entities prefix
description: ""
triggers:
  - seconds: /5
    trigger: time_pattern
actions:
  - data:
      code: |
        (function() {
            const prefix = "browser_mod_";
            // Long-Lived Access Token, alternative: JSON.parse(localStorage.getItem('hassTokens')).access_token
            const access_token = "*******************************************************************************************************"
            const headers = {
                'Authorization': `Bearer ${access_token}`,
                'Content-Type': 'application/json',
            };
            fetch('/api/states', { method: 'GET', headers }).then(response => response.json()).then(states => {
                // Check whether entity.attributes.type == 'browser_mod' is not enough to retrieve all IDs
                // const ids = states.filter(entity => (entity.attributes.type == 'browser_mod')).map(entity => entity.attributes.browserID);
                const ids = [...new Set(
                    states
                        .filter(entity => /Browser path/.test(entity.attributes.friendly_name))
                        .map(entity => entity.attributes.friendly_name.split("Browser path").shift().trim().replace(/[\s\-]/g, '_').toLowerCase())
                )].filter(Boolean);
                const browserModEntities = states.filter(entity => ids.some(id => entity.entity_id.includes(id)) && !entity.entity_id.includes(`.${prefix}`));
                browserModEntities.map(entity => {
                    const new_entity_id = entity.entity_id.replace(/^([a-zA-Z0-9_]+)\.(.+)$/, `$1.${prefix}$2`);
                    // See https://spook.boo/entities#update-an-entitys-id
                    fetch(`/api/services/homeassistant/update_entity_id`, {
                        method: 'POST',
                        headers,
                        body: JSON.stringify({ entity_id: entity.entity_id, new_entity_id })
                    }).catch(error => console.error(error));
                });
            }).catch(error => console.error(error));
            // Optional: purge orphaned entities https://spook.boo/entities#delete-all-orphaned-entities
            fetch(`/api/services/homeassistant/delete_all_orphaned_entities`, { method: 'POST', headers }).catch(error => console.error(error));
        })();
    action: browser_mod.javascript

Instead, here is the automation to remove the prefix from all entities (disable the previous one before activating it)

alias: Browser Mod entities prefix remove
description: ""
triggers:
  - seconds: /5
    trigger: time_pattern
actions:
  - data:
      code: |
        (function() {
            const prefix = "browser_mod_";
            // Long-Lived Access Token, alternative: JSON.parse(localStorage.getItem('hassTokens')).access_token
            const access_token = "*******************************************************************************************************"
            const headers = {
                'Authorization': `Bearer ${access_token}`,
                'Content-Type': 'application/json',
            };
            fetch('/api/states', { method: 'GET', headers }).then(response => response.json()).then(states => {
                states.filter(entity => entity.entity_id.includes(prefix)).map(entity => {
                    const new_entity_id = entity.entity_id.replace(prefix, "");
                    // See https://spook.boo/entities#update-an-entitys-id
                    fetch(`/api/services/homeassistant/update_entity_id`, {
                        method: 'POST',
                        headers,
                        body: JSON.stringify({ entity_id: entity.entity_id, new_entity_id })
                    }).catch(error => console.error(error));
                });
            }).catch(error => console.error(error));
            // Optional: purge orphaned entities https://spook.boo/entities#delete-all-orphaned-entities
            fetch(`/api/services/homeassistant/delete_all_orphaned_entities`, { method: 'POST', headers }).catch(error => console.error(error));
        })();
    action: browser_mod.javascript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants