Files
Newsfeed/utility.py
2026-01-29 23:02:55 -05:00

315 lines
9.7 KiB
Python
Executable File

import time
import webbrowser
import requests
from datetime import timedelta
from datetime import datetime
from datetime import timezone
from environment import *
class myLog():
def __init__(self):
self._file = open(PATH_LOG_FILE,"a",encoding='utf-8')
def write(self,item):
currentDateTime = DateTimeHelper.getCurrentDateTime()
strCurrentDateTime = DateTimeHelper.getDateTimeAsString(currentDateTime)
strOutput = '[' + strCurrentDateTime +'] '+item
self._file.write(strOutput)
self._file.write("\n")
self._file.flush()
class Utility:
def __init__(self):
pass
@staticmethod
def pad(strItem, strPad, length):
while len(strItem)<length:
strItem=strPad + strItem
return strItem
class StringHelper:
def __init__(self):
pass
@staticmethod
def betweenString(strItem, strBegin, strEnd):
if strItem is None:
return None
index=-1
if strBegin is None:
index=0
else:
index = strItem.index(strBegin)
if -1==index:
return None
str=None
if strBegin is not None:
str=strItem[index+len(strBegin):]
else:
str=strItem
if strEnd is None:
return str
index=str.index(strEnd)
if -1==index :
return None
sb=""
for strIndex in range(0, len(str)-1):
if index==strIndex:
break
sb=sb+str[strIndex]
return (sb)
class HttpNetRequest:
def __init__(self):
self.Message=""
def getHttpNetRequest(self,url):
retrycount=0
maxretries=5
while retrycount<maxretries:
try:
response=requests.get(url, timeout=10)
return response
except:
retrycount=retrycount+1
if retrycount > maxretries:
raise
class DateTimeHelper:
def __init__(self):
pass
def __init__(self,capturedatetime,timeChange):
self.datetimestamp=capturedatetime
self.timeChange=timeChange
self.offsetTime=DateTimeHelper.applyRelativeTime(self.datetimestamp, self.timeChange)
def getDateTimeStamp(self):
return self.datetimestamp
def getTimeChange(self):
return self.timeChange
def getOffsetTime(self):
return self.offsetTime
def getOffsetTimeAsString(self):
return DateTimeHelper.getDateTimeAsString(self.offsetTime)
def toString(self):
pass
@staticmethod
def getDateTimeAsString(someDateTime):
if(not isinstance(someDateTime,datetime)):
raise Exception('Invalid type for parameter')
return someDateTime.strftime("%m-%d-%Y %H:%M:%S")
@staticmethod
def getDateTimeFromString(someDateTimeString):
if(not isinstance(someDateTimeString,str)):
raise Exception('Invalid type for parameter')
return DateTimeHelper.strptime(someDateTimeString,"%m-%d-%Y %H:%M:%S")
@staticmethod
def getCurrentDateTime():
return datetime.now()
# January 1, 2026
@staticmethod
def strptime(date_string):
month_map = {
'January': 1, 'February': 2, 'March': 3, 'April': 4,
'May': 5, 'June': 6, 'July': 7, 'August': 8,
'September': 9, 'October': 10, 'November': 11, 'December': 12
}
date_string = date_string.replace(',', '')
parts = date_string.split()
if len(parts) == 3:
month_str, day_str, year_str = parts
month = month_map.get(month_str)
day = int(day_str)
year = int(year_str)
if month is not None:
return datetime(year, month, day)
else:
raise ValueError("Invalid month name in date string")
else:
raise ValueError("Date string format is incorrect")
# January 1, 2026
@staticmethod
def canstrptime(date_string):
month_map = {
'January': 1, 'February': 2, 'March': 3, 'April': 4,
'May': 5, 'June': 6, 'July': 7, 'August': 8,
'September': 9, 'October': 10, 'November': 11, 'December': 12
}
date_string = date_string.replace(',', '')
parts = date_string.split()
if len(parts) != 3:
return False
month_str, day_str, year_str = parts
month = month_map.get(month_str)
if month is None:
return False
day = int(day_str)
year = int(year_str)
return True
# returns a datetime
@staticmethod
def applyRelativeTime(sometime,relativetime):
relativeTimeResult = sometime
if(not isinstance(sometime,datetime)):
raise Exception('Invalid type for parameter')
if(not isinstance(relativetime,str)):
raise Exception('Invalid type for parameter')
if DateTimeHelper.canstrptime(relativetime):
relativeTimeResult = DateTimeHelper.strptime(relativetime)
return relativeTimeResult
if relativetime=='just now':
return relativeTimeResult
if relativetime=='just in':
return relativeTimeResult
relativetimesplit=relativetime.split()
if len(relativetimesplit)==2:
year=datetime.now().year
relativetimex=relativetime+', '+str(year)
relativeDate = DateTimeHelper.strptime(relativetimex)
if(relativeDate>datetime.now()):
year=datetime.now().year-1
relativetimex=relativetime+', '+str(year)
relativeDate=DateTimeHelper.strptime(relativetimex)
days=sometime-relativeDate
relativeTimeResult=sometime-days
elif relativetimesplit[1]=='hour' or relativetimesplit[1]=='hours':
hours=int(relativetimesplit[0])
relativeTimeResult=sometime-timedelta(hours=hours)
elif relativetimesplit[1]=='day' or relativetimesplit[1]=='days':
days=int(relativetimesplit[0])
relativeTimeResult=sometime-timedelta(days=days)
elif relativetimesplit[1]=='minute' or relativetimesplit[1]=='minutes':
minutes=int(relativetimesplit[0])
relativeTimeResult=sometime-timedelta(minutes=minutes)
elif len(relativetimesplit)==3: # '16 mins ago' '2 hours ago'
if relativetimesplit[1]=='mins':
minutes=int(relativetimesplit[0])
relativeTimeResult=sometime-timedelta(minutes=minutes)
elif relativetimesplit[1]=='hours':
hours=int(relativetimesplit[0])
relativeTimeResult=sometime-timedelta(hours=hours)
elif relativetimesplit[1]=='day' or relativetimesplit[1]=='days':
days=int(relativetimesplit[0])
relativeTimeResult=sometime-timedelta(days=days)
return relativeTimeResult
class DateTime:
def __init__(self):
self.date=DateTime.getCurrentTime()
def __init__(self,strDate=None):
if None!=strDate:
self.date=DateTime.dateFromString(strDate)
else:
self.date=DateTime.getCurrentTime()
def toString(self):
return DateTime.dateToString(self.date)
def toStringMonthDay(self):
return self.getMonthAsString() + ' ' + Utility.pad(str(self.date.day),'0',2) + ', '+ str(self.date.year)
def getMonthAsString(self):
strMonth=None
if(self.date.month==1):
strMonth='January'
elif(self.date.month==2):
strMonth='February'
elif(self.date.month==3):
strMonth='March'
elif(self.date.month==4):
strMonth='April'
elif(self.date.month==5):
strMonth='May'
elif(self.date.month==6):
strMonth='June'
elif(self.date.month==7):
strMonth='July'
elif(self.date.month==8):
strMonth='August'
elif(self.date.month==9):
strMonth='September'
elif(self.date.month==10):
strMonth='October'
elif(self.date.month==11):
strMonth='November'
elif(self.date.month==12):
strMonth='December'
else:
strMonth='???'
return strMonth
def deltaTime(self,someDate):
return DateTime.deltaTime(self.date,someDate)
def getDate(self):
return self.date
@staticmethod
def fromdatetime(somedatetime):
if(not isinstance(somedatetime,datetime)):
raise Exception('Invalid type for parameter')
theDate=DateTime()
theDate.date=somedatetime
return theDate
@staticmethod
def dateToString(someDate):
return str(someDate)
@staticmethod
def dateFromString(strDate):
return datetime.fromisoformat(strDate)
@staticmethod
def now():
return DateTime.getCurrentTime()
@staticmethod
def getCurrentTime():
return datetime.now(timezone.utc)
@staticmethod
def sortList(dateList):
dateList.sort(key=lambda x:x.toString())
@staticmethod
def deltaTime(startTime,endTime):
if startTime > endTime:
timedelta=startTime-endTime
else:
timedelta=endTime-startTime
days, seconds=timedelta.days, timedelta.seconds
hours=timedelta.total_seconds()//3600
minutes=(seconds %3600)//60
seconds=seconds%60
return days, hours, minutes, seconds
#currentDate=DateTimeHelper.getCurrentDateTime()
#strDateTime=DateTimeHelper.getDateTimeAsString(currentDate)
#print(strDateTime)
#relativeTime=DateTimeHelper.applyRelativeTime(currentDate,'October 9')
#strDateTime=DateTimeHelper.getDateTimeAsString(relativeTime)
#print(relativeTime)
#if(relativeTime>currentDate):
# print('It is greater')