def onConnectBtn(self, e): e.EventObject.Label = "Connecting..." auth_mgr = AuthenticationManager.from_file(TOKENS_FILE) auth_mgr.authenticate() auth_mgr.dump(TOKENS_FILE) userhash = auth_mgr.userinfo.userhash token = auth_mgr.xsts_token.jwt # TODO: make a drop-down list of discovered xboxes if self.worker is None: self.discover(self.xbox_ip_address.GetValue()) if len(self.discovered): c = self.discovered[0] self.worker = XboxThread( self.GetStaticBox(), c.address, c.name, c.uuid, c.liveid, c.protocol.crypto, userhash, token ) else: print("Discover a console first") else: # Kill worker if it's alive self.worker.abort() self.worker = None
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up the Xbox One platform""" from xbox.webapi.authentication.manager import AuthenticationManager from xbox.sg.enum import ConnectionState from xbox.sg.console import Console hass.loop.set_debug(True) ip_address = config.get(CONF_IP_ADDRESS) live_id = config.get(CONF_LIVE_ID) name = config.get(CONF_NAME) tokens_file_name = hass.config.path(config.get(CONF_TOKEN_FILE)) _LOGGER.debug('Trying to authenticate') try: auth_mgr = AuthenticationManager.from_file(tokens_file_name) auth_mgr.authenticate(do_refresh=False) auth_mgr.dump(tokens_file_name) except Exception as e: _LOGGER.error(e) _LOGGER.debug('Authenticated, starting discovery.') consoles = Console.discover(timeout=1, addr=ip_address) if not consoles: _LOGGER.debug('No consoles found, could be turned off') async_add_devices([XboxOne(auth_mgr, live_id, ip_address, name)]) else: async_add_devices([ XboxOne(auth_mgr, live_id, ip_address, name, console) for console in consoles if console.liveid == live_id ])
def on_connect_request(req: ConnectionRequest): auth_mgr = AuthenticationManager.from_file(TOKENS_FILE) auth_mgr.dump(TOKENS_FILE) userhash = auth_mgr.userinfo.userhash token = auth_mgr.xsts_token.jwt for c in Console.discovered(): if str(c.uuid) == str(req.console_dict['uuid']): self._console = c if self._console is None: self.outq.put( XboxEvent(EVT_XBOX_DISCONNECT_ID, "Failed to connect")) return self._console.add_manager(TextManager) self._console.text.on_systemtext_input += on_text self._console.protocol.on_timeout += lambda: self._timedout.set() try: status = self._console.connect(userhash, token) except OSError as e: self.outq.put( XboxEvent(EVT_XBOX_DISCONNECT_ID, f"Failed to connect {e}")) return self._console.wait(1) self.outq.put(XboxEvent(EVT_XBOX_CONNECT_ID, self._console.address))
def main(): parser = argparse.ArgumentParser(description="Change your gamertag") parser.add_argument( '--tokens', '-t', default=TOKENS_FILE, help="Token filepath. Default: \'{}\'".format(TOKENS_FILE)) parser.add_argument('gamertag', help="Desired Gamertag") args = parser.parse_args() if len(args.gamertag) > 15: print('Desired gamertag exceedes limit of 15 chars') sys.exit(-1) try: auth_mgr = AuthenticationManager.from_file(args.tokens) except FileNotFoundError as e: print('Failed to load tokens from \'{}\'.\n' 'ERROR: {}'.format(e.filename, e.strerror)) sys.exit(-1) try: auth_mgr.authenticate(do_refresh=True) except AuthenticationException as e: print('Authentication failed! Err: %s' % e) sys.exit(-1) xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash, auth_mgr.xsts_token.jwt, auth_mgr.userinfo.xuid) print(':: Trying to get recent clips for xuid \'%i\'...' % xbl_client.xuid) test_gameclips_recent_own(xbl_client) # print('Claiming gamertag...') # resp = xbl_client.account.claim_gamertag(xbl_client.xuid, args.gamertag) # if resp.status_code == 409: # print('Claiming gamertag failed - Desired gamertag is unavailable') # sys.exit(-1) # elif resp.status_code != 200: # print('Invalid HTTP response from claim: %i' % resp.status_code) # print('Headers: %s' % resp.headers) # print('Response: %s' % resp.content) # sys.exit(-1) # # print('Changing gamertag...') # resp = xbl_client.account.change_gamertag(xbl_client.xuid, args.gamertag) # if resp.status_code == 1020: # print('Changing gamertag failed - You are out of free changes') # sys.exit(-1) # elif resp.status_code != 200: # print('Invalid HTTP response from change: %i' % resp.status_code) # print('Headers: %s' % resp.headers) # print('Response: %s' % resp.content) # sys.exit(-1) # print('Clips successfully fetched' % args.gamertag)
def main(): parser = argparse.ArgumentParser(description="Basic smartglass client") parser.add_argument('--tokens', '-t', default=TOKENS_FILE, help="Token file, created by xbox-authenticate script") parser.add_argument('--address', '-a', help="IP address of console") parser.add_argument('--refresh', '-r', action='store_true', help="Refresh xbox live tokens in provided token file") args = parser.parse_args() logging.basicConfig(level=logging.DEBUG) try: auth_mgr = AuthenticationManager.from_file(args.tokens) auth_mgr.authenticate(do_refresh=args.refresh) auth_mgr.dump(args.tokens) except Exception as e: print("Failed to authenticate with provided tokens, Error: %s" % e) print("Please re-run xbox-authenticate to get a fresh set") sys.exit(1) userhash = auth_mgr.userinfo.userhash token = auth_mgr.xsts_token.jwt discovered = Console.discover(timeout=1, addr=args.address) if len(discovered): console = discovered[0] console.on_timeout += on_timeout console.add_manager(InputManager) state = console.connect(userhash, token) if state != ConnectionState.Connected: print("Connection failed") sys.exit(1) console.wait(1) getch = get_getch_func() while True: ch = getch() print(ch) if ord(ch) == 3: # CTRL-C sys.exit(1) elif ch not in input_map: continue button = input_map[ch] console.gamepad_input(button) console.wait(0.1) console.gamepad_input(GamePadButton.Clear) signal.signal(signal.SIGINT, lambda *args: console.protocol.stop()) console.protocol.serve_forever() else: print("No consoles discovered") sys.exit(1)
def check_status(cls): auth_mgr = AuthenticationManager.from_file(TOKEN_FILE) try: auth_mgr.authenticate(do_refresh=True) except AuthenticationException: cls.generate_token() xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash, auth_mgr.xsts_token.jwt, auth_mgr.userinfo.xuid) friendslist = xbl_client.people.get_friends_own().json() people = [o["xuid"] for o in friendslist["people"]] profiles_data = xbl_client.profile.get_profiles(people).json() profiles = profiles_data.get("profileUsers", []) if not profiles: print("Profile Users not found!!!") status = {} for profile in profiles: profile['presence'] = xbl_client.presence.get_presence( profile['id'], presence_level=PresenceLevel.ALL).json() print(profile['presence']) xf, created = XboxFriends.objects.get_or_create(xuid=profile["id"]) changed = created xf.gamertag = cls._get_settings(profile["settings"], "Gamertag") xf.realname = cls._get_settings(profile["settings"], "RealName") xf.gamedisplayname = cls._get_settings(profile["settings"], "GameDisplayName") new_state = profile["presence"]["state"] #new_state = "Online" if new_state != xf.state: changed = True xf.state = new_state if "lastSeen" in profile["presence"]: xf.lastseen_titlename = profile["presence"]["lastSeen"][ "titleName"] xf.lastseen_timestamp = datetime.datetime.strptime( profile["presence"]["lastSeen"]["timestamp"].split(".")[0], '%Y-%m-%dT%H:%M:%S') else: xf.lastseen_timestamp = timezone.now() xf.save() print("{} is {}".format(xf.gamertag, xf.state)) status[xf] = { 'state': xf.state, 'changed': changed, 'gamertag': xf.gamertag, 'title': xf.lastseen_titlename, } return status
def main(): parser = argparse.ArgumentParser(description="Search for Content on XBL") parser.add_argument( '--tokens', '-t', default=TOKENS_FILE, help="Token filepath. Default: \'{}\'".format(TOKENS_FILE)) parser.add_argument('--legacy', '-l', action='store_true', help="Search for Xbox 360 content") parser.add_argument("--keys", action='append', type=lambda kv: kv.split("="), dest='keyvalues') parser.add_argument('search_query', help="Name to search for") args = parser.parse_args() try: auth_mgr = AuthenticationManager.from_file(args.tokens) except FileNotFoundError as e: print('Failed to load tokens from \'{}\'.\n' 'ERROR: {}'.format(e.filename, e.strerror)) sys.exit(-1) try: auth_mgr.authenticate(do_refresh=True) except AuthenticationException as e: print('Authentication failed! Err: %s' % e) sys.exit(-1) xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash, auth_mgr.xsts_token.jwt, auth_mgr.userinfo.xuid) keys = dict(args.keyvalues) if args.keyvalues else dict() if not args.legacy: resp = xbl_client.eds.get_singlemediagroup_search(args.search_query, 10, "DGame", domain="Modern", **keys) else: resp = xbl_client.eds.get_singlemediagroup_search(args.search_query, 10, "Xbox360Game", domain="Xbox360", **keys) if resp.status_code != 200: print("Invalid EDS details response") sys.exit(-1) print(json.dumps(resp.json(), indent=2))
def main(): parser = argparse.ArgumentParser(description="Power off xbox one console") parser.add_argument('--tokens', '-t', default=TOKENS_FILE, help="Token file, created by xbox-authenticate script") parser.add_argument('--liveid', '-l', help="Console Live ID") parser.add_argument('--address', '-a', help="IP address of console") parser.add_argument('--all', action='store_true', help="Power off all consoles") parser.add_argument('--refresh', '-r', action='store_true', help="Refresh xbox live tokens in provided token file") args = parser.parse_args() logging.basicConfig(level=logging.INFO) try: auth_mgr = AuthenticationManager.from_file(args.tokens) auth_mgr.authenticate(do_refresh=args.refresh) auth_mgr.dump(args.tokens) except Exception as e: print("Failed to authenticate with provided tokens, Error: %s" % e) print("Please re-run xbox-authenticate to get a fresh set") sys.exit(1) userhash = auth_mgr.userinfo.userhash token = auth_mgr.xsts_token.jwt if not args.liveid and not args.address and not args.all: print("No arguments supplied!") parser.print_help() sys.exit(1) consoles = Console.discover(timeout=1, addr=args.address) if not len(consoles): print("No consoles found!") sys.exit(1) if not args.all and args.liveid: consoles = [c for c in consoles if c.liveid == args.liveid] if not args.all and args.address: consoles = [c for c in consoles if c.address == args.address] for c in consoles: state = c.connect(userhash, token) if state != ConnectionState.Connected: print("Connecting to %s failed" % c) continue c.wait(1) print("Shutting down %s ..." % c) c.power_off()
def main(): parser = argparse.ArgumentParser(description="Basic smartglass client") parser.add_argument('--tokens', '-t', default=TOKENS_FILE, help="Token file, created by xbox-authenticate script") parser.add_argument('--address', '-a', help="IP address of console") parser.add_argument('--refresh', '-r', action='store_true', help="Refresh xbox live tokens in provided token file") parser.add_argument('--verbose', '-v', action='store_true', help="Verbose flag, also log message content") args = parser.parse_args() if args.verbose: fmt = VerboseFormatter(logging.BASIC_FORMAT) else: fmt = logging.Formatter(logging.BASIC_FORMAT) handler = logging.StreamHandler() handler.setFormatter(fmt) logging.root.addHandler(handler) logging.root.setLevel(logging.DEBUG) # logging.basicConfig(level=logging.DEBUG, format=logfmt) try: auth_mgr = AuthenticationManager.from_file(args.tokens) auth_mgr.authenticate(do_refresh=args.refresh) auth_mgr.dump(args.tokens) except Exception as e: print("Failed to authenticate with provided tokens, Error: %s" % e) print("Please re-run xbox-authenticate to get a fresh set") sys.exit(1) userhash = auth_mgr.userinfo.userhash token = auth_mgr.xsts_token.jwt discovered = Console.discover(timeout=1, addr=args.address) if len(discovered): console = discovered[0] console.on_timeout += on_timeout state = console.connect(userhash, token) if state != ConnectionState.Connected: logging.error("Connection failed") sys.exit(1) signal.signal(signal.SIGINT, lambda *args: console.protocol.stop()) console.protocol.serve_forever() else: logging.error("No consoles discovered") sys.exit(1)
def test_load_tokens_from_file(tokens_filepath): auth_manager = AuthenticationManager.from_file(tokens_filepath) assert auth_manager.userinfo is not None assert auth_manager.userinfo.userhash == '1674471606081042789' assert auth_manager.userinfo.xuid == '2535428504476914' assert auth_manager.userinfo.gamertag == 'xboxWebapiGamertag' assert auth_manager.access_token.is_valid is False assert auth_manager.refresh_token.is_valid is True assert auth_manager.user_token.is_valid is True assert auth_manager.xsts_token is None
def main(): parser = argparse.ArgumentParser(description="Basic smartglass client") parser.add_argument('--tokens', '-t', default=TOKENS_FILE, help="Token file, created by xbox-authenticate script") parser.add_argument('--address', '-a', help="IP address of console") parser.add_argument('--refresh', '-r', action='store_true', help="Refresh xbox live tokens in provided token file") args = parser.parse_args() logging.basicConfig(level=logging.DEBUG) try: auth_mgr = AuthenticationManager.from_file(args.tokens) auth_mgr.authenticate(do_refresh=args.refresh) auth_mgr.dump(args.tokens) except Exception as e: print("Failed to authenticate with provided tokens, Error: %s" % e) print("Please re-run xbox-authenticate to get a fresh set") sys.exit(1) userhash = auth_mgr.userinfo.userhash token = auth_mgr.xsts_token.jwt discovered = Console.discover(timeout=1, addr=args.address) if len(discovered): console = discovered[0] console.add_manager(NanoManager) console.connect(userhash, token) if console.connection_state != ConnectionState.Connected: print("Connection failed") sys.exit(1) console.wait(1) console.nano.start_stream() console.wait(5) client = SDLClient(1920, 1080) console.nano.start_gamestream(client) try: console.protocol.serve_forever() except KeyboardInterrupt: pass else: print("No consoles discovered") sys.exit(1)
def main(): parser = argparse.ArgumentParser(description="Basic smartglass client") parser.add_argument('--tokens', '-t', default=TOKENS_FILE, help="Token file, created by xbox-authenticate script") parser.add_argument('--address', '-a', help="IP address of console") parser.add_argument('--refresh', '-r', action='store_true', help="Refresh xbox live tokens in provided token file") args = parser.parse_args() logging.basicConfig(level=logging.DEBUG) try: auth_mgr = AuthenticationManager.from_file(args.tokens) auth_mgr.authenticate(do_refresh=args.refresh) auth_mgr.dump(args.tokens) except Exception as e: print("Failed to authenticate with provided tokens, Error: %s" % e) print("Please re-run xbox-authenticate to get a fresh set") sys.exit(1) userhash = auth_mgr.userinfo.userhash token = auth_mgr.xsts_token.jwt discovered = Console.discover(timeout=1, addr=args.address) if len(discovered): console = discovered[0] console.on_timeout += on_timeout console.add_manager(TextManager) console.text.on_systemtext_configuration += on_text_config console.text.on_systemtext_input += functools.partial( on_text_input, console) console.text.on_systemtext_done += on_text_done state = console.connect(userhash, token) if state != ConnectionState.Connected: print("Connection failed") sys.exit(1) console.wait(1) signal.signal(signal.SIGINT, lambda *args: console.protocol.stop()) console.protocol.serve_forever() else: print("No consoles discovered") sys.exit(1)
def do_authentication(token_filepath, do_refresh): """ Shortcut for doing xbox live authentication (uses xbox-webapi-python lib). Args: token_filepath (str): Token filepath do_refresh (bool): Whether to refresh tokens Returns: AuthenticationManager: An authenticated instance Raises: AuthenticationException: If authentication failed """ auth_mgr = AuthenticationManager.from_file(token_filepath) auth_mgr.authenticate(do_refresh=do_refresh) if do_refresh: auth_mgr.dump(token_filepath) return auth_mgr
# Mac OSX: /Users/<username>/Library/Application Support/xbox/tokens.json # Linux: /home/<username>/.local/share/xbox # # For more information, see: https://pypi.org/project/appdirs and module: xbox.webapi.scripts.constants xbox-authenticate --tokens tokens.json --email [email protected] --password abc123 # NOTE: If no credentials are provided via cmdline, they are requested from stdin xbox-authenticate --tokens tokens.json # If you have a shell compatible with ncurses, you can use the Terminal UI app xbox-auth-ui --tokens tokens.json """ try: auth_mgr = AuthenticationManager.from_file('tokens/tokens.json') except FileNotFoundError as e: print('Failed to load tokens from \'{}\'.\n' 'ERROR: {}'.format(e.filename, e.strerror)) sys.exit(-1) try: auth_mgr.authenticate(do_refresh=True) except AuthenticationException as e: print('Authentication failed! Err: %s' % e) sys.exit(-1) xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash, auth_mgr.xsts_token.jwt, auth_mgr.userinfo.xuid) # Some example API calls
def main(): parser = argparse.ArgumentParser(description="Search for Content on XBL") parser.add_argument('--tokens', '-t', default=TOKENS_FILE, help="Token file, if file doesnt exist it gets created") args = parser.parse_args() mgr = AuthenticationManager.from_file(args.tokens) client = XboxLiveClient(mgr.userinfo.userhash, mgr.xsts_token.jwt, mgr.userinfo.xuid) with betamax.Betamax.configure() as config: config.cassette_library_dir = CASSETTE_LIBRARY_DIR config.default_cassette_options['record_mode'] = 'new_episodes' config.default_cassette_options['serialize_with'] = 'prettyjson' # Make sure to not expose private tokens config.define_cassette_placeholder( "<UHS>", mgr.userinfo.userhash ) config.define_cassette_placeholder( "<JWT>", mgr.xsts_token.jwt ) config.define_cassette_placeholder( "<XUID>", str(mgr.userinfo.xuid) ) def dump_response(resp): print(resp.status_code) if resp.status_code != 200: print(resp.headers) print(resp.content) sys.exit(1) print(json.dumps(resp.json(), indent=2)) print('!!! SUCCESS !!!') recorder = betamax.Betamax(client.session) """ EDIT TO RECORD NEW API ENDPOINT """ title_id = '219630713' xuid = '2669321029139235' # req = [ # # client.screenshots.get_recent_own_screenshots(), # # client.screenshots.get_recent_own_screenshots(title_id), # # client.screenshots.get_recent_screenshots_by_xuid(xuid), # client.screenshots.get_recent_screenshots_by_xuid(xuid, title_id), # # client.screenshots.get_saved_community_screenshots_by_title_id(title_id), # # client.screenshots.get_saved_own_screenshots(), # # client.screenshots.get_saved_own_screenshots(title_id), # # client.screenshots.get_saved_screenshots_by_xuid(xuid), # # client.screenshots.get_saved_screenshots_by_xuid(xuid, title_id) # ] with recorder.use_cassette('screenshots_community'): client.screenshots.get_recent_community_screenshots_by_title_id(title_id) with recorder.use_cassette('screenshots_specific_user'): client.screenshots.get_recent_screenshots_by_xuid(xuid, title_id)
def initiate_turbo(name, accounts, gamertags): counter = 0 password = load_password() auth.main(name, password) try: auth_mgr = AuthenticationManager.from_file( 'C:/Users/Admin/AppData/Local/OpenXbox/xbox/tokens.json') except FileNotFoundError as e: print('Failed to load tokens from \'{}\'.\n' 'ERROR: {}'.format(e.filename, e.strerror)) sys.exit(-1) try: auth_mgr.authenticate(do_refresh=True) except AuthenticationException as e: print('Authentication failed! Err: %s' % e) sys.exit(-1) xbl_client = XboxLiveClient(auth_mgr.userinfo.userhash, auth_mgr.xsts_token.jwt, auth_mgr.userinfo.xuid) while True: for tag in gamertags: time.sleep(0.15) if xbl_client.profile.get_profile_by_gamertag( tag).status_code == 200: print(tag + ': Not available for claiming') else: response = xbl_client.accounts.change_gamertag( str(xbl_client.xuid), tag) if response.status_code == 200: update_log(tag) print("Tag: " + tag + " has been claimed!") try: name = accounts.pop(0) gamertags.remove(tag) except: print("No more accounts available to claim!") sys.exit(0) initiate_turbo(name, accounts, gamertags) elif response.status_code == 403: os.remove( "C:/Users/Admin/AppData/Local/OpenXbox/xbox/tokens.json" ) print("Tag is not yet out in wild") print("Refreshing tokens.json") initiate_turbo(name, accounts, gamertags) elif response.status_code == 429: time.sleep(15) elif response.status_code == 1020: print( 'Changing gamertag failed - You are out of free changes' ) else: time.sleep(0.5) os.remove( "C:/Users/Admin/AppData/Local/OpenXbox/xbox/tokens.json" ) print("Refreshing tokens.json") initiate_turbo(name, accounts, gamertags) counter += 1 if counter % 298 == 0: cls = lambda: os.system('cls') cls() time.sleep(1) if counter % 600 == 0: return