Beispiel #1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up xbox from a config entry."""
    implementation = (
        await config_entry_oauth2_flow.async_get_config_entry_implementation(
            hass, entry
        )
    )
    session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
    auth = api.AsyncConfigEntryAuth(
        aiohttp_client.async_get_clientsession(hass), session
    )

    client = XboxLiveClient(auth)
    consoles: SmartglassConsoleList = await client.smartglass.get_console_list()
    _LOGGER.debug(
        "Found %d consoles: %s",
        len(consoles.result),
        consoles.dict(),
    )

    coordinator = XboxUpdateCoordinator(hass, client, consoles)
    await coordinator.async_config_entry_first_refresh()

    hass.data[DOMAIN][entry.entry_id] = {
        "client": XboxLiveClient(auth),
        "consoles": consoles,
        "coordinator": coordinator,
    }

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Beispiel #2
0
    async def on_startup(self):
        await Tortoise.init(db_url=os.environ.get("DB_URL"),
                            modules={"models": ["common.models"]})
        self.redis = aioredis.from_url(os.environ.get("REDIS_URL"),
                                       decode_responses=True)

        self.session = aiohttp.ClientSession()
        auth_mgr = AuthenticationManager(
            self.session,
            os.environ["XBOX_CLIENT_ID"],
            os.environ["XBOX_CLIENT_SECRET"],
            "",
        )
        auth_mgr.oauth = OAuth2TokenResponse.parse_file(
            os.environ["XAPI_TOKENS_LOCATION"])
        await auth_mgr.refresh_tokens()
        xbl_client = XboxLiveClient(auth_mgr)
        self.profile = ProfileProvider(xbl_client)
        self.club = ClubProvider(xbl_client)

        self.realms = RealmsAPI(aiohttp.ClientSession())

        headers = {
            "X-Authorization": os.environ["OPENXBL_KEY"],
            "Accept": "application/json",
            "Accept-Language": "en-US",
        }
        self.openxbl_session = aiohttp.ClientSession(headers=headers)
Beispiel #3
0
def test_authorization_header(auth_mgr):
    client = XboxLiveClient(auth_mgr)

    assert (
        client._auth_mgr.xsts_token.authorization_header_value
        == "XBL3.0 x=abcdefg;123456789"
    )
Beispiel #4
0
    async def gamertag_from_xuid(self, ctx, xuid: int):
        if str(xuid) in self.bot.gamertags.keys():
            await ctx.send(
                f"Gamertag for `{xuid}`: {self.bot.gamertags[str(xuid)]}")
        else:
            async with AuthenticationManager(
                    os.environ.get("XBOX_EMAIL"),
                    os.environ.get("XBOX_PASSWORD")) as auth_mgr:
                async with XboxLiveClient(auth_mgr.userinfo.userhash,
                                          auth_mgr.xsts_token.jwt,
                                          auth_mgr.userinfo.xuid) as xb_client:
                    profile = await xb_client.profile.get_profile_by_xuid(xuid)

                    try:
                        resp_json = await profile.json()
                    except aiohttp.ContentTypeError:
                        await ctx.send(
                            f"ERROR: Unable to find gamertag from XUID `{xuid}`! Make sure you have entered it in correctly."
                        )
                        return

            if "code" in resp_json.keys():
                await ctx.send(
                    f"ERROR: Unable to find gamertag from XUID `{xuid}`! Make sure you have entered it in correctly."
                )
            else:
                settings = {}
                for setting in resp_json["profileUsers"][0]["settings"]:
                    settings[setting["id"]] = setting["value"]

                self.bot.gamertags[str(xuid)] = settings["Gamertag"]
                await ctx.send(f"Gamertag for `{xuid}`: {settings['Gamertag']}"
                               )
