cache.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. __filename__ = "cache.py"
  2. __author__ = "Bob Mottram"
  3. __license__ = "AGPL3+"
  4. __version__ = "1.0.0"
  5. __maintainer__ = "Bob Mottram"
  6. __email__ = "bob@freedombone.net"
  7. __status__ = "Production"
  8. import os
  9. import time
  10. import datetime
  11. from utils import loadJson
  12. from utils import saveJson
  13. def storePersonInCache(baseDir: str,personUrl: str,personJson: {},personCache: {}) -> None:
  14. """Store an actor in the cache
  15. """
  16. currTime=datetime.datetime.utcnow()
  17. personCache[personUrl]={
  18. "actor": personJson,
  19. "timestamp": currTime.strftime("%Y-%m-%dT%H:%M:%SZ")
  20. }
  21. if not baseDir:
  22. return
  23. # store to file
  24. if os.path.isdir(baseDir+'/cache/actors'):
  25. cacheFilename=baseDir+'/cache/actors/'+personUrl.replace('/','#')+'.json'
  26. if not os.path.isfile(cacheFilename):
  27. saveJson(personJson,cacheFilename)
  28. def getPersonFromCache(baseDir: str,personUrl: str,personCache: {}) -> {}:
  29. """Get an actor from the cache
  30. """
  31. # if the actor is not in memory then try to load it from file
  32. loadedFromFile=False
  33. if not personCache.get(personUrl):
  34. cacheFilename=baseDir+'/cache/actors/'+personUrl.replace('/','#')+'.json'
  35. if os.path.isfile(cacheFilename):
  36. personJson=loadJson(cacheFilename)
  37. if personJson:
  38. storePersonInCache(baseDir,personUrl,personJson,personCache)
  39. loadedFromFile=True
  40. if personCache.get(personUrl):
  41. if not loadedFromFile:
  42. # update the timestamp for the last time the actor was retrieved
  43. currTime=datetime.datetime.utcnow()
  44. personCache[personUrl]['timestamp']=currTime.strftime("%Y-%m-%dT%H:%M:%SZ")
  45. return personCache[personUrl]['actor']
  46. return None
  47. def expirePersonCache(personCache: {}):
  48. """Expires old entries from the cache in memory
  49. """
  50. currTime=datetime.datetime.utcnow()
  51. removals=[]
  52. for personUrl,cacheJson in personCache.items():
  53. cacheTime= \
  54. datetime.datetime.strptime(cacheJson['timestamp'], \
  55. "%Y-%m-%dT%H:%M:%SZ")
  56. daysSinceCached=(currTime - cacheTime).days
  57. if daysSinceCached > 2:
  58. removals.append(personUrl)
  59. if len(removals)>0:
  60. for personUrl in removals:
  61. del personCache[personUrl]
  62. print(str(len(removals))+' actors were expired from the cache')
  63. def storeWebfingerInCache(handle: str,wf,cachedWebfingers: {}) -> None:
  64. """Store a webfinger endpoint in the cache
  65. """
  66. cachedWebfingers[handle]=wf
  67. def getWebfingerFromCache(handle: str,cachedWebfingers: {}) -> {}:
  68. """Get webfinger endpoint from the cache
  69. """
  70. if cachedWebfingers.get(handle):
  71. return cachedWebfingers[handle]
  72. return None