Freebox thin client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
3.8KB

  1. """
  2. Console script
  3. """
  4. import os
  5. import time
  6. import logging
  7. import json
  8. import argparse
  9. import pprint
  10. import requests
  11. from pyfbx import Fbx
  12. from pyfbx.client import (ResponseError, RequestError)
  13. log_level = (logging.WARNING, logging.INFO, logging.DEBUG)
  14. def console(log, level):
  15. log.setLevel(level)
  16. if level == logging.DEBUG:
  17. formatter = logging.Formatter('%(asctime)s - %(name)14s - %(levelname)7s - %(funcName)10s:%(lineno)3d - %(message)s')
  18. else:
  19. formatter = logging.Formatter('%(asctime)s - %(name)14s - %(levelname)7s - %(message)s')
  20. stream_handler = logging.StreamHandler()
  21. stream_handler.setFormatter(formatter)
  22. log.addHandler(stream_handler)
  23. def output(fbx, command, json_output, send_url):
  24. try:
  25. res = eval("fbx.{}".format(command))
  26. except RequestError as exc:
  27. if "403 Client Error" in str(exc):
  28. fbx.log.info("Got 403, refreshing token")
  29. fbx.mksession()
  30. res = eval("fbx.{}".format(command))
  31. else:
  32. raise(exc)
  33. if send_url:
  34. try:
  35. r = requests.post(send_url, json=res)
  36. except BaseException as exc:
  37. log.error("While sending to {}, got exception {}".format(send_url, exc))
  38. elif json_output:
  39. print(json.dumps(res))
  40. else:
  41. pp = pprint.PrettyPrinter(indent=4)
  42. pp.pprint(res)
  43. def main():
  44. log = logging.getLogger("pyfbx")
  45. parser = argparse.ArgumentParser()
  46. parser.add_argument("-a", "--app_id", type=str,
  47. help="application identifier")
  48. parser.add_argument("-t", "--token", type=str,
  49. help="token (or f:<filename>)")
  50. parser.add_argument("-v", "--verbose", action="count", default=0,
  51. help="increase verbosity to INFO, use twice for DEBUG")
  52. parser.add_argument("-n", "--http", action="store_true",
  53. help="disable MDNS and use http known address")
  54. parser.add_argument("-j", "--json", action="store_true", default=False,
  55. help="json output")
  56. parser.add_argument("-d", "--delay", type=int,
  57. help="cylically send command (number of seconds)")
  58. parser.add_argument("-u", "--url", type=str,
  59. help="specific url to query")
  60. parser.add_argument("-s", "--send", type=str,
  61. help="url to send json to")
  62. parser.add_argument("-c", "--command", action='append',
  63. help="command, defaults to System.Get_the_current_system_info()")
  64. args = parser.parse_args()
  65. console(log, log_level[min(2, args.verbose)])
  66. token = args.token
  67. app_id = args.app_id
  68. if not args.command:
  69. args.command = ["System.Get_the_current_system_info()"]
  70. myfb = Fbx(nomdns=args.http, url=args.url)
  71. try:
  72. if token:
  73. if token.startswith('f:'):
  74. with open(args.token[2:]) as tok_file:
  75. token, app_id = tok_file.read().splitlines()
  76. else:
  77. log.warning("Registering app {}, id {}, Press button".format(__name__, app_id))
  78. token = myfb.register(app_id=app_id, app_name=__name__,
  79. device=os.uname().nodename)
  80. log.warning("Save your application token: {}".format(token))
  81. myfb.mksession(app_id=app_id, token=token)
  82. while True:
  83. log.debug("-" * 8)
  84. for command in args.command:
  85. output(myfb, command, args.json, args.send)
  86. if not args.delay:
  87. break
  88. time.sleep(args.delay)
  89. except RequestError as exc:
  90. log.error("Got Http Error {}".format(exc))
  91. return 2
  92. except ResponseError as exc:
  93. log.error("Got Response Error {}".format(exc))
  94. return 1
  95. return 0
  96. if __name__ == "__main__":
  97. exit(main())