Beispiel #5
0
    async def xuid_from_gamertag(self, ctx, *, gamertag):
        if gamertag in self.bot.gamertags.values():
            xuid = next(e for e in self.bot.gamertags.keys()
                        if self.bot.gamertags[e] == gamertag)
            await ctx.send(f"XUID of `{gamertag}`: `{xuid}`")
        else:
            async with AuthenticationManager(
                    os.environ.get("XBOX_EMAIL"),
                    os.environ.get("XBOX_PASSWORD")) as auth_mgr:
                async with XboxLiveClient(auth_mgr.userinfo.userhash,
                                          auth_mgr.xsts_token.jwt,
                                          auth_mgr.userinfo.xuid) as xb_client:
                    profile = await xb_client.profile.get_profile_by_gamertag(
                        gamertag)

                    try:
                        resp_json = await profile.json()
                    except aiohttp.ContentTypeError:
                        await ctx.send(
                            f"ERROR: Unable to find XUID from gamertag `{gamertag}`! Make sure you have entered it in correctly."
                        )
                        return

            if "code" in resp_json.keys():
                await ctx.send(
                    f"ERROR: Unable to find XUID from gamertag `{gamertag}`! Make sure you have entered it in correctly."
                )
            else:
                xuid = resp_json["profileUsers"][0]["id"]
                self.bot.gamertags[str(xuid)] = gamertag
                await ctx.send(f"XUID of `{gamertag}`: `{xuid}`")
 def xbl_client(self):
     if self.authentication_mgr.authenticated:
         self._xbl_client = XboxLiveClient(
             userhash=self.authentication_mgr.userinfo.userhash,
             auth_token=self.authentication_mgr.xsts_token.jwt,
             xuid=self.authentication_mgr.userinfo.xuid)
     return self._xbl_client
async def xboxlive_login_callback(
    code: str,
    state: str,
    error: Optional[str] = None
):
    if error:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error)
    elif not code or not state:
        parameter_name = 'Code' if not code else 'State'
        error_detail = f'{parameter_name} missing from authorization callback'
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=error_detail)

    # Get auth session config that was set previously when
    # generating authorization redirect
    auth_session_config = singletons.auth_session_configs.get(state)
    if not auth_session_config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f'Auth session config for state \'{state}\' not found'
        )

    # Construct authentication manager that will be cached
    auth_mgr = generate_authentication_manager(
        auth_session_config,
        singletons.http_session
    )
    await auth_mgr.request_tokens(code)

    singletons.authentication_manager = auth_mgr
    singletons.xbl_client = XboxLiveClient(singletons.authentication_manager)
    return RedirectResponse(url='/auth')
Beispiel #8
0
async def test():
    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(session, args.client_id,
                                         args.client_secret, "")

        with open(args.tokens, mode="r") as f:
            tokens = f.read()
        auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
        try:
            auth_mgr.refresh_tokens()
        except ClientResponseError:
            print("Could not refresh tokens")
            sys.exit(-1)

        with open(args.tokens, mode="w") as f:
            f.write(auth_mgr.oauth.json())

        xbl_client = XboxLiveClient(auth_mgr)

        # Some example API calls

        # Get friendslist
        friendslist = await xbl_client.people.get_friends_own()

        # Get presence status (by list of XUID)
        presence = await xbl_client.presence.get_presence_batch(
            ["12344567687845", "453486346235151"])

        # Get messages
        messages = await xbl_client.message.get_inbox()

        # Get profile by GT
        profile = await xbl_client.profile.get_profile_by_gamertag(
            "SomeGamertag")
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)
Beispiel #10
0
    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
Beispiel #11
0
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))
async def async_main():
    parser = argparse.ArgumentParser(description="Change your gamertag")
    parser.add_argument(
        "--tokens",
        "-t",
        default=TOKENS_FILE,
        help=f"Token filepath. Default: '{TOKENS_FILE}'",
    )
    parser.add_argument(
        "--client-id",
        "-cid",
        default=os.environ.get("CLIENT_ID", CLIENT_ID),
        help="OAuth2 Client ID",
    )
    parser.add_argument(
        "--client-secret",
        "-cs",
        default=os.environ.get("CLIENT_SECRET", CLIENT_SECRET),
        help="OAuth2 Client Secret",
    )

    args = parser.parse_args()

    if not os.path.exists(args.tokens):
        print("No token file found, run xbox-authenticate")
        sys.exit(-1)

    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(
            session, args.client_id, args.client_secret, ""
        )

        with open(args.tokens, mode="r") as f:
            tokens = f.read()
        auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
        try:
            await auth_mgr.refresh_tokens()
        except ClientResponseError:
            print("Could not refresh tokens")
            sys.exit(-1)

        with open(args.tokens, mode="w") as f:
            f.write(auth_mgr.oauth.json())

        xbl_client = XboxLiveClient(auth_mgr)

        try:
            resp = await xbl_client.people.get_friends_own()
        except ClientResponseError:
            print("Invalid HTTP response")
            sys.exit(-1)

        pprint(resp.dict())
