Skip to content

Commit

Permalink
fix: Remove unwanted update on uuid expiration
Browse files Browse the repository at this point in the history
  • Loading branch information
storm1er committed Oct 12, 2024
1 parent 97a07f3 commit e9ff749
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 11 deletions.
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,18 @@ The `track_package` service creates a sensor for each tracked package with the f

| Attribute | Description |
| --------------- | ------------------------------------------------------------------ |
| status | Current state (archived, delivered, transit, arrived, pickup) |
| uuid | UUID used by the ParcelsApp API |
| message | Latest update message from the delivery company |
| origin | Country of departure |
| carrier | Delivery company name |
| days_in_transit | Number of days between transit and delivery |
| last_updated | Timestamp of the latest check by the integration |
| status | Current state (archived, delivered, transit, arrived, pickup) |
| uuid | UUID used by the ParcelsApp API |
| uuid_timestamp | Timestamp when the UUID was obtained |
| message | Latest update message from the delivery company |
| location | Latest known location of the parcel |
| origin | Country of departure |
| destination | Destination country or address |
| carrier | Delivery company name |
| days_in_transit | Number of days the parcel has been in transit |
| last_updated | Timestamp of the latest check by the integration |
| name | Name given to the parcel (from the name parameter) |
| tracking_id | The tracking ID of the parcel |

## Installation

Expand Down
55 changes: 52 additions & 3 deletions custom_components/parcelsapp/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ async def remove_package(self, tracking_id: str) -> None:

async def update_package(self, tracking_id: str, uuid: str | None, uuid_timestamp: datetime | None) -> None:
"""Update a single package."""
# Ensure uuid_timestamp is a datetime object
if isinstance(uuid_timestamp, str):
uuid_timestamp = datetime.fromisoformat(uuid_timestamp)

# Check if UUID is expired
uuid_expired = False
if uuid_timestamp:
Expand All @@ -157,9 +161,19 @@ async def update_package(self, tracking_id: str, uuid: str | None, uuid_timestam
uuid_expired = True # No UUID timestamp means we need a new UUID

if uuid_expired or not uuid:
# Re-initiate tracking to get a new UUID
await self.track_package(tracking_id)
return
# Get a new UUID without overwriting existing data
new_uuid, new_uuid_timestamp = await self.get_new_uuid(tracking_id)
if new_uuid:
package_data = self.tracked_packages.get(tracking_id, {})
package_data['uuid'] = new_uuid
package_data['uuid_timestamp'] = new_uuid_timestamp
self.tracked_packages[tracking_id] = package_data
await self._save_tracked_packages()
else:
_LOGGER.error(f"Failed to get new UUID for {tracking_id}")
# Proceed with the update using the new UUID
uuid = new_uuid
uuid_timestamp = new_uuid_timestamp

url = f"https://parcelsapp.com/api/v3/shipments/tracking?uuid={uuid}&apiKey={self.api_key}&language={self.language}"

Expand Down Expand Up @@ -241,3 +255,38 @@ async def _fetch_parcels_app_status(self):
}
except aiohttp.ClientError as err:
raise UpdateFailed(f"Error communicating with API: {err}")

async def get_new_uuid(self, tracking_id: str) -> (str, datetime):
"""Get a new UUID for a tracking ID."""
url = "https://parcelsapp.com/api/v3/shipments/tracking"
payload = json.dumps(
{
"shipments": [
{
"trackingId": tracking_id,
"destinationCountry": self.destination_country,
}
],
"language": self.language,
"apiKey": self.api_key,
}
)
headers = {"Content-Type": "application/json"}

try:
async with self.session.post(
url, headers=headers, data=payload
) as response:
response_text = await response.text()
response.raise_for_status()
data = json.loads(response_text)
if "uuid" in data:
return data["uuid"], datetime.now()
else:
_LOGGER.error(
f"Unexpected API response when getting new UUID for tracking ID {tracking_id}. Response: {response_text}"
)
return None, None
except aiohttp.ClientError as err:
_LOGGER.error(f"Error getting new UUID for {tracking_id}: {err}")
return None, None
2 changes: 1 addition & 1 deletion custom_components/parcelsapp/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@
"dependencies": [],
"codeowners": [],
"iot_class": "cloud_polling",
"version": "0.1.0"
"version": "0.1.1"
}

0 comments on commit e9ff749

Please sign in to comment.