Skip to content

Commit

Permalink
Merge pull request #28 from antoinebou12/master
Browse files Browse the repository at this point in the history
sync with master
  • Loading branch information
neilzilla authored Sep 30, 2024
2 parents b11f2db + f1ce746 commit 22b4710
Showing 1 changed file with 70 additions and 9 deletions.
79 changes: 70 additions & 9 deletions api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os

import asyncio
import datetime
from datetime import datetime, date
import logging
import time
from base64 import b64encode
Expand Down Expand Up @@ -379,9 +379,11 @@ def __init__(self, email, password, user_id=None, refresh=60, proxy=None):
self.is_polling_active = False
self.proxy = proxy

_LOGGER.info(f"Initializing RenphoWeight instance. Proxy is {'enabled: ' + proxy if proxy else 'disabled.'}")

@staticmethod
def get_timestamp() -> int:
start_date = datetime.date(1998, 1, 1)
start_date = date(1998, 1, 1)
return int(time.mktime(start_date.timetuple()))


Expand Down Expand Up @@ -412,18 +414,30 @@ async def open_session(self):

async def check_proxy(self):
"""
Checks if the proxy is working by making a request to httpbin.org.
Checks if the proxy is working by making a request to a Renpho API endpoint.
"""
test_url = 'https://renpho.qnclouds.com/api/v3/girths/list_girth.json?app_id=Renpho&terminal_user_session_key='
test_url = 'http://httpbin.org/get'

if not self.proxy:
_LOGGER.info("No proxy configured. Proceeding without proxy.")
else:
_LOGGER.info(f"Checking proxy connectivity using proxy: {self.proxy}")

try:
connector = ProxyConnector.from_url(self.proxy) if self.proxy else None
async with aiohttp.ClientSession(connector=connector) as session:
async with session.get(test_url) as response:
session = aiohttp.ClientSession(connector=connector)
async with session.get(test_url) as response:
if response.status == 200:
_LOGGER.info("Proxy check successful." if self.proxy else "Direct connection successful.")
return True
else:
_LOGGER.error(f"Failed to connect using {'proxy' if self.proxy else 'direct connection'}. HTTP Status: {response.status}")
return False
except Exception as e:
_LOGGER.error(f"Proxy connection failed: {e}")
return False

finally:
await session.close()

async def _request(self, method: str, url: str, retries: int = 3, skip_auth=False, **kwargs):
"""
Expand Down Expand Up @@ -498,11 +512,13 @@ async def validate_credentials(self):
Validate the current credentials by attempting to authenticate.
Returns True if authentication succeeds, False otherwise.
"""
_LOGGER.debug("Validating credentials for user: %s", self.email)
try:
return await self.auth()
except Exception as e:
_LOGGER.error(f"Validation failed: {e}")
return False
_LOGGER.error("Failed to validate credentials for user: %s. Error: %s", self.email, e)
raise AuthenticationError(f"Invalid credentials for user {self.email}. Error details: {e}") from e


async def auth(self):
"""Authenticate with the Renpho API."""
Expand Down Expand Up @@ -688,6 +704,40 @@ async def get_measurements_history(self):
_LOGGER.error(f"Failed to fetch weight measurements: {e}")
return None

async def get_all_users_measurements_history(self):
"""
Fetch the most recent weight measurements_history for the user.
"""
url = f"{API_MEASUREMENTS_URL}?last_at={self.get_timestamp()}&locale=en&app_id=Renpho&terminal_user_session_key={self.token}"
try:
parsed = await self._request("GET", url, skip_auth=True)

if not parsed:
_LOGGER.error("Failed to fetch weight measurements.")
return

if "status_code" in parsed and parsed["status_code"] == "20000":
if "last_ary" not in parsed:
_LOGGER.error("No weight measurements found in the response.")
return
if measurements := parsed["last_ary"]:
self.weight_history = [MeasurementDetail(**measurement) for measurement in measurements]
return self.weight_history
else:
_LOGGER.error("No weight measurements found in the response.")
return None
else:
# Handling different error scenarios
if "status_code" not in parsed:
_LOGGER.error("Invalid response format received from weight measurements endpoint.")
else:
_LOGGER.error(f"Error fetching weight measurements: Status Code {parsed.get('status_code')} - {parsed.get('status_message')}")
return None

except Exception as e:
_LOGGER.error(f"Failed to fetch weight measurements: {e}")
return None

async def get_weight(self):
if self.weight and self.weight_info:
return self.weight, self.weight_info
Expand Down Expand Up @@ -1192,6 +1242,17 @@ async def get_measurements_history(request: Request, renpho: RenphoWeight = Depe
_LOGGER.error(f"Error fetching measurements_history: {e}")
return APIResponse(status="error", message=str(e))

@app.get("/all_users_measurements_history", response_model=APIResponse)
async def get_measurements_history(request: Request, renpho: RenphoWeight = Depends(get_current_user)):
try:
measurements_history = await renpho.get_all_users_measurements_history()
if measurements_history:
return APIResponse(status="success", message="Fetched measurements_history.", data={"measurements_history": measurements_history})
raise HTTPException(status_code=404, detail="Measurements not found")
except Exception as e:
_LOGGER.error(f"Error fetching measurements_history: {e}")
return APIResponse(status="error", message=str(e))

@app.get("/weight", response_model=APIResponse)
async def get_weight(request: Request, renpho: RenphoWeight = Depends(get_current_user)):
try:
Expand Down

0 comments on commit 22b4710

Please sign in to comment.