Esempio n. 1
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']}"
                               )
Esempio n. 2
0
def test_extract_js_node(windows_live_authenticate_response):
    auth_manager = AuthenticationManager()
    js_node = auth_manager.extract_js_object(windows_live_authenticate_response, 'ServerData')

    assert js_node is not None
    assert js_node['sFTTag'] == "<input name=\"PPFT\" value=\"normally_base64_encoded_string_here+\"/>"
    assert js_node['urlPost'] == "https://login.live.com/ppsecure/post.srf?response_type=token"
Esempio n. 3
0
def test_parsing_redirect_url_success(redirect_url):
    access, refresh = AuthenticationManager().parse_redirect_url(redirect_url)

    assert access.is_valid
    assert refresh.is_valid
    assert len(refresh.jwt) == 12
    assert len(access.jwt) == 11
Esempio n. 4
0
    def __init__(self, tokenfile_path):
        self.tokenfile_path = tokenfile_path

        self.auth_mgr = AuthenticationManager()
        self.two_factor_auth = None

        # 2FA cache
        self.index = None
        self.proof = None
        self.otc = None

        self.loop = None
        self.log = LogListBox(self)

        self.view_stack = []

        try:
            self.auth_mgr.load(self.tokenfile_path)
        except Exception as e:
            logging.debug('Tokens failed to load from file, Error: {}'.format(e))

        '''
        self.need_refresh = self.auth_mgr.refresh_token and \
            self.auth_mgr.refresh_token.is_valid and \
            self.auth_mgr.refresh_token.date_valid < (datetime.now(tzutc()) + timedelta(days=7))
        '''
        self.need_full_auth = not self.auth_mgr.refresh_token or not self.auth_mgr.refresh_token.is_valid
Esempio n. 5
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")
Esempio n. 6
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)
Esempio n. 7
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 __init__(self, name):
        super(SmartGlassFlaskApp, self).__init__(name)

        self.console_cache = {}
        self.title_cache = {}
        self.authentication_mgr = AuthenticationManager()
        self.token_file = None
        self._xbl_client = None
Esempio n. 9
0
async def auth_mgr(event_loop):
    session = ClientSession(loop=event_loop)
    mgr = AuthenticationManager(session, "abc", "123", "http://localhost")
    mgr.oauth = OAuth2TokenResponse.parse_raw(get_response("auth_oauth2_token"))
    mgr.user_token = XAUResponse.parse_raw(get_response("auth_user_token"))
    mgr.xsts_token = XSTSResponse.parse_raw(get_response("auth_xsts_token"))
    yield mgr
    await session.close()
Esempio n. 10
0
async def auth_mgr(event_loop):
    mgr = AuthenticationManager(
        ClientSession(loop=event_loop), "abc", "123", "http://localhost"
    )
    mgr.oauth = OAuth2TokenResponse.parse_raw(get_response("auth_oauth2_token"))
    mgr.user_token = XAUResponse.parse_raw(get_response("auth_user_token"))
    mgr.xsts_token = XSTSResponse.parse_raw(get_response("auth_xsts_token"))
    return mgr
Esempio n. 11
0
def main():
    parser = argparse.ArgumentParser(description="Authenticate with xbox live")
    parser.add_argument('--tokens', '-t', default=TOKENS_FILE,
                        help="Token filepath, file gets created if nonexistent and auth is successful."
                             " Default: {}".format(TOKENS_FILE))
    parser.add_argument('--email', '-e',
                        help="Microsoft Account Email address")
    parser.add_argument('--password', '-p',
                        help="Microsoft Account password")

    args = parser.parse_args()

    tokens_loaded = False
    two_factor_auth_required = False
    server_data = None

    auth_mgr = AuthenticationManager()
    if args.tokens:
        try:
            auth_mgr.load(args.tokens)
            tokens_loaded = True
        except FileNotFoundError as e:
            print('Failed to load tokens from \'{}\'. Error: {}'.format(e.filename, e.strerror))

    auth_mgr.email_address = args.email
    auth_mgr.password = args.password

    if (not args.email or not args.password) and not tokens_loaded:
        print("Please input authentication credentials")
    if not args.email and not tokens_loaded:
        auth_mgr.email_address = input("Microsoft Account Email: ")
    if not args.password and not tokens_loaded:
        auth_mgr.password = getpass.getpass('Microsoft Account Password: '******'2FA is required, message: %s' % e)
        two_factor_auth_required = True
        server_data = e.server_data
    except AuthenticationException as e:
        print('Email/Password authentication failed! Err: %s' % e)
        sys.exit(-1)

    if two_factor_auth_required:
        try:
            two_factor_auth(auth_mgr, server_data)
        except AuthenticationException as e:
            print('2FA Authentication failed! Err: %s' % e)
            sys.exit(-1)

    if args.tokens:
        auth_mgr.dump(args.tokens)

    print('Refresh Token: %s' % auth_mgr.refresh_token)
    print('XSTS Token: %s' % auth_mgr.xsts_token)
    print('Userinfo: %s' % auth_mgr.userinfo)
