Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 3 additions & 28 deletions homeassistant/components/media_player/plex.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"""
import json
import logging
import os
from datetime import timedelta

import requests
Expand All @@ -22,6 +21,7 @@
DEVICE_DEFAULT_NAME, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.event import track_utc_time_change
from homeassistant.util.json import load_json, save_json

REQUIREMENTS = ['plexapi==3.0.3']

Expand All @@ -48,35 +48,10 @@
})


def config_from_file(filename, config=None):
"""Small configuration file management function."""
if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error("Saving config file failed: %s", error)
return False
return True
else:
# We're reading config
if os.path.isfile(filename):
try:
with open(filename, 'r') as fdesc:
return json.loads(fdesc.read())
except IOError as error:
_LOGGER.error("Reading config file failed: %s", error)
# This won't work yet
return False
else:
return {}


def setup_platform(hass, config, add_devices_callback, discovery_info=None):
"""Set up the Plex platform."""
# get config from plex.conf
file_config = config_from_file(hass.config.path(PLEX_CONFIG_FILE))
file_config = load_json(hass.config.path(PLEX_CONFIG_FILE))

if file_config:
# Setup a configured PlexServer
Expand Down Expand Up @@ -146,7 +121,7 @@ def setup_plexserver(
_LOGGER.info("Discovery configuration done")

# Save config
if not config_from_file(
if not save_json(
hass.config.path(PLEX_CONFIG_FILE), {host: {
'token': token,
'ssl': has_ssl,
Expand Down
50 changes: 50 additions & 0 deletions homeassistant/util/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""JSON utility functions."""
import logging
from typing import Union, List, Dict

import json

from homeassistant.exceptions import HomeAssistantError

_LOGGER = logging.getLogger(__name__)


def load_json(filename: str) -> Union[List, Dict]:
"""Load JSON data from a file and return as dict or list.

Defaults to returning empty dict if file is not found.
"""
try:
with open(filename, encoding='utf-8') as fdesc:
return json.loads(fdesc.read())
except FileNotFoundError:
# This is not a fatal error
_LOGGER.debug('JSON file not found: %s', filename)
except ValueError as error:
_LOGGER.exception('Could not parse JSON content: %s', filename)
raise HomeAssistantError(error)
except OSError as error:
_LOGGER.exception('JSON file reading failed: %s', filename)
raise HomeAssistantError(error)
return {} # (also evaluates to False)


def save_json(filename: str, config: Union[List, Dict]):
"""Save JSON data to a file.

Returns True on success.
"""
try:
data = json.dumps(config, sort_keys=True, indent=4)
with open(filename, 'w', encoding='utf-8') as fdesc:
fdesc.write(data)
return True
except TypeError as error:
_LOGGER.exception('Failed to serialize to JSON: %s',
filename)
raise HomeAssistantError(error)
except OSError as error:
_LOGGER.exception('Saving JSON file failed: %s',
filename)
raise HomeAssistantError(error)
return False