<commit_before>"""
Support for interface with an Orange Livebox Play TV appliance.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.liveboxplaytv/
"""
import asyncio
import logging
from datetime import timedelta

import requests
import voluptuous as vol

from homeassistant.components.media_player import (
    SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_PLAY,
    SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
    SUPPORT_VOLUME_STEP, SUPPORT_VOLUME_MUTE, SUPPORT_SELECT_SOURCE,
    MEDIA_TYPE_CHANNEL, MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
    CONF_HOST, CONF_PORT, STATE_ON, STATE_OFF, STATE_PLAYING,
    STATE_PAUSED, CONF_NAME)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util

REQUIREMENTS = ['liveboxplaytv==2.0.2', 'pyteleloisirs==3.4']

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Livebox Play TV'
DEFAULT_PORT = 8080

SUPPORT_LIVEBOXPLAYTV = SUPPORT_TURN_OFF | SUPPORT_TURN_ON | \
    SUPPORT_NEXT_TRACK | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | \
    SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_MUTE | SUPPORT_SELECT_SOURCE | \
    SUPPORT_PLAY

MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST): cv.string,
    vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Orange Livebox Play TV platform."""
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    name = config.get(CONF_NAME)

    livebox_devices = []

    try:
        device = LiveboxPlayTvDevice(host, port, name)
        livebox_devices.append(device)
    except IOError:
        _LOGGER.error("Failed to connect to Livebox Play TV at %s:%s. "
                      "Please check your configuration", host, port)
    async_add_devices(livebox_devices, True)


class LiveboxPlayTvDevice(MediaPlayerDevice):
    """Representation of an Orange Livebox Play TV."""

    def __init__(self, host, port, name):
        """Initialize the Livebox Play TV device."""
        from liveboxplaytv import LiveboxPlayTv
        self._client = LiveboxPlayTv(host, port)
        # Assume that the appliance is not muted
        self._muted = False
        self._name = name
        self._current_source = None
        self._state = None
        self._channel_list = {}
        self._current_channel = None
        self._current_program = None
        self._media_duration = None
        self._media_remaining_time = None
        self._media_image_url = None
        self._media_last_updated = None

    @asyncio.coroutine
    def async_update(self):
        """Retrieve the latest data."""
        import pyteleloisirs
        try:
            self._state = self.refresh_state()
            # Update current channel
            channel = self._client.channel
            if channel is not None:
                self._current_channel = channel
                program = yield from \
                    self._client.async_get_current_program()
                if program and self._current_program != program.get('name'):
                    self._current_program = program.get('name')
                    # Media progress info
                    self._media_duration = \
                        pyteleloisirs.get_program_duration(program)
                    rtime = pyteleloisirs.get_remaining_time(program)
                    if rtime != self._media_remaining_time:
                        self._media_remaining_time = rtime
                        self._media_last_updated = dt_util.utcnow()
                # Set media image to current program if a thumbnail is
                # available. Otherwise we'll use the channel's image.
                img_size = 800
                prg_img_url = yield from \
                    self._client.async_get_current_program_image(img_size)
                if prg_img_url:
                    self._media_image_url = prg_img_url
                else:
                    chan_img_url = \
                        self._client.get_current_channel_image(img_size)<commit_msg>Fix liveboxplaytv empty channel list (#15404)<commit_after>"""
Support for interface with an Orange Livebox Play TV appliance.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.liveboxplaytv/
"""
import asyncio
import logging
from datetime import timedelta

import requests
import voluptuous as vol

from homeassistant.components.media_player import (
    SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_PLAY,
    SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PREVIOUS_TRACK,
    SUPPORT_VOLUME_STEP, SUPPORT_VOLUME_MUTE, SUPPORT_SELECT_SOURCE,
    MEDIA_TYPE_CHANNEL, MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.const import (
    CONF_HOST, CONF_PORT, STATE_ON, STATE_OFF, STATE_PLAYING,
    STATE_PAUSED, CONF_NAME)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util

REQUIREMENTS = ['liveboxplaytv==2.0.2', 'pyteleloisirs==3.4']

_LOGGER = logging.getLogger(__name__)

DEFAULT_NAME = 'Livebox Play TV'
DEFAULT_PORT = 8080

SUPPORT_LIVEBOXPLAYTV = SUPPORT_TURN_OFF | SUPPORT_TURN_ON | \
    SUPPORT_NEXT_TRACK | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | \
    SUPPORT_VOLUME_STEP | SUPPORT_VOLUME_MUTE | SUPPORT_SELECT_SOURCE | \
    SUPPORT_PLAY

MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=1)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_HOST): cv.string,
    vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})


@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Orange Livebox Play TV platform."""
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    name = config.get(CONF_NAME)

    livebox_devices = []

    try:
        device = LiveboxPlayTvDevice(host, port, name)
        livebox_devices.append(device)
    except IOError:
        _LOGGER.error("Failed to connect to Livebox Play TV at %s:%s. "
                      "Please check your configuration", host, port)
    async_add_devices(livebox_devices, True)


class LiveboxPlayTvDevice(MediaPlayerDevice):
    """Representation of an Orange Livebox Play TV."""

    def __init__(self, host, port, name):
        """Initialize the Livebox Play TV device."""
        from liveboxplaytv import LiveboxPlayTv
        self._client = LiveboxPlayTv(host, port)
        # Assume that the appliance is not muted
        self._muted = False
        self._name = name
        self._current_source = None
        self._state = None
        self._channel_list = {}
        self._current_channel = None
        self._current_program = None
        self._media_duration = None
        self._media_remaining_time = None
        self._media_image_url = None
        self._media_last_updated = None

    @asyncio.coroutine
    def async_update(self):
        """Retrieve the latest data."""
        import pyteleloisirs
        try:
            self._state = self.refresh_state()
            # Update channel list
            self.refresh_channel_list()
            # Update current channel
            channel = self._client.channel
            if channel is not None:
                self._current_channel = channel
                program = yield from \
                    self._client.async_get_current_program()
                if program and self._current_program != program.get('name'):
                    self._current_program = program.get('name')
                    # Media progress info
                    self._media_duration = \
                        pyteleloisirs.get_program_duration(program)
                    rtime = pyteleloisirs.get_remaining_time(program)
                    if rtime != self._media_remaining_time:
                        self._media_remaining_time = rtime
                        self._media_last_updated = dt_util.utcnow()
                # Set media image to current program if a thumbnail is
                # available. Otherwise we'll use the channel's image.
                img_size = 800
                prg_img_url = yield from \
                    self._client.async_get_current_program_image(img_size)
                if prg_img_url:
                    self._media_image_url = prg_img_url
                else:
                    chan_img_url = \
                        self._client.get_current_channel_image(img_size)
{'fraction_non_alphanumeric': 0.07319004524886878, 'fraction_numerical': 0.003959276018099547, 'mean_word_length': 2.611519607843137, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '526702', 'n_tokens_mistral': 2704, 'n_tokens_neox': 2557, 'n_words': 580}