Esempio n. 12
0
def test_auth_invalid_credentials():
    auth_manager = AuthenticationManager()
    auth_manager.email_address = "*****@*****.**"
    auth_manager.password = "******"

    with Betamax(auth_manager.session).use_cassette('invalid_auth'):
        with pytest.raises(AuthenticationException):
            auth_manager.authenticate()

    assert auth_manager.authenticated is False
Esempio n. 13
0
 def __attrs_post_init__(self):
     self.auth_mgr = AuthenticationManager(
         self.session,
         os.environ["XBOX_CLIENT_ID"],
         os.environ["XBOX_CLIENT_SECRET"],
         "",
     )
     self.auth_mgr.oauth = OAuth2TokenResponse.parse_file(
         os.environ["XAPI_TOKENS_LOCATION"])
     asyncio.create_task(self.refresh_tokens())
Esempio n. 14
0
def generate_authentication_manager(
    session_config: AuthSessionConfig,
    http_session: aiohttp.ClientSession = None
) -> AuthenticationManager:
    return AuthenticationManager(
        client_session=http_session,
        client_id=session_config.client_id,
        client_secret=session_config.client_secret,
        redirect_uri=session_config.redirect_uri,
        scopes=session_config.scopes
    )
Esempio n. 15
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:
            resp = await xbl_client.people.get_friends_own()
        except ClientResponseError:
            print("Invalid HTTP response")
            sys.exit(-1)

        pprint(resp.dict())
Esempio n. 16
0
def test_auth_valid_credentials():
    auth_manager = AuthenticationManager()
    auth_manager.email_address = "*****@*****.**"
    auth_manager.password = "******"

    with Betamax(auth_manager.session).use_cassette('full_auth'):
        auth_manager.authenticate(do_refresh=False)

    assert auth_manager.authenticated is True
    assert auth_manager.xsts_token.is_valid is True
    assert auth_manager.access_token.is_valid is True
    assert auth_manager.refresh_token.is_valid is True
    assert auth_manager.user_token.is_valid is True
    assert auth_manager.userinfo.userhash == '1674471606081042789'
    assert auth_manager.userinfo.xuid == '2535428504476914'
    assert auth_manager.userinfo.gamertag == 'xboxWebapiGamertag'
Esempio n. 17
0
def test_save_tokens_to_file(tmpdir, jwt, token_timestring):
    filepath = os.path.join(str(tmpdir), 'save_tokens.json')
    auth_manager = AuthenticationManager()

    auth_manager.access_token = AccessToken(jwt, 1000)
    auth_manager.xsts_token = XSTSToken(jwt, token_timestring, token_timestring)
    auth_manager.userinfo = XboxLiveUserInfo(xuid='2535428504476914',
                                             userhash='1674471606081042789',
                                             gamertag='xboxWebapiGamertag',
                                             age_group='Adult',
                                             privileges='123 321 432 654',
                                             user_privileges='123')

    auth_manager.dump(filepath)

    assert os.path.isfile(filepath) is True
Esempio n. 18
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)
Esempio n. 19
0
def test_invalid_authmethod_choice():
    server_data = {
        'D':
        [
            {
                'data': '<some data>', 'type': 1, 'display': '*****@*****.**', 'otcEnabled': True,
                'otcSent': False, 'isLost': False, 'isSleeping': False, 'isSADef': True, 'isVoiceDef': False,
                'isVoiceOnly': False, 'pushEnabled': False
            }
        ]
    }

    auth_manager = AuthenticationManager()
    two_factor_auth = TwoFactorAuthentication(auth_manager.session, '*****@*****.**', server_data)

    with pytest.raises(IndexError):
        two_factor_auth.authenticate(strategy_index=99, proof=None, otc='')
Esempio n. 20
0
def _do_2fa(cassette_name, strategy_index, proof=None, otc=None):
    auth_manager = AuthenticationManager()
    auth_manager.email_address = '*****@*****.**'
    auth_manager.password = '******'

    with Betamax(auth_manager.session).use_cassette(cassette_name):
        with pytest.raises(TwoFactorAuthRequired) as excinfo:
            auth_manager.authenticate()

        two_fa_auth = TwoFactorAuthentication(
            auth_manager.session, auth_manager.email_address, excinfo.value.server_data
        )
        two_fa_auth.check_otc(strategy_index, proof)
        access_token, refresh_token = two_fa_auth.authenticate(strategy_index, proof, otc)
        auth_manager.access_token = access_token
        auth_manager.refresh_token = refresh_token
        auth_manager.authenticate(do_refresh=False)
    return auth_manager
