Skip to content

Commit

Permalink
fix: Show correct time until next match (#147)
Browse files Browse the repository at this point in the history
* Update for timezones, showing incorrect time.
Pretty sure this was the fault of it showing incorrect diff.

* fix incorrect time

* fix for edge case

fixes a rare edge case where some matches hadn't started when planned due to delay or cancellation

* moved time calculation to separate function

* timezone-correct starttime

* remove unused method

* Formatting

---------

Co-authored-by: Nicklas Sørensen <nicklas.henri@gmail.com>
Co-authored-by: League of Poro <95635582+LeagueOfPoro@users.noreply.github.com>
  • Loading branch information
3 people authored Feb 22, 2023
1 parent 5a3f700 commit 2428f27
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 17 deletions.
74 changes: 59 additions & 15 deletions src/DataProviderThread.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, timezone, timedelta
from threading import Thread
from time import sleep
import cloudscraper
Expand Down Expand Up @@ -28,6 +28,8 @@ def __init__(self, log, config, sharedData: SharedData):
'desktop': True
},
debug=False)
self.currentTime = None
self.startTime = None

def run(self):
while True:
Expand Down Expand Up @@ -83,20 +85,62 @@ def fetchTimeUntilNextMatch(self):
res.close()
events = resJson["data"]["schedule"]["events"]
for event in events:
try:
if "inProgress" != event["state"]:
startTime = datetime.strptime(event["startTime"], '%Y-%m-%dT%H:%M:%SZ') #Some matches aparrently don't have a starttime
except:
continue
if datetime.now() < startTime:
timeUntil = startTime - datetime.now()
total_seconds = int(timeUntil.total_seconds() + 3600)
days, remainder = divmod(total_seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
self.sharedData.setTimeUntilNextMatch(f"None - next in {str(days)}d" if days else f'None - next in {hours}h {minutes}m')
if event["state"] == "unstarted":
if self._isStartTimeLater(event["startTime"]): # startTime is later
timeDiff = self._calculateTimeDifference(event["startTime"])
systemTimeDT = self._getSystemTime()

# This line calculates a timezone-correct startime no matter which timezone you're in
startTime = systemTimeDT + timeDiff

niceStartTime = datetime.strftime(startTime, '%H:%M')
self.sharedData.setTimeUntilNextMatch(
f"Up next: {event['league']['name']} at {niceStartTime}")
break
else: # We're past the startTime due to delay or cancellation i'm guessing
continue # Continue for loop to find next 'unstarted' event
except StatusCodeAssertException as ex:
self.log.error(ex)
self.sharedData.setTimeUntilNextMatch("None")
except:
self.sharedData.setTimeUntilNextMatch("None")
except Exception as ex:
self.log.error(ex)
self.sharedData.setTimeUntilNextMatch("None")

def _isStartTimeLater(self, time: str) -> bool:
"""
Checks if an events starttime is greater than the current time
:param time: string
:return: bool
"""
datetimeFormat = '%Y-%m-%dT%H:%M:%SZ'
self.startTime = datetime.strptime(time, datetimeFormat)
currentTimeString = datetime.now(timezone.utc).strftime(datetimeFormat)
self.currentTime = datetime.strptime(currentTimeString, datetimeFormat)
return self.currentTime < self.startTime

def _calculateTimeDifference(self, time: str) -> timedelta:
"""
Calculates the time difference between the current time and a starttime
:param time: string
:return: timedelta, timedelta object containing time difference
"""
datetimeFormat = '%Y-%m-%dT%H:%M:%SZ'
self.startTime = datetime.strptime(time, datetimeFormat)
currentTimeString = datetime.now(timezone.utc).strftime(datetimeFormat)
self.currentTime = datetime.strptime(currentTimeString, datetimeFormat)

timeDifference = self.startTime - self.currentTime
return timeDifference

def _getSystemTime(self) -> datetime:
"""
Gets the systems current time
:return: datetime, systems current time as datetime
"""
datetimeFormat = '%Y-%m-%dT%H:%M:%SZ'
systemTimeStr = datetime.now().strftime(datetimeFormat)
systemTimeDT = datetime.strptime(systemTimeStr, datetimeFormat)
return systemTimeDT
4 changes: 2 additions & 2 deletions src/SharedData.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ class SharedData:
def __init__(self) -> None:
self.liveMatches = {}
self.timeUntilNextMatch = "None"

def setLiveMatches(self, liveMatches):
self.liveMatches = liveMatches

Expand All @@ -13,4 +13,4 @@ def setTimeUntilNextMatch(self, timeUntilNextMatch):
self.timeUntilNextMatch = timeUntilNextMatch

def getTimeUntilNextMatch(self):
return self.timeUntilNextMatch
return self.timeUntilNextMatch

0 comments on commit 2428f27

Please sign in to comment.