epicyon/cache.py

60 lines
1.9 KiB
Python
Raw Normal View History

2019-06-30 15:03:26 +00:00
__filename__ = "cache.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "0.0.1"
__maintainer__ = "Bob Mottram"
__email__ = "bob@freedombone.net"
__status__ = "Production"
2019-08-20 09:16:03 +00:00
import os
2019-06-30 15:18:40 +00:00
import datetime
2019-08-20 09:16:03 +00:00
import commentjson
2019-06-30 15:18:40 +00:00
2019-08-20 09:16:03 +00:00
def storePersonInCache(baseDir: str,personUrl: str,personJson: {},personCache: {}) -> None:
2019-06-30 15:03:26 +00:00
"""Store an actor in the cache
"""
2019-06-30 15:18:40 +00:00
currTime=datetime.datetime.utcnow()
2019-07-06 17:00:22 +00:00
personCache[personUrl]={
"actor": personJson,
"timestamp": currTime.strftime("%Y-%m-%dT%H:%M:%SZ")
}
2019-08-20 09:16:03 +00:00
if not baseDir:
return
# store to file
if not os.path.isdir(baseDir+'/cache'):
os.mkdir(baseDir+'/cache')
if not os.path.isdir(baseDir+'/cache/actors'):
os.mkdir(baseDir+'/cache/actors')
cacheFilename=baseDir+'/cache/actors/'+personUrl.replace('/','#')+'.json'
if not os.path.isfile(cacheFilename):
with open(cacheFilename, 'w') as fp:
commentjson.dump(personJson, fp, indent=4, sort_keys=False)
2019-06-30 15:03:26 +00:00
2019-07-01 14:30:48 +00:00
def storeWebfingerInCache(handle: str,wf,cachedWebfingers: {}) -> None:
2019-06-30 15:03:26 +00:00
"""Store a webfinger endpoint in the cache
"""
cachedWebfingers[handle]=wf
2019-07-01 14:30:48 +00:00
def getPersonFromCache(personUrl: str,personCache: {}) -> {}:
2019-06-30 15:03:26 +00:00
"""Get an actor from the cache
"""
if personCache.get(personUrl):
2019-06-30 15:20:10 +00:00
# how old is the cached data?
2019-06-30 15:18:40 +00:00
currTime=datetime.datetime.utcnow()
2019-07-06 17:00:22 +00:00
cacheTime= \
datetime.datetime.strptime(personCache[personUrl]['timestamp'], \
"%Y-%m-%dT%H:%M:%SZ")
2019-06-30 15:18:40 +00:00
daysSinceCached=(currTime - cacheTime).days
2019-06-30 15:20:10 +00:00
# return cached value if it has not expired
2019-06-30 15:18:40 +00:00
if daysSinceCached <= 2:
return personCache[personUrl]['actor']
2019-06-30 15:03:26 +00:00
return None
2019-07-01 14:30:48 +00:00
def getWebfingerFromCache(handle: str,cachedWebfingers: {}) -> {}:
2019-06-30 15:03:26 +00:00
"""Get webfinger endpoint from the cache
"""
if cachedWebfingers.get(handle):
return cachedWebfingers[handle]
return None