Esempio n. 21
0
def test_auth_refresh_token():
    auth_manager = AuthenticationManager()
    auth_manager.refresh_token = RefreshToken(
        "CuZ*4TX7!SAF33cW*kzdFmgCLPRcz0DtUHFqjQgF726!FG3ScC5yMiDLsJYJ03m4fURrzf3J7X8l6A8mJGhHoRf42aHeJLrtp6wS"
        "Jh*PudaQdPNGJZHD1CpU4diJJxz0zhrijFsaAYXMqf3mSU7EerR5RtdHOwbcrlRlj7TBQ9RdLqWpy9KWsNhyPrwOMDJnBfAf3xsZ"
        "3g3QkmMeKGil85*q*MV*YqMPZTa8UVLPfM!jJeHwOjVhWPaYVq4hf6zIAwSLJl1Reo6GbkkPktrK3laFBGeqSkq651YgdjwtepwC"
        "Ef7oMwzz8c8msv8l95RU*QmtIjdRFd!fYtQctiGLDGs$")

    with Betamax(auth_manager.session).use_cassette('token_refresh'):
        auth_manager.authenticate(do_refresh=True)

    assert auth_manager.authenticated is True
    assert auth_manager.xsts_token.is_valid is True
    assert auth_manager.access_token.is_valid is True
    assert auth_manager.refresh_token.is_valid is True
    assert auth_manager.user_token.is_valid is True
    assert auth_manager.userinfo.userhash == '1674471606081042789'
    assert auth_manager.userinfo.xuid == '2535428504476914'
    assert auth_manager.userinfo.gamertag == 'xboxWebapiGamertag'
Esempio n. 22
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())
Esempio n. 23
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)
async def async_main(client_id: str, client_secret: str, redirect_uri: str,
                     token_filepath: str):

    async with ClientSession() as session:
        auth_mgr = AuthenticationManager(session, client_id, client_secret,
                                         redirect_uri)

        # Refresh tokens if we have them
        if os.path.exists(token_filepath):
            with open(token_filepath, mode="r") as f:
                tokens = f.read()
            auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
            await auth_mgr.refresh_tokens()

        # Request new ones if they are not valid
        if not (auth_mgr.xsts_token and auth_mgr.xsts_token.is_valid()):
            auth_url = auth_mgr.generate_authorization_url()
            webbrowser.open(auth_url)
            code = await queue.get()
            await auth_mgr.request_tokens(code)

        with open(token_filepath, mode="w") as f:
            f.write(auth_mgr.oauth.json())
async def do_authentication(args: argparse.Namespace) -> AuthenticationManager:
    """
    Shortcut for doing xbox live authentication (uses xbox-webapi-python lib).

    Args:
        args: Parsed arguments

    Returns: An authenticated instance of AuthenticationManager

    Raises:
        AuthenticationException: If authentication failed
    """
    async with aiohttp.ClientSession() as session:
        auth_mgr = AuthenticationManager(
            session, args.client_id, args.client_secret, args.redirect_uri
        )

        # Refresh tokens if we have them
        if os.path.exists(args.tokens):
            with open(args.tokens, mode="r") as f:
                tokens = f.read()
            auth_mgr.oauth = OAuth2TokenResponse.parse_raw(tokens)
            await auth_mgr.refresh_tokens()

        # Request new ones if they are not valid
        if not (auth_mgr.xsts_token and auth_mgr.xsts_token.is_valid()):
            auth_url = auth_mgr.generate_authorization_url()
            print(f'Authorize with following URL: {auth_url}\n')

            code = input('Enter received authorization code: ')
            await auth_mgr.request_tokens(code)

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

    return auth_mgr
Esempio n. 26
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"
Esempio n. 27
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())
Esempio n. 28
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)
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)
def nano_overview(console):
    return success(**{'nano_status': console.nano_status})


@app.route('/devices/<liveid>/nano/start')
@console_connected
def nano_start(console):
    console.nano_start()
    return success()


@app.route('/devices/<liveid>/nano/stop')
@console_connected
def nano_stop(console):
    console.nano_stop()
    return success()
"""


@app.route('/')
def webroot():

    routes = []
    for rule in app.url_map.iter_rules():
        routes.append('%s' % rule)

    return success(endpoints=sorted(routes), version=xbox.rest.__version__)

console_cache = {}
authentication_mgr = AuthenticationManager()