cache.py 2.8 KB

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