<commit_before>"""Provide functionality to interact with the vlc telnet interface."""
import logging

from python_telnet_vlc import (
    CommandError,
    ConnectionError as ConnErr,
    LuaError,
    ParseError,
    VLCTelnet,
)
import voluptuous as vol

from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity
from homeassistant.components.media_player.const import (
    MEDIA_TYPE_MUSIC,
    SUPPORT_CLEAR_PLAYLIST,
    SUPPORT_NEXT_TRACK,
    SUPPORT_PAUSE,
    SUPPORT_PLAY,
    SUPPORT_PLAY_MEDIA,
    SUPPORT_PREVIOUS_TRACK,
    SUPPORT_SEEK,
    SUPPORT_SHUFFLE_SET,
    SUPPORT_STOP,
    SUPPORT_VOLUME_MUTE,
    SUPPORT_VOLUME_SET,
)
from homeassistant.const import (
    CONF_HOST,
    CONF_NAME,
    CONF_PASSWORD,
    CONF_PORT,
    STATE_IDLE,
    STATE_PAUSED,
    STATE_PLAYING,
    STATE_UNAVAILABLE,
)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util

_LOGGER = logging.getLogger(__name__)

DOMAIN = "vlc_telnet"

DEFAULT_NAME = "VLC-TELNET"
DEFAULT_PORT = 4212
MAX_VOLUME = 500

SUPPORT_VLC = (
    SUPPORT_CLEAR_PLAYLIST
    | SUPPORT_NEXT_TRACK
    | SUPPORT_PAUSE
    | SUPPORT_PLAY
    | SUPPORT_PLAY_MEDIA
    | SUPPORT_PREVIOUS_TRACK
    | SUPPORT_SEEK
    | SUPPORT_SHUFFLE_SET
    | SUPPORT_STOP
    | SUPPORT_VOLUME_MUTE
    | SUPPORT_VOLUME_SET
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_HOST): cv.string,
        vol.Required(CONF_PASSWORD): cv.string,
        vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.positive_int,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    }
)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the vlc platform."""
    add_entities(
        [
            VlcDevice(
                config.get(CONF_NAME),
                config.get(CONF_HOST),
                config.get(CONF_PORT),
                config.get(CONF_PASSWORD),
            )
        ],
        True,
    )


class VlcDevice(MediaPlayerEntity):
    """Representation of a vlc player."""

    def __init__(self, name, host, port, passwd):
        """Initialize the vlc device."""
        self._name = name
        self._volume = None
        self._muted = None
        self._state = STATE_UNAVAILABLE
        self._media_position_updated_at = None
        self._media_position = None
        self._media_duration = None
        self._host = host
        self._port = port
        self._password = <PASSWORD>
        self._vlc = None
        self._available = True
        self._volume_bkp = 0
        self._media_artist = ""
        self._media_title = ""

    def update(self):
        """Get the latest details from the device."""
        if self._vlc is None:
            try:
                self._vlc = VLCTelnet(self._host, self._password, self._port)
            except (ConnErr, EOFError) as err:
                if self._available:
                    _LOGGER.error("Connection error: %s", err)
                    self._available = False
                self._vlc = None
                return

            self._state = STATE_IDLE
            self._available = True

        try:
            status = self._vlc.status()
            _LOGGER.debug("Status: %s", status)

            if status:
                if "volume" in status:
                    self._volume = int(status["volume"]) / 500.0
                else:
                    self._volume = None
                if "state" in status:
                    state = status["state"]
                    if state == "playing":
                        self._state = STATE_PLAYING
                    elif state == "paused":
                        self._state = STATE_PAUSED
                    else:
                        self._state = STATE_IDLE
                else:
                    self._state = STATE_IDLE

            if self._state != STATE_IDLE:
                self._media_duration = self._vlc.get_length()
                vlc_position = self._vlc.get_time()

                # Check if current position is stale.
                if vlc_position != self._media_position:
                    self._media_position_updated_at = dt_util.utcnow()
                    self._media_position = vlc_position

            info = self._vlc.info()
            _LOGGER.debug("Info: %s", info)

            if info:
                self._media_artist = info.get(0, {}).get("artist")
                self._media_title = info.get(0, {}).get("title")

        except (CommandError, LuaError, ParseError) as err:
            _LOGGER.error("Command error: %s", err)
        except (ConnErr, EOFError) as err:
            if self._available:
                _LOGGER.error("Connection error: %s", err)
                self._available = False
            self._vlc = None<commit_msg>Fallback to filename for title in vlc_telnet (#48438)<commit_after>"""Provide functionality to interact with the vlc telnet interface."""
import logging

from python_telnet_vlc import (
    CommandError,
    ConnectionError as ConnErr,
    LuaError,
    ParseError,
    VLCTelnet,
)
import voluptuous as vol

from homeassistant.components.media_player import PLATFORM_SCHEMA, MediaPlayerEntity
from homeassistant.components.media_player.const import (
    MEDIA_TYPE_MUSIC,
    SUPPORT_CLEAR_PLAYLIST,
    SUPPORT_NEXT_TRACK,
    SUPPORT_PAUSE,
    SUPPORT_PLAY,
    SUPPORT_PLAY_MEDIA,
    SUPPORT_PREVIOUS_TRACK,
    SUPPORT_SEEK,
    SUPPORT_SHUFFLE_SET,
    SUPPORT_STOP,
    SUPPORT_VOLUME_MUTE,
    SUPPORT_VOLUME_SET,
)
from homeassistant.const import (
    CONF_HOST,
    CONF_NAME,
    CONF_PASSWORD,
    CONF_PORT,
    STATE_IDLE,
    STATE_PAUSED,
    STATE_PLAYING,
    STATE_UNAVAILABLE,
)
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util

_LOGGER = logging.getLogger(__name__)

DOMAIN = "vlc_telnet"

DEFAULT_NAME = "VLC-TELNET"
DEFAULT_PORT = 4212
MAX_VOLUME = 500

SUPPORT_VLC = (
    SUPPORT_CLEAR_PLAYLIST
    | SUPPORT_NEXT_TRACK
    | SUPPORT_PAUSE
    | SUPPORT_PLAY
    | SUPPORT_PLAY_MEDIA
    | SUPPORT_PREVIOUS_TRACK
    | SUPPORT_SEEK
    | SUPPORT_SHUFFLE_SET
    | SUPPORT_STOP
    | SUPPORT_VOLUME_MUTE
    | SUPPORT_VOLUME_SET
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_HOST): cv.string,
        vol.Required(CONF_PASSWORD): cv.string,
        vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.positive_int,
        vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    }
)


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the vlc platform."""
    add_entities(
        [
            VlcDevice(
                config.get(CONF_NAME),
                config.get(CONF_HOST),
                config.get(CONF_PORT),
                config.get(CONF_PASSWORD),
            )
        ],
        True,
    )


