respondd.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python3
  2. import json
  3. import zlib
  4. import time
  5. import lib.helper
  6. class Respondd:
  7. def __init__(self, config):
  8. self._config = config
  9. self._aliasOverlay = {}
  10. self.__cache = {}
  11. self.__cacheTime = 0
  12. try:
  13. with open('alias.json', 'r') as fh: # TODO: prevent loading more then once !
  14. self._aliasOverlay = json.load(fh)
  15. except IOError:
  16. print('can\'t load alias.json!')
  17. pass
  18. def getNodeID(self):
  19. if 'nodeinfo' in self._aliasOverlay and 'node_id' in self._aliasOverlay['nodeinfo']:
  20. return self._aliasOverlay['nodeinfo']['node_id']
  21. else:
  22. return lib.helper.getInterfaceMAC(self._config['batman']).replace(':', '')
  23. def getStruct(self, rootName=None):
  24. if 'caching' in self._config and time.time() - self.__cacheTime <= self._config['caching']:
  25. ret = self.__cache
  26. else:
  27. ret = self._get()
  28. self.__cache = ret
  29. self.__cacheTime = time.time()
  30. ret['node_id'] = self.getNodeID()
  31. if rootName is not None:
  32. ret_tmp = ret
  33. ret = {}
  34. ret[rootName] = ret_tmp
  35. return ret
  36. def getJSON(self, rootName=None):
  37. return bytes(json.dumps(self.getStruct(rootName), separators=(',', ':')), 'UTF-8')
  38. def getJSONCompressed(self, rootName=None):
  39. return self.compress(self.getJSON(rootName))
  40. @staticmethod
  41. def compress(data):
  42. encoder = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) # The data may be decompressed using zlib and many zlib bindings using -15 as the window size parameter.
  43. dataGzip = encoder.compress(data)
  44. dataGzip += encoder.flush()
  45. return dataGzip
  46. @staticmethod
  47. def _get():
  48. return {}