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
12 changes: 9 additions & 3 deletions src/linkplay/bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -153,9 +153,15 @@ async def update_status(self) -> None:

self.properties = fixup_player_properties(properties)
if self.bridge.device.manufacturer == MANUFACTURER_WIIM:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
try:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
except LinkPlayInvalidDataException as exc:
if getattr(exc, "data", None) == "Failed":
self.metainfo = {}
else:
raise
else:
self.metainfo = {}

Expand Down
20 changes: 11 additions & 9 deletions src/linkplay/consts.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -473,18 +473,18 @@ def __str__(self):

def __repr__(self):
return self.value


class MetaInfo(StrEnum):

class MetaInfo(StrEnum):
METADATA = "metaData"

def __str__(self):
return self.value

def __repr__(self):
return self.value

return self.value


class MetaInfoMetaData(StrEnum):
"""Defines the metadata within the metainfo."""

Expand All@@ -496,25 +496,27 @@ class MetaInfoMetaData(StrEnum):
BIT_DEPTH = "bitDepth"
BIT_RATE = "bitRate"
TRACK_ID = "trackId"

def __str__(self):
return self.value

def __repr__(self):
return self.value
return self.value


class AudioOutputHwMode(StrEnum):
"""Defines a output mode for the hardware."""

OPTICAL = "1"
LINE_OUT = "2"
COAXIAL = "3"
HEADPHONES = "4"


# Map between a play mode and how to activate the play mode
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { # case sensitive!
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line-out",
AudioOutputHwMode.COAXIAL: "co-axial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
}
4 changes: 3 additions & 1 deletion src/linkplay/exceptions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,4 +7,6 @@ class LinkPlayRequestException(LinkPlayException):