Beispiel #13
0
    def __init__(self, email, password):
        self.auth_mgr = AuthenticationManager()

        # set data for auth manager
        self.auth_mgr.email_address = email
        self.auth_mgr.password = password

        # authentication
        self.auth_mgr.authenticate(do_refresh=True)

        # set the new info to a xbl client
        self.xbl_client = XboxLiveClient(self.auth_mgr.userinfo.userhash,
                                         self.auth_mgr.xsts_token.jwt,
                                         self.auth_mgr.userinfo.xuid)
        # not currently used but could be useful later
        self.profile_provider = ProfileProvider(self.xbl_client)
        self.people_provider = PeopleProvider(self.xbl_client)
Beispiel #14
0
async def async_main():
    parser = argparse.ArgumentParser(description="Search for Content on XBL")
    parser.add_argument("search_query", help="Name to search for")

    args = parser.parse_args()

    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(session, "", "", "")

        # No Auth necessary for catalog searches
        xbl_client = XboxLiveClient(auth_mgr)

        try:
            resp = await xbl_client.catalog.product_search(args.search_query)
        except ClientResponseError:
            print("Search failed")
            sys.exit(-1)

        pprint(resp.dict())
Beispiel #15
0
    def __init__(self, email, password, x_auth_key):
        self.x_auth_key = x_auth_key
        self.url = 'http://xapi.us/v2'
        self.client = Client(api_key=x_auth_key)

        # use the microsoft api to get the xuid info without using requests
        self.auth_mgr = AuthenticationManager()

        # set data for auth manager
        self.auth_mgr.email_address = email
        self.auth_mgr.password = password

        # authentication
        self.auth_mgr.authenticate(do_refresh=True)

        # set the new info to a xbl client
        self.xbl_client = XboxLiveClient(self.auth_mgr.userinfo.userhash,
                                         self.auth_mgr.xsts_token.jwt,
                                         self.auth_mgr.userinfo.xuid)
        self.profile_provider = ProfileProvider(self.xbl_client)
        self.people_provider = PeopleProvider(self.xbl_client)
Beispiel #16
0
    async def verify_xbl_handler(self, gamertag, user: discord.Member):
        mem_gt_url = gamertag

        async with AuthenticationManager(
                os.environ.get("XBOX_EMAIL"),
                os.environ.get("XBOX_PASSWORD")) as auth_mgr:
            async with XboxLiveClient(auth_mgr.userinfo.userhash,
                                      auth_mgr.xsts_token.jwt,
                                      auth_mgr.userinfo.xuid) as xb_client:
                profile = await xb_client.profile.get_profile_by_gamertag(
                    mem_gt_url)

                try:
                    resp_json = await profile.json()
                except aiohttp.ContentTypeError:
                    return f"ERROR: Unable to find {user.mention}'s gamertag, `{gamertag}`! Make sure it is spelled and entered in correctly!"

        if "code" in resp_json.keys():
            return f"ERROR: Unable to find {user.mention}'s gamertag, `{gamertag}`! Make sure it is spelled and entered in correctly!"
        else:
            settings = {}
            for setting in resp_json["profileUsers"][0]["settings"]:
                settings[setting["id"]] = setting["value"]

            if settings["XboxOneRep"] != "GoodPlayer":
                return "".join((
                    f"WARNING: {user.mention}'s gamertag exists, but doesn't have the best reputation on Xbox Live! ",
                    "Be careful! A mod must bypass this check for the user to be verified."
                ))
            elif settings["Gamerscore"] == "0":
                return "".join((
                    f"WARNING: {user.mention}'s gamertag exists, but has no gamerscore! ",
                    "This is probably a new user, so be careful! A mod must bypass this check for ",
                    "the user to be verified."))
            else:
                return "OK"
def xbl_client(auth_mgr):
    return XboxLiveClient(auth_mgr)