class VlcDevice(MediaPlayerEntity):
    """Representation of a vlc player."""

    def __init__(self, name, host, port, passwd):
        """Initialize the vlc device."""
        self._name = name
        self._volume = None
        self._muted = None
        self._state = STATE_UNAVAILABLE
        self._media_position_updated_at = None
        self._media_position = None
        self._media_duration = None
        self._host = host
        self._port = port
        self._password = <PASSWORD>
        self._vlc = None
        self._available = True
        self._volume_bkp = 0
        self._media_artist = ""
        self._media_title = ""

    def update(self):
        """Get the latest details from the device."""
        if self._vlc is None:
            try:
                self._vlc = VLCTelnet(self._host, self._password, self._port)
            except (ConnErr, EOFError) as err:
                if self._available:
                    _LOGGER.error("Connection error: %s", err)
                    self._available = False
                self._vlc = None
                return

            self._state = STATE_IDLE
            self._available = True

        try:
            status = self._vlc.status()
            _LOGGER.debug("Status: %s", status)

            if status:
                if "volume" in status:
                    self._volume = int(status["volume"]) / 500.0
                else:
                    self._volume = None
                if "state" in status:
                    state = status["state"]
                    if state == "playing":
                        self._state = STATE_PLAYING
                    elif state == "paused":
                        self._state = STATE_PAUSED
                    else:
                        self._state = STATE_IDLE
                else:
                    self._state = STATE_IDLE

            if self._state != STATE_IDLE:
                self._media_duration = self._vlc.get_length()
                vlc_position = self._vlc.get_time()

                # Check if current position is stale.
                if vlc_position != self._media_position:
                    self._media_position_updated_at = dt_util.utcnow()
                    self._media_position = vlc_position

            info = self._vlc.info()
            _LOGGER.debug("Info: %s", info)

            if info:
                self._media_artist = info.get(0, {}).get("artist")
                self._media_title = info.get(0, {}).get("title")

                if not self._media_title:
                    # Fall back to filename.
                    data_info = info.get("data")
                    if data_info:
                        self._media_title = data_info["filename"]

        except (CommandError, LuaError, ParseError) as err:
            _LOGGER.error("Command error: %s", err)
        except (ConnErr, EOFError) as err:
            if self._available:
                _LOGGER.error("Connection error: %s", err)
                self._available = False
            self._vlc = None
{'fraction_non_alphanumeric': 0.0849009154008651, 'fraction_numerical': 0.0033195855547731618, 'mean_word_length': 1.8365192582025678, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, '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': '2554035', 'n_tokens_mistral': 3130, 'n_tokens_neox': 2905, 'n_words': 611}