class LinkPlayInvalidDataException(LinkPlayException):
pass
def __init__(self, message: str = "Invalid data received", data: str | None = None):
super().__init__(message)
self.data = data
2 changes: 1 addition & 1 deletion src/linkplay/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,7 @@ async def session_call_api_json(
except json.JSONDecodeError as jsonexc:
url = API_ENDPOINT.format(endpoint, command)
raise LinkPlayInvalidDataException(
f"Unexpected JSON ({result}) received from '{url}'"
message=f"Unexpected JSON ({result}) received from '{url}'", data=result
) from jsonexc


Expand Down
40 changes: 39 additions & 1 deletion tests/linkplay/test_bridge.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
"""Test bridge functionality."""

from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
from linkplay.bridge import (
Expand All@@ -22,6 +22,7 @@
PlayingStatus,
)
from linkplay.endpoint import LinkPlayApiEndpoint
from linkplay.manufacturers import MANUFACTURER_WIIM


def test_device_name():
Expand DownExpand Up@@ -561,3 +562,40 @@ async def test_update_status_does_not_trigger_controller_on_no_mode_change(mock_
await player.update_status()

mock_bridge.device.controller.assert_not_called()


async def test_meta_info_failed_handling():
"""Test that the player handles a failed META_INFO request correctly."""

async def mock_session_call_api_json_side_effect(endpoint, session, command):
if command == LinkPlayCommand.META_INFO:
return "Failed"
return "{}"

# Mock the session_call_api function
with patch(
"linkplay.utils.session_call_api",
new=AsyncMock(side_effect=mock_session_call_api_json_side_effect),
) as mock_api:
# Mock the bridge and its device
mock_bridge = LinkPlayBridge(
endpoint=LinkPlayApiEndpoint(
protocol="http", port=80, endpoint="1.2.3.4", session=None
)
)
mock_bridge.device = MagicMock()
mock_bridge.device.manufacturer = (
MANUFACTURER_WIIM # Set the manufacturer to WiiM
)

# Create a LinkPlayPlayer instance with the mocked bridge
player = LinkPlayPlayer(mock_bridge)

# Simulate the META_INFO request and exception handling
await player.update_status()

# Verify that metainfo is set to an empty dictionary after the exception
assert player.metainfo == {}

# Verify that the mocked function was called with the correct command
mock_api.assert_called_with("http://1.2.3.4", None, LinkPlayCommand.META_INFO)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Handle "failed" returned as plain text to the WiiM metainfo command by silamon · Pull Request #93 · Velleman/python-linkplay · GitHub
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
12 changes: 9 additions & 3 deletions src/linkplay/bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -153,9 +153,15 @@ async def update_status(self) -> None:

self.properties = fixup_player_properties(properties)
if self.bridge.device.manufacturer == MANUFACTURER_WIIM:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
try:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
except LinkPlayInvalidDataException as exc:
if getattr(exc, "data", None) == "Failed":
self.metainfo = {}
else:
raise
else:
self.metainfo = {}

Expand Down
20 changes: 11 additions & 9 deletions src/linkplay/consts.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -473,18 +473,18 @@ def __str__(self):

def __repr__(self):
return self.value


class MetaInfo(StrEnum):

class MetaInfo(StrEnum):
METADATA = "metaData"

def __str__(self):
return self.value

def __repr__(self):
return self.value

return self.value


class MetaInfoMetaData(StrEnum):
"""Defines the metadata within the metainfo."""

Expand All@@ -496,25 +496,27 @@ class MetaInfoMetaData(StrEnum):
BIT_DEPTH = "bitDepth"
BIT_RATE = "bitRate"
TRACK_ID = "trackId"

def __str__(self):
return self.value

def __repr__(self):
return self.value
return self.value


class AudioOutputHwMode(StrEnum):
"""Defines a output mode for the hardware."""

OPTICAL = "1"
LINE_OUT = "2"
COAXIAL = "3"
HEADPHONES = "4"


# Map between a play mode and how to activate the play mode
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { # case sensitive!
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line-out",
AudioOutputHwMode.COAXIAL: "co-axial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
}
4 changes: 3 additions & 1 deletion src/linkplay/exceptions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,4 +7,6 @@ class LinkPlayRequestException(LinkPlayException):


class LinkPlayInvalidDataException(LinkPlayException):
pass
def __init__(self, message: str = "Invalid data received", data: str | None = None):
super().__init__(message)
self.data = data
2 changes: 1 addition & 1 deletion src/linkplay/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,7 @@ async def session_call_api_json(
except json.JSONDecodeError as jsonexc:
url = API_ENDPOINT.format(endpoint, command)
raise LinkPlayInvalidDataException(
f"Unexpected JSON ({result}) received from '{url}'"
message=f"Unexpected JSON ({result}) received from '{url}'", data=result
) from jsonexc


Expand Down
40 changes: 39 additions & 1 deletion tests/linkplay/test_bridge.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
"""Test bridge functionality."""

from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
from linkplay.bridge import (
Expand All@@ -22,6 +22,7 @@
PlayingStatus,
)
from linkplay.endpoint import LinkPlayApiEndpoint
from linkplay.manufacturers import MANUFACTURER_WIIM


def test_device_name():
Expand DownExpand Up@@ -561,3 +562,40 @@ async def test_update_status_does_not_trigger_controller_on_no_mode_change(mock_
await player.update_status()

mock_bridge.device.controller.assert_not_called()


async def test_meta_info_failed_handling():
"""Test that the player handles a failed META_INFO request correctly."""

async def mock_session_call_api_json_side_effect(endpoint, session, command):
if command == LinkPlayCommand.META_INFO:
return "Failed"
return "{}"

# Mock the session_call_api function
with patch(
"linkplay.utils.session_call_api",
new=AsyncMock(side_effect=mock_session_call_api_json_side_effect),
) as mock_api:
# Mock the bridge and its device
mock_bridge = LinkPlayBridge(
endpoint=LinkPlayApiEndpoint(
protocol="http", port=80, endpoint="1.2.3.4", session=None
)
)
mock_bridge.device = MagicMock()
mock_bridge.device.manufacturer = (
MANUFACTURER_WIIM # Set the manufacturer to WiiM
)

# Create a LinkPlayPlayer instance with the mocked bridge
player = LinkPlayPlayer(mock_bridge)

# Simulate the META_INFO request and exception handling
await player.update_status()

# Verify that metainfo is set to an empty dictionary after the exception
assert player.metainfo == {}

# Verify that the mocked function was called with the correct command
mock_api.assert_called_with("http://1.2.3.4", None, LinkPlayCommand.META_INFO)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Handle "failed" returned as plain text to the WiiM metainfo command by silamon · Pull Request #93 · Velleman/python-linkplay · GitHub
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
12 changes: 9 additions & 3 deletions src/linkplay/bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -153,9 +153,15 @@ async def update_status(self) -> None:

self.properties = fixup_player_properties(properties)
if self.bridge.device.manufacturer == MANUFACTURER_WIIM:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
try:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
except LinkPlayInvalidDataException as exc:
if getattr(exc, "data", None) == "Failed":
self.metainfo = {}
else:
raise
else:
self.metainfo = {}

Expand Down
20 changes: 11 additions & 9 deletions src/linkplay/consts.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -473,18 +473,18 @@ def __str__(self):

def __repr__(self):
return self.value


class MetaInfo(StrEnum):

class MetaInfo(StrEnum):
METADATA = "metaData"

def __str__(self):
return self.value

def __repr__(self):
return self.value

return self.value


class MetaInfoMetaData(StrEnum):
"""Defines the metadata within the metainfo."""

Expand All@@ -496,25 +496,27 @@ class MetaInfoMetaData(StrEnum):
BIT_DEPTH = "bitDepth"
BIT_RATE = "bitRate"
TRACK_ID = "trackId"

def __str__(self):
return self.value

def __repr__(self):
return self.value
return self.value


class AudioOutputHwMode(StrEnum):
"""Defines a output mode for the hardware."""

OPTICAL = "1"
LINE_OUT = "2"
COAXIAL = "3"
HEADPHONES = "4"


# Map between a play mode and how to activate the play mode
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { # case sensitive!
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line-out",
AudioOutputHwMode.COAXIAL: "co-axial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
}
4 changes: 3 additions & 1 deletion src/linkplay/exceptions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,4 +7,6 @@ class LinkPlayRequestException(LinkPlayException):


class LinkPlayInvalidDataException(LinkPlayException):
pass
def __init__(self, message: str = "Invalid data received", data: str | None = None):
super().__init__(message)
self.data = data
2 changes: 1 addition & 1 deletion src/linkplay/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,7 @@ async def session_call_api_json(
except json.JSONDecodeError as jsonexc:
url = API_ENDPOINT.format(endpoint, command)
raise LinkPlayInvalidDataException(
f"Unexpected JSON ({result}) received from '{url}'"
message=f"Unexpected JSON ({result}) received from '{url}'", data=result
) from jsonexc


Expand Down
40 changes: 39 additions & 1 deletion tests/linkplay/test_bridge.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
"""Test bridge functionality."""

from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
from linkplay.bridge import (
Expand All@@ -22,6 +22,7 @@
PlayingStatus,
)
from linkplay.endpoint import LinkPlayApiEndpoint
from linkplay.manufacturers import MANUFACTURER_WIIM


def test_device_name():
Expand DownExpand Up@@ -561,3 +562,40 @@ async def test_update_status_does_not_trigger_controller_on_no_mode_change(mock_
await player.update_status()

mock_bridge.device.controller.assert_not_called()


async def test_meta_info_failed_handling():
"""Test that the player handles a failed META_INFO request correctly."""

async def mock_session_call_api_json_side_effect(endpoint, session, command):
if command == LinkPlayCommand.META_INFO:
return "Failed"
return "{}"

# Mock the session_call_api function
with patch(
"linkplay.utils.session_call_api",
new=AsyncMock(side_effect=mock_session_call_api_json_side_effect),
) as mock_api:
# Mock the bridge and its device
mock_bridge = LinkPlayBridge(
endpoint=LinkPlayApiEndpoint(
protocol="http", port=80, endpoint="1.2.3.4", session=None
)
)
mock_bridge.device = MagicMock()
mock_bridge.device.manufacturer = (
MANUFACTURER_WIIM # Set the manufacturer to WiiM
)

# Create a LinkPlayPlayer instance with the mocked bridge
player = LinkPlayPlayer(mock_bridge)

# Simulate the META_INFO request and exception handling
await player.update_status()

# Verify that metainfo is set to an empty dictionary after the exception
assert player.metainfo == {}

# Verify that the mocked function was called with the correct command
mock_api.assert_called_with("http://1.2.3.4", None, LinkPlayCommand.META_INFO)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Handle "failed" returned as plain text to the WiiM metainfo command by silamon · Pull Request #93 · Velleman/python-linkplay · GitHub
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
12 changes: 9 additions & 3 deletions src/linkplay/bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -153,9 +153,15 @@ async def update_status(self) -> None:

self.properties = fixup_player_properties(properties)
if self.bridge.device.manufacturer == MANUFACTURER_WIIM:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
try:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
except LinkPlayInvalidDataException as exc:
if getattr(exc, "data", None) == "Failed":
self.metainfo = {}
else:
raise
else:
self.metainfo = {}

Expand Down
20 changes: 11 additions & 9 deletions src/linkplay/consts.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -473,18 +473,18 @@ def __str__(self):

def __repr__(self):
return self.value


class MetaInfo(StrEnum):

class MetaInfo(StrEnum):
METADATA = "metaData"

def __str__(self):
return self.value

def __repr__(self):
return self.value

return self.value


class MetaInfoMetaData(StrEnum):
"""Defines the metadata within the metainfo."""

Expand All@@ -496,25 +496,27 @@ class MetaInfoMetaData(StrEnum):
BIT_DEPTH = "bitDepth"
BIT_RATE = "bitRate"
TRACK_ID = "trackId"

def __str__(self):
return self.value

def __repr__(self):
return self.value
return self.value


class AudioOutputHwMode(StrEnum):
"""Defines a output mode for the hardware."""

OPTICAL = "1"
LINE_OUT = "2"
COAXIAL = "3"
HEADPHONES = "4"


# Map between a play mode and how to activate the play mode
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { # case sensitive!
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line-out",
AudioOutputHwMode.COAXIAL: "co-axial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
}
4 changes: 3 additions & 1 deletion src/linkplay/exceptions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,4 +7,6 @@ class LinkPlayRequestException(LinkPlayException):


class LinkPlayInvalidDataException(LinkPlayException):
pass
def __init__(self, message: str = "Invalid data received", data: str | None = None):
super().__init__(message)
self.data = data
2 changes: 1 addition & 1 deletion src/linkplay/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,7 @@ async def session_call_api_json(
except json.JSONDecodeError as jsonexc:
url = API_ENDPOINT.format(endpoint, command)
raise LinkPlayInvalidDataException(
f"Unexpected JSON ({result}) received from '{url}'"
message=f"Unexpected JSON ({result}) received from '{url}'", data=result
) from jsonexc


Expand Down
40 changes: 39 additions & 1 deletion tests/linkplay/test_bridge.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
"""Test bridge functionality."""

from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
from linkplay.bridge import (
Expand All@@ -22,6 +22,7 @@
PlayingStatus,
)
from linkplay.endpoint import LinkPlayApiEndpoint
from linkplay.manufacturers import MANUFACTURER_WIIM


def test_device_name():
Expand DownExpand Up@@ -561,3 +562,40 @@ async def test_update_status_does_not_trigger_controller_on_no_mode_change(mock_
await player.update_status()

mock_bridge.device.controller.assert_not_called()


async def test_meta_info_failed_handling():
"""Test that the player handles a failed META_INFO request correctly."""

async def mock_session_call_api_json_side_effect(endpoint, session, command):
if command == LinkPlayCommand.META_INFO:
return "Failed"
return "{}"

# Mock the session_call_api function
with patch(
"linkplay.utils.session_call_api",
new=AsyncMock(side_effect=mock_session_call_api_json_side_effect),
) as mock_api:
# Mock the bridge and its device
mock_bridge = LinkPlayBridge(
endpoint=LinkPlayApiEndpoint(
protocol="http", port=80, endpoint="1.2.3.4", session=None
)
)
mock_bridge.device = MagicMock()
mock_bridge.device.manufacturer = (
MANUFACTURER_WIIM # Set the manufacturer to WiiM
)

# Create a LinkPlayPlayer instance with the mocked bridge
player = LinkPlayPlayer(mock_bridge)

# Simulate the META_INFO request and exception handling
await player.update_status()

# Verify that metainfo is set to an empty dictionary after the exception
assert player.metainfo == {}

# Verify that the mocked function was called with the correct command
mock_api.assert_called_with("http://1.2.3.4", None, LinkPlayCommand.META_INFO)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Handle "failed" returned as plain text to the WiiM metainfo command by silamon · Pull Request #93 · Velleman/python-linkplay · GitHub
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
12 changes: 9 additions & 3 deletions src/linkplay/bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -153,9 +153,15 @@ async def update_status(self) -> None:

self.properties = fixup_player_properties(properties)
if self.bridge.device.manufacturer == MANUFACTURER_WIIM:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
try:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
except LinkPlayInvalidDataException as exc:
if getattr(exc, "data", None) == "Failed":
self.metainfo = {}
else:
raise
else:
self.metainfo = {}

Expand Down
20 changes: 11 additions & 9 deletions src/linkplay/consts.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -473,18 +473,18 @@ def __str__(self):

def __repr__(self):
return self.value


class MetaInfo(StrEnum):

class MetaInfo(StrEnum):
METADATA = "metaData"

def __str__(self):
return self.value

def __repr__(self):
return self.value

return self.value


class MetaInfoMetaData(StrEnum):
"""Defines the metadata within the metainfo."""

Expand All@@ -496,25 +496,27 @@ class MetaInfoMetaData(StrEnum):
BIT_DEPTH = "bitDepth"
BIT_RATE = "bitRate"
TRACK_ID = "trackId"

def __str__(self):
return self.value

def __repr__(self):
return self.value
return self.value


class AudioOutputHwMode(StrEnum):
"""Defines a output mode for the hardware."""

OPTICAL = "1"
LINE_OUT = "2"
COAXIAL = "3"
HEADPHONES = "4"


# Map between a play mode and how to activate the play mode
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { # case sensitive!
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line-out",
AudioOutputHwMode.COAXIAL: "co-axial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
}
4 changes: 3 additions & 1 deletion src/linkplay/exceptions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,4 +7,6 @@ class LinkPlayRequestException(LinkPlayException):


class LinkPlayInvalidDataException(LinkPlayException):
pass
def __init__(self, message: str = "Invalid data received", data: str | None = None):
super().__init__(message)
self.data = data
2 changes: 1 addition & 1 deletion src/linkplay/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,7 @@ async def session_call_api_json(
except json.JSONDecodeError as jsonexc:
url = API_ENDPOINT.format(endpoint, command)
raise LinkPlayInvalidDataException(
f"Unexpected JSON ({result}) received from '{url}'"
message=f"Unexpected JSON ({result}) received from '{url}'", data=result
) from jsonexc


Expand Down
40 changes: 39 additions & 1 deletion tests/linkplay/test_bridge.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
"""Test bridge functionality."""

from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
from linkplay.bridge import (
Expand All@@ -22,6 +22,7 @@
PlayingStatus,
)
from linkplay.endpoint import LinkPlayApiEndpoint
from linkplay.manufacturers import MANUFACTURER_WIIM


def test_device_name():
Expand DownExpand Up@@ -561,3 +562,40 @@ async def test_update_status_does_not_trigger_controller_on_no_mode_change(mock_
await player.update_status()

mock_bridge.device.controller.assert_not_called()


async def test_meta_info_failed_handling():
"""Test that the player handles a failed META_INFO request correctly."""

async def mock_session_call_api_json_side_effect(endpoint, session, command):
if command == LinkPlayCommand.META_INFO:
return "Failed"
return "{}"

# Mock the session_call_api function
with patch(
"linkplay.utils.session_call_api",
new=AsyncMock(side_effect=mock_session_call_api_json_side_effect),
) as mock_api:
# Mock the bridge and its device
mock_bridge = LinkPlayBridge(
endpoint=LinkPlayApiEndpoint(
protocol="http", port=80, endpoint="1.2.3.4", session=None
)
)
mock_bridge.device = MagicMock()
mock_bridge.device.manufacturer = (
MANUFACTURER_WIIM # Set the manufacturer to WiiM
)

# Create a LinkPlayPlayer instance with the mocked bridge
player = LinkPlayPlayer(mock_bridge)

# Simulate the META_INFO request and exception handling
await player.update_status()

# Verify that metainfo is set to an empty dictionary after the exception
assert player.metainfo == {}

# Verify that the mocked function was called with the correct command
mock_api.assert_called_with("http://1.2.3.4", None, LinkPlayCommand.META_INFO)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Handle "failed" returned as plain text to the WiiM metainfo command by silamon · Pull Request #93 · Velleman/python-linkplay · GitHub
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
12 changes: 9 additions & 3 deletions src/linkplay/bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -153,9 +153,15 @@ async def update_status(self) -> None:

self.properties = fixup_player_properties(properties)
if self.bridge.device.manufacturer == MANUFACTURER_WIIM:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
try:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
except LinkPlayInvalidDataException as exc:
if getattr(exc, "data", None) == "Failed":
self.metainfo = {}
else:
raise
else:
self.metainfo = {}

Expand Down
20 changes: 11 additions & 9 deletions src/linkplay/consts.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -473,18 +473,18 @@ def __str__(self):

def __repr__(self):
return self.value


class MetaInfo(StrEnum):

class MetaInfo(StrEnum):
METADATA = "metaData"

def __str__(self):
return self.value

def __repr__(self):
return self.value

return self.value


class MetaInfoMetaData(StrEnum):
"""Defines the metadata within the metainfo."""

Expand All@@ -496,25 +496,27 @@ class MetaInfoMetaData(StrEnum):
BIT_DEPTH = "bitDepth"
BIT_RATE = "bitRate"
TRACK_ID = "trackId"

def __str__(self):
return self.value

def __repr__(self):
return self.value
return self.value


class AudioOutputHwMode(StrEnum):
"""Defines a output mode for the hardware."""

OPTICAL = "1"
LINE_OUT = "2"
COAXIAL = "3"
HEADPHONES = "4"


# Map between a play mode and how to activate the play mode
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { # case sensitive!
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line-out",
AudioOutputHwMode.COAXIAL: "co-axial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
}
4 changes: 3 additions & 1 deletion src/linkplay/exceptions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,4 +7,6 @@ class LinkPlayRequestException(LinkPlayException):


class LinkPlayInvalidDataException(LinkPlayException):
pass
def __init__(self, message: str = "Invalid data received", data: str | None = None):
super().__init__(message)
self.data = data
2 changes: 1 addition & 1 deletion src/linkplay/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,7 @@ async def session_call_api_json(
except json.JSONDecodeError as jsonexc:
url = API_ENDPOINT.format(endpoint, command)
raise LinkPlayInvalidDataException(
f"Unexpected JSON ({result}) received from '{url}'"
message=f"Unexpected JSON ({result}) received from '{url}'", data=result
) from jsonexc


Expand Down
40 changes: 39 additions & 1 deletion tests/linkplay/test_bridge.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
"""Test bridge functionality."""

from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
from linkplay.bridge import (
Expand All@@ -22,6 +22,7 @@
PlayingStatus,
)
from linkplay.endpoint import LinkPlayApiEndpoint
from linkplay.manufacturers import MANUFACTURER_WIIM


def test_device_name():
Expand DownExpand Up@@ -561,3 +562,40 @@ async def test_update_status_does_not_trigger_controller_on_no_mode_change(mock_
await player.update_status()

mock_bridge.device.controller.assert_not_called()


async def test_meta_info_failed_handling():
"""Test that the player handles a failed META_INFO request correctly."""

async def mock_session_call_api_json_side_effect(endpoint, session, command):
if command == LinkPlayCommand.META_INFO:
return "Failed"
return "{}"

# Mock the session_call_api function
with patch(
"linkplay.utils.session_call_api",
new=AsyncMock(side_effect=mock_session_call_api_json_side_effect),
) as mock_api:
# Mock the bridge and its device
mock_bridge = LinkPlayBridge(
endpoint=LinkPlayApiEndpoint(
protocol="http", port=80, endpoint="1.2.3.4", session=None
)
)
mock_bridge.device = MagicMock()
mock_bridge.device.manufacturer = (
MANUFACTURER_WIIM # Set the manufacturer to WiiM
)

# Create a LinkPlayPlayer instance with the mocked bridge
player = LinkPlayPlayer(mock_bridge)

# Simulate the META_INFO request and exception handling
await player.update_status()

# Verify that metainfo is set to an empty dictionary after the exception
assert player.metainfo == {}

# Verify that the mocked function was called with the correct command
mock_api.assert_called_with("http://1.2.3.4", None, LinkPlayCommand.META_INFO)
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Handle "failed" returned as plain text to the WiiM metainfo command by silamon · Pull Request #93 · Velleman/python-linkplay · GitHub
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
12 changes: 9 additions & 3 deletions src/linkplay/bridge.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -153,9 +153,15 @@ async def update_status(self) -> None:

self.properties = fixup_player_properties(properties)
if self.bridge.device.manufacturer == MANUFACTURER_WIIM:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
try:
self.metainfo: dict[
MetaInfo, dict[MetaInfoMetaData, str]
] = await self.bridge.json_request(LinkPlayCommand.META_INFO) # type: ignore[assignment]
except LinkPlayInvalidDataException as exc:
if getattr(exc, "data", None) == "Failed":
self.metainfo = {}
else:
raise
else:
self.metainfo = {}

Expand Down
20 changes: 11 additions & 9 deletions src/linkplay/consts.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -473,18 +473,18 @@ def __str__(self):

def __repr__(self):
return self.value


class MetaInfo(StrEnum):

class MetaInfo(StrEnum):
METADATA = "metaData"

def __str__(self):
return self.value

def __repr__(self):
return self.value

return self.value


class MetaInfoMetaData(StrEnum):
"""Defines the metadata within the metainfo."""

Expand All@@ -496,25 +496,27 @@ class MetaInfoMetaData(StrEnum):
BIT_DEPTH = "bitDepth"
BIT_RATE = "bitRate"
TRACK_ID = "trackId"

def __str__(self):
return self.value

def __repr__(self):
return self.value
return self.value


class AudioOutputHwMode(StrEnum):
"""Defines a output mode for the hardware."""

OPTICAL = "1"
LINE_OUT = "2"
COAXIAL = "3"
HEADPHONES = "4"


# Map between a play mode and how to activate the play mode
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { # case sensitive!
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line-out",
AudioOutputHwMode.COAXIAL: "co-axial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
}
4 changes: 3 additions & 1 deletion src/linkplay/exceptions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,4 +7,6 @@ class LinkPlayRequestException(LinkPlayException):


class LinkPlayInvalidDataException(LinkPlayException):
pass
def __init__(self, message: str = "Invalid data received", data: str | None = None):
super().__init__(message)
self.data = data
2 changes: 1 addition & 1 deletion src/linkplay/utils.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -82,7 +82,7 @@ async def session_call_api_json(
except json.JSONDecodeError as jsonexc:
url = API_ENDPOINT.format(endpoint, command)
raise LinkPlayInvalidDataException(
f"Unexpected JSON ({result}) received from '{url}'"
message=f"Unexpected JSON ({result}) received from '{url}'", data=result
) from jsonexc


Expand Down
40 changes: 39 additions & 1 deletion tests/linkplay/test_bridge.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
"""Test bridge functionality."""

from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
from linkplay.bridge import (
Expand All@@ -22,6 +22,7 @@
PlayingStatus,
)
from linkplay.endpoint import LinkPlayApiEndpoint
from linkplay.manufacturers import MANUFACTURER_WIIM


def test_device_name():
Expand DownExpand Up@@ -561,3 +562,40 @@ async def test_update_status_does_not_trigger_controller_on_no_mode_change(mock_
await player.update_status()

mock_bridge.device.controller.assert_not_called()


async def test_meta_info_failed_handling():
"""Test that the player handles a failed META_INFO request correctly."""

async def mock_session_call_api_json_side_effect(endpoint, session, command):
if command == LinkPlayCommand.META_INFO:
return "Failed"
return "{}"

# Mock the session_call_api function
with patch(
"linkplay.utils.session_call_api",
new=AsyncMock(side_effect=mock_session_call_api_json_side_effect),
) as mock_api:
# Mock the bridge and its device
mock_bridge = LinkPlayBridge(
endpoint=LinkPlayApiEndpoint(
protocol="http", port=80, endpoint="1.2.3.4", session=None
)
)
mock_bridge.device = MagicMock()
mock_bridge.device.manufacturer = (
MANUFACTURER_WIIM # Set the manufacturer to WiiM
)

# Create a LinkPlayPlayer instance with the mocked bridge
player = LinkPlayPlayer(mock_bridge)

# Simulate the META_INFO request and exception handling
await player.update_status()

# Verify that metainfo is set to an empty dictionary after the exception
assert player.metainfo == {}

# Verify that the mocked function was called with the correct command
mock_api.assert_called_with("http://1.2.3.4", None, LinkPlayCommand.META_INFO)