Skip to content
Open
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
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ nintendo = await NintendoParental.create(auth, timezone="Europe/London", lang="e

After creation, the `NintendoParental` object will have a `devices` property, which is a dictionary of `Device` objects, keyed by their device ID.

Call `await nintendo.update()` to refresh every device. Pass `monthly_summary=False` to skip the monthly summaries, for example on frequent polls; devices without one still fetch it.

### The `Device` object

The `Device` object contains information about a specific Nintendo Switch console and allows you to control it.
Expand All @@ -154,7 +156,7 @@ The `Device` object contains information about a specific Nintendo Switch consol

All methods are asynchronous.

- `update()`: Refreshes the device data from the Nintendo API.
- `update(monthly_summary: bool = True)`: Refreshes the device data from the Nintendo API. Pass `monthly_summary=False` to skip the monthly summary and keep the last one.
- `add_device_callback(callback)`: Adds a callback that will be called when the device state changes.
- `remove_device_callback(callback)`: Removes a previously added callback.
- `set_new_pin(pin: str)`: Sets a new PIN for the parental controls.
Expand Down
12 changes: 8 additions & 4 deletions pynintendoparental/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ def __init__(self, auth: Authenticator, timezone, lang) -> None:
self.account_id = auth.account_id
self.devices: dict[str, Device] = {}

async def _get_devices(self):
async def _get_devices(self, monthly_summary: bool = True):
"""Gets devices from the API and stores in self.devices"""

async def update_device(dev: Device):
"""Update a device."""
try:
await dev.update()
await dev.update(monthly_summary=monthly_summary or not dev.last_month_summary)
except Exception as err:
_LOGGER.exception("Error updating device %s: %s", dev.device_id, err)

Expand All @@ -55,15 +55,19 @@ async def update_device(dev: Device):
await asyncio.gather(*coros)
_LOGGER.debug("Found %s device(s)", len(self.devices))

async def update(self):
async def update(self, *, monthly_summary: bool = True):
"""Update module data.

Refreshes all devices and their associated data from Nintendo's servers.
This method fetches the latest information about all devices linked to
the authenticated account.

Args:
monthly_summary: Also fetch the monthly summaries. Devices without one
always fetch it.
"""
_LOGGER.debug("Received request to update data.")
await self._get_devices()
await self._get_devices(monthly_summary=monthly_summary)
_LOGGER.debug("Update complete.")

@classmethod
Expand Down
13 changes: 7 additions & 6 deletions pynintendoparental/device/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def last_sync(self) -> float | None:
"""
return self.extra.get("synchronizedParentalControlSetting", {}).get("synchronizedAt", None)

async def update(self, now: datetime | None = None):
async def update(self, now: datetime | None = None, *, monthly_summary: bool = True):
"""Update device data from Nintendo servers.

Fetches the latest information including daily summaries, parental control
Expand All @@ -125,15 +125,16 @@ async def update(self, now: datetime | None = None):
Args:
now: Optional datetime for the update. Defaults to the current time in the
API timezone if not provided.
monthly_summary: Also fetch the monthly summary. If False, the last
one is kept.
"""
_LOGGER.debug(">> Device.update()")
if now is None:
now = current_datetime(self._api._tz)
await asyncio.gather(
self._get_daily_summaries(now),
self.get_monthly_summary(),
self._get_extras(),
)
requests = [self._get_daily_summaries(now), self._get_extras()]
if monthly_summary:
requests.append(self.get_monthly_summary())
await asyncio.gather(*requests)
# Fetch PCS after daily summaries so extra_playing_time is not parsed from a
# stale concurrent response (see #118 / debug-430f96).
await self._get_parental_control_setting(now)
Expand Down
23 changes: 23 additions & 0 deletions tests/test_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,29 @@ async def test_get_monthly_summary_error(
assert expected_log.format(DEVICE_ID=device.device_id) in caplog.text


async def test_update_skip_monthly_summary(device: Device, mock_api: Api):
"""Test that update(monthly_summary=False) skips the monthly summary requests."""
summary_before = device.last_month_summary
players_before = {player.player_id for player in device.players}
list_calls = mock_api.async_get_device_monthly_summaries.call_count
summary_calls = mock_api.async_get_device_monthly_summary.call_count

await device.update(monthly_summary=False)

assert mock_api.async_get_device_monthly_summaries.call_count == list_calls
assert mock_api.async_get_device_monthly_summary.call_count == summary_calls
assert device.last_month_summary == summary_before
assert {player.player_id for player in device.players} == players_before
assert mock_api.async_get_device_daily_summaries.call_count == 2


async def test_update_monthly_summary_default(device: Device, mock_api: Api):
"""Test that update() still fetches the monthly summary by default."""
await device.update()

assert mock_api.async_get_device_monthly_summary.call_count == 2


@pytest.mark.parametrize(
"side_effect,timer_state,kwargs",
[
Expand Down
20 changes: 20 additions & 0 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,23 @@ async def test_device_update_exception(mock_authenticator: Authenticator, mock_a
parental = await NintendoParental.create(mock_authenticator)
assert len(parental.devices) == 1
assert device_id in parental.devices


async def test_update_monthly_summary(mock_authenticator: Authenticator, mock_api_init: AsyncMock):
"""Test that update(monthly_summary=False) is passed on, except for devices without a summary."""
devices_fixture = await load_fixture("account_devices")
mock_api_instance = mock_api_init.return_value
mock_api_instance.async_get_account_devices.return_value = {"json": devices_fixture}

with patch("pynintendoparental.Device.update", autospec=True) as mock_update:
parental = await NintendoParental.create(mock_authenticator)
device = next(iter(parental.devices.values()))
assert mock_update.call_args.kwargs == {"monthly_summary": True}

device.last_month_summary = {"players": []}
await parental.update(monthly_summary=False)
assert mock_update.call_args.kwargs == {"monthly_summary": False}

device.last_month_summary = {}
await parental.update(monthly_summary=False)
assert mock_update.call_args.kwargs == {"monthly_summary": True}