cache.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. import commentjson
  12. def storePersonInCache(baseDir: str,personUrl: str,personJson: {},personCache: {}) -> None:
  13. """Store an actor in the cache
  14. """
  15. currTime=datetime.datetime.utcnow()
  16. personCache[personUrl]={
  17. "actor": personJson,
  18. "timestamp": currTime.strftime("%Y-%m-%dT%H:%M:%SZ")
  19. }
  20. if not baseDir:
  21. return
  22. # store to file
  23. if os.path.isdir(baseDir+'/cache/actors'):
  24. cacheFilename=baseDir+'/cache/actors/'+personUrl.replace('/','#')+'.json'
  25. if not os.path.isfile(cacheFilename):
  26. with open(cacheFilename, 'w') as fp:
  27. commentjson.dump(personJson, fp, indent=4, sort_keys=False)
  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=None
  37. try:
  38. with open(cacheFilename, 'r') as fp:
  39. personJson=commentjson.load(fp)
  40. except Exception as e:
  41. print('ERROR: unable to load actor from cache '+cacheFilename)
  42. print(e)
  43. if personJson:
  44. storePersonInCache(baseDir,personUrl,personJson,personCache)
  45. loadedFromFile=True
  46. if personCache.get(personUrl):
  47. if not loadedFromFile:
  48. # update the timestamp for the last time the actor was retrieved
  49. currTime=datetime.datetime.utcnow()
  50. personCache[personUrl]['timestamp']=currTime.strftime("%Y-%m-%dT%H:%M:%SZ")
  51. return personCache[personUrl]['actor']
  52. return None
  53. def expirePersonCache(personCache: {}):
  54. """Expires old entries from the cache in memory
  55. """
  56. currTime=datetime.datetime.utcnow()
  57. removals=[]
  58. for personUrl,cacheJson in personCache.items():
  59. cacheTime= \
  60. datetime.datetime.strptime(cacheJson['timestamp'], \
  61. "%Y-%m-%dT%H:%M:%SZ")
  62. daysSinceCached=(currTime - cacheTime).days
  63. if daysSinceCached > 2:
  64. removals.append(personUrl)
  65. if len(removals)>0:
  66. for personUrl in removals:
  67. del personCache[personUrl]
  68. print(str(len(removals))+' actors were expired from the cache')
  69. def storeWebfingerInCache(handle: str,wf,cachedWebfingers: {}) -> None:
  70. """Store a webfinger endpoint in the cache
  71. """
  72. cachedWebfingers[handle]=wf
  73. def getWebfingerFromCache(handle: str,cachedWebfingers: {}) -> {}:
  74. """Get webfinger endpoint from the cache
  75. """
  76. if cachedWebfingers.get(handle):
  77. return cachedWebfingers[handle]
  78. return None