blakeblackshear / frigate-hass-integration

Frigate integration for Home Assistant
MIT License
660 stars 110 forks source link

Fix media browsing bug with events where `top_score` is `0` #626

Closed jeffc closed 5 months ago

jeffc commented 5 months ago

Fix a bug where home assistant media browser fails to load clips if any have a top_score of zero.

The errors look like this:

  File "/config/custom_components/frigate/media_source.py", line 774, in _browse_events
    event_items = self._build_event_response(identifier, events)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/frigate/media_source.py", line 860, in _build_event_response
    title=f"{dt.datetime.fromtimestamp(event['start_time'], DEFAULT_TIME_ZONE).strftime(DATE_STR_FORMAT)} [{duration}s, {event['label'].capitalize()} {int((event['data'].get('top_score') or event['top_score'])*100)}%]",
                                                                                                                                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

This was mostly fixed in this commit, but python evaluates (0 or None) as None (interestingly, it evaluates (None or 0) as 0). This means that if event['top_score'] is 0 (which can happen if you create the event through an API call, for instance... that's how I found this bug) and event['data'].get('top_score') is None, the expression evaluates to int(None * 100), which causes the error.

This fixes it by adding a default case of 0.

My event that triggered this bug, as reported by /api/events?limit=50&has_clip=1&include_thumbnails=0:

...
  {
    "box": null,
    "camera": "doorbell",
    "data": {
      "score": 0,
      "top_score": 0,
      "type": "api"
    },
    "end_time": 1707375125.15415,
    "false_positive": null,
    "has_clip": true,
    "has_snapshot": true,
    "id": "1707375090.154146-rfnk4j",
    "label": "testevent",
    "plus_id": null,
    "retain_indefinitely": false,
    "start_time": 1707375085.15415,
    "sub_label": null,
    "top_score": null,
    "zones": []
  },
...
codecov[bot] commented 5 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (cac06ae) 100.00% compared to head (cf98933) 100.00%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #626 +/- ## ========================================= Coverage 100.00% 100.00% ========================================= Files 16 16 Lines 2017 2017 ========================================= Hits 2017 2017 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

dermotduffy commented 5 months ago

Thanks @jeffc !