Beispiel #18
0
"""

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

# Get friendslist
friendslist = xbl_client.people.get_friends_own()
resp = friendslist.json()
print(resp)
people = [o["xuid"] for o in resp["people"]]
print(people)

# Get presence status (by list of XUID)
#presence = xbl_client.presence.get_presence_batch(people)
#presence = xbl_client.presence.get_presence_batch(people, presence_level=PresenceLevel.ALL)

for p in people:
Beispiel #19
0
async def async_main():
    parser = argparse.ArgumentParser(description="Change your gamertag")
    parser.add_argument(
        "--tokens",
        "-t",
        default=TOKENS_FILE,
        help=f"Token filepath. Default: '{TOKENS_FILE}'",
    )
    parser.add_argument(
        "--client-id",
        "-cid",
        default=os.environ.get("CLIENT_ID", CLIENT_ID),
        help="OAuth2 Client ID",
    )
    parser.add_argument(
        "--client-secret",
        "-cs",
        default=os.environ.get("CLIENT_SECRET", CLIENT_SECRET),
        help="OAuth2 Client Secret",
    )

    args = parser.parse_args()

    if not os.path.exists(args.tokens):
        print("No token file found, run xbox-authenticate")
        sys.exit(-1)

    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(
            session, args.client_id, args.client_secret, ""
        )

        with open(args.tokens, mode="r") as f:
            tokens = f.read()
        auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
        try:
            await auth_mgr.refresh_tokens()
        except ClientResponseError:
            print("Could not refresh tokens")
            sys.exit(-1)

        with open(args.tokens, mode="w") as f:
            f.write(auth_mgr.oauth.json())

        xbl_client = XboxLiveClient(auth_mgr)

        try:
            uniname = "c:/users/willr/downloads/UNIQUENAME9.mp4"
            # resp = await xbl_client.screenshots.get_recent_own_screenshots(max_items=3)
            resp = await xbl_client.gameclips.get_recent_own_clips(max_items=1)
            # downloadLink = resp.game_clips[0].game_clip_uris[0].uri
            # wget.download(downloadLink, uniname)
            # clip = VideoFileClip(uniname).subclip(8)
            # clip.write_videofile("c:/users/willr/downloads/UNIQUENAME9-finished.mp4",temp_audiofile='temp-audio.m4a', remove_temp=True, codec="libx264", audio_codec="aac")
            # clip.close()
            # highlightz = TweetMachine()
            # highlightz.makeAVidTweet('c:/users/willr/downloads/UNIQUENAME9-finished.mp4','🚨🚨🚨BUZZER BEATER ALERT🚨🚨🚨')
        except ClientResponseError:
            print("Invalid HTTP response")
            sys.exit(-1)

        pprint(resp.dict())
Beispiel #20
0
def test_xuid_from_int():
    client = XboxLiveClient('userhash', 'token', 1234567890)

    assert client.xuid == 1234567890
async def async_main():
    parser = argparse.ArgumentParser(description="Change your gamertag")
    parser.add_argument(
        "--tokens",
        "-t",
        default=TOKENS_FILE,
        help=f"Token filepath. Default: '{TOKENS_FILE}'",
    )
    parser.add_argument(
        "--client-id",
        "-cid",
        default=os.environ.get("CLIENT_ID", CLIENT_ID),
        help="OAuth2 Client ID",
    )
    parser.add_argument(
        "--client-secret",
        "-cs",
        default=os.environ.get("CLIENT_SECRET", CLIENT_SECRET),
        help="OAuth2 Client Secret",
    )
    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)

    if not os.path.exists(args.tokens):
        print("No token file found, run xbox-authenticate")
        sys.exit(-1)

    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(session, args.client_id,
                                         args.client_secret, "")

        with open(args.tokens, mode="r") as f:
            tokens = f.read()
        auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
        try:
            await auth_mgr.refresh_tokens()
        except ClientResponseError:
            print("Could not refresh tokens")
            sys.exit(-1)

        with open(args.tokens, mode="w") as f:
            f.write(auth_mgr.oauth.json())

        xbl_client = XboxLiveClient(auth_mgr)

        print(":: Trying to change gamertag to '%s' for xuid '%i'..." %
              (args.gamertag, xbl_client.xuid))

        print("Claiming gamertag...")
        try:
            resp = await xbl_client.account.claim_gamertag(
                xbl_client.xuid, args.gamertag)
            if resp == ClaimGamertagResult.NotAvailable:
                print(
                    "Claiming gamertag failed - Desired gamertag is unavailable"
                )
                sys.exit(-1)
        except ClientResponseError:
            print("Invalid HTTP response from claim")
            sys.exit(-1)

        print("Changing gamertag...")
        try:
            resp = await xbl_client.account.change_gamertag(
                xbl_client.xuid, args.gamertag)
            if resp == ChangeGamertagResult.NoFreeChangesAvailable:
                print("Changing gamertag failed - You are out of free changes")
                sys.exit(-1)
        except ClientResponseError:
            print("Invalid HTTP response from change")
            sys.exit(-1)

        print("Gamertag successfully changed to %s" % args.gamertag)
Beispiel #22
0
def test_xuid_from_string():
    client = XboxLiveClient('userhash', 'token', '1234567890')

    assert client.xuid == 1234567890
Beispiel #23
0
def test_invalid_xuid_format():
    with pytest.raises(ValueError):
        XboxLiveClient('userhash', 'token', b'1234567890')
def xbl_client(auth_mgr):
    yield XboxLiveClient(auth_mgr)
Beispiel #25
0
def test_authorization_header():
    client = XboxLiveClient('userhash', 'token', '1234567890')

    assert client.session.headers['Authorization'] == 'XBL3.0 x=userhash;token'
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
Beispiel #27
0
    async def playerlist(self, ctx, **kwargs):

        if not "no_init_mes" in kwargs.keys():
            if self.bot.gamertags == {}:
                await ctx.send(
                    "This will probably take a long time as the bot does not have a gamertag cache. Please be patient."
                )
            else:
                await ctx.send("This might take a bit. Please be patient.")

        async with ctx.channel.typing():
            now = datetime.datetime.utcnow()

            if not "limited" in kwargs.keys():
                time_delta = datetime.timedelta(days=1)
            else:
                time_delta = datetime.timedelta(hours=2)

            time_ago = now - time_delta

            xuid_list = []
            state_list = []
            last_seen_list = []

            online_list = []
            offline_list = []

            async with AuthenticationManager(
                    os.environ.get("XBOX_EMAIL"),
                    os.environ.get("XBOX_PASSWORD")) as auth_mgr:
                async with XboxLiveClient(auth_mgr.userinfo.userhash,
                                          auth_mgr.xsts_token.jwt,
                                          auth_mgr.userinfo.xuid) as xb_client:
                    club_presence = await self.bappo_club_get(xb_client)

                    for member in club_presence:
                        last_seen = datetime.datetime.strptime(
                            member["lastSeenTimestamp"][:-2],
                            "%Y-%m-%dT%H:%M:%S.%f")
                        if last_seen > time_ago:
                            xuid_list.append(member["xuid"])
                            state_list.append(member["lastSeenState"])
                            last_seen_list.append(last_seen)
                        else:
                            break

                    xuid_list_filter = xuid_list.copy()
                    for xuid in xuid_list_filter:
                        if str(xuid) in self.bot.gamertags.keys():
                            xuid_list_filter.remove(xuid)

                    profiles, new_xuid_list = await self.try_until_valid(
                        xb_client, xuid_list_filter)
                    users = profiles["profileUsers"]
                    users = self.get_diff_xuids(users, xuid_list,
                                                new_xuid_list)

            def add_list(gamertag, state, last_seen):
                if state == "InGame":
                    online_list.append(f"{gamertag}")
                else:
                    time_format = last_seen.strftime("%x %X (%I:%M:%S %p) UTC")
                    offline_list.append(f"{gamertag}: last seen {time_format}")

            for i in range(len(xuid_list)):
                entry = users[i]
                state = state_list[i]
                last_seen = last_seen_list[i]

                gamertag = f"User with xuid {xuid_list[i]}"

                if entry == "Gamertag not gotten":
                    if str(xuid_list[i]) in self.bot.gamertags.keys():
                        gamertag = self.bot.gamertags[str(xuid_list[i])]
                else:
                    try:
                        settings = {}
                        for setting in entry["settings"]:
                            settings[setting["id"]] = setting["value"]

                        gamertag = settings["Gamertag"]
                        self.bot.gamertags[str(xuid_list[i])] = gamertag
                    except KeyError:
                        gamertag = f"User with xuid {xuid_list[i]}"

                add_list(gamertag, state, last_seen)

        if online_list != []:
            online_str = "```\nPeople online right now:\n\n"
            online_str += "\n".join(online_list)
            await ctx.send(online_str + "\n```")

        if offline_list != []:
            if len(offline_list) < 20:
                if not "limited" in kwargs.keys():
                    offline_str = "```\nOther people on in the last 24 hours:\n\n"
                else:
                    offline_str = "```\nOther people on in the last 2 hours:\n\n"

                offline_str += "\n".join(offline_list)
                await ctx.send(offline_str + "\n```")
            else:
                chunks = [
                    offline_list[x:x + 20]
                    for x in range(0, len(offline_list), 20)
                ]

                if not "limited" in kwargs.keys():
                    first_offline_str = "```\nOther people on in the last 24 hours:\n\n" + "\n".join(
                        chunks[0]) + "\n```"
                else:
                    first_offline_str = "```\nOther people on in the last 2 hours:\n\n" + "\n".join(
                        chunks[0]) + "\n```"

                await ctx.send(first_offline_str)

                for x in range(len(chunks)):
                    if x == 0:
                        continue

                    offline_chunk_str = "```\n" + "\n".join(
                        chunks[x]) + "\n```"
                    await ctx.send(offline_chunk_str)
def xbl_client():
    return XboxLiveClient(
        userhash='012345679',
        auth_token='eyToken==',
        xuid='987654321'
    )
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)