Esempio n. 1
0
    def login(self, email, password):
        """
        Attempts to create an authenticated session using the email and
        password provided.
        Return ``True`` if the login was successful, ``False`` otherwise.
        Raises AlreadyLoggedIn if the session is already authenticated.

        :param email: The email address of the account to log in.
        :param password: The password of the account to log in.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        self.client = ClientLogin(email, password, 'sj')
        tokenauth = TokenAuth('sj', self.PLAY_URL, 'jumper')

        if self.client.get_auth_token() is None:
            return False

        tokenauth.authenticate(self.client)
        self.web_cookies = tokenauth.get_cookies()

        if self._get_cookies():
            self.logged_in = True
        else:
            self.logged_in = False

        return self.logged_in
    def login(self, email, password):
        """
        Attempts to create an authenticated session using the email and
        password provided.
        Return True if the login was successful, False otherwise.
        Raises AlreadyLoggedIn if the session is already authenticated.

        :param email: The email address of the account to log in.
        :param password: The password of the account to log in.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        self.client = ClientLogin(email, password, 'sj')
        tokenauth = TokenAuth('sj', self.PLAY_URL, 'jumper')

        if self.client.get_auth_token() is None:
            return False

        tokenauth.authenticate(self.client)
        self.cookies = tokenauth.get_cookies()

        self.logged_in = self._get_cookies()

        return self.logged_in
class PlaySession(object):
    """
    A Google Play Music session.

    It allows for authentication and the making of authenticated
    requests through the MusicManager API (protocol buffers), Web client requests,
    and the Skyjam client API.
    """

    # The URL for authenticating against Google Play Music
    PLAY_URL = 'https://play.google.com/music/listen?u=0&hl=en'

    # Common User Agent used for web requests
    _user_agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)"

    def __init__(self):
        """
        Initializes a default unauthenticated session.
        """
        self.client = None
        self.cookies = None
        self.logged_in = False

        # Wish there were better names for these
        self.android = HTTPSConnection('android.clients.google.com')
        self.jumper  = HTTPConnection('uploadsj.clients.google.com')


    def _get_cookies(self):
        """
        Gets cookies needed for web and media streaming access.
        Returns True if the necessary cookies are found, False otherwise.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        handler = build_opener(HTTPCookieProcessor(self.cookies))
        req = Request(self.PLAY_URL, None, {}) #header)
        resp_obj = handler.open(req)

        return  (
                    self.get_cookie('sjsaid') is not None and
                    self.get_cookie('xt') is not None
                )


    def get_cookie(self, name):
        """
        Finds the value of a cookie by name, returning None on failure.

        :param name: The name of the cookie to find.
        """
        for cookie in self.cookies:
            if cookie.name == name:
                return cookie.value

        return None


    def login(self, email, password):
        """
        Attempts to create an authenticated session using the email and
        password provided.
        Return True if the login was successful, False otherwise.
        Raises AlreadyLoggedIn if the session is already authenticated.

        :param email: The email address of the account to log in.
        :param password: The password of the account to log in.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        self.client = ClientLogin(email, password, 'sj')
        tokenauth = TokenAuth('sj', self.PLAY_URL, 'jumper')

        if self.client.get_auth_token() is None:
            return False

        tokenauth.authenticate(self.client)
        self.cookies = tokenauth.get_cookies()

        self.logged_in = self._get_cookies()

        return self.logged_in


    def logout(self):
        """
        Resets the session to an unauthenticated default state.
        """
        self.__init__()


    def open_web_url(self, url_builder, extra_args=None, data=None, useragent=None):
        """
        Opens an https url using the current session and returns the response.
        Code adapted from:
        http://code.google.com/p/gdatacopier/source/browse/tags/gdatacopier-1.0.2/gdatacopier.py

        :param url_builder: the url, or a function to receieve a dictionary of querystring arg/val pairs and return the url.
        :param extra_args: (optional) key/val querystring pairs.
        :param data: (optional) encoded POST data.
        :param useragent: (optional) The User Agent to use for the request.
        """
        # I couldn't find a case where we don't need to be logged in
        if not self.logged_in:
            raise NotLoggedIn

        args = {'xt': self.get_cookie("xt")}

        if extra_args:
            args = dict(args.items() + extra_args.items())

        if isinstance(url_builder, basestring):
            url = url_builder
        else:
            url = url_builder(args)

        opener = build_opener(HTTPCookieProcessor(self.cookies))

        if not useragent:
            useragent = self._user_agent

        opener.addheaders = [('User-agent', useragent)]

        if data:
            response = opener.open(url, data)
        else:
            response = opener.open(url)

        return response


    def post_protobuf(self, path, protobuf):
        """
        Returns the response from encoding and posting the given data.

        :param path: the name of the service url
        :param proto: data to be encoded with protobuff
        """
        if not self.logged_in:
            raise NotLoggedIn

        urlpath = '/upsj/' + path
        self.android.request('POST', urlpath, protobuf.SerializeToString(), {
            'Cookie':       'SID=%s' % self.client.get_sid_token(),
            'Content-Type': 'application/x-google-protobuf'
        })

        resp = self.android.getresponse()

        return resp.read()


    def post_jumper(self, url, encoded_data, headers=None):
        """
        Returns the response of a post to the MusicManager jumper service.
        """
        if not self.logged_in:
            raise NotLoggedIn

        if not headers:
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Cookie':       'SID=%s' % self.client.get_sid_token()
            }

        self.jumper.request('POST', url, encoded_data, headers)
        return self.jumper.getresponse()
Esempio n. 4
0
class PlaySession(object):
    """
    A Google Play Music session.

    It allows for authentication and the making of authenticated
    requests through the MusicManager API (protocol buffers), Web client requests,
    and the Skyjam client API.
    """

    # The URL for authenticating against Google Play Music
    PLAY_URL = 'https://play.google.com/music/listen?u=0&hl=en'

    # Common User Agent used for web requests
    _user_agent = (
        "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) "
        "Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)"
    )

    def __init__(self):
        """
        Initializes a default unauthenticated session.
        """
        self.client = None
        self.web_cookies = None
        self.logged_in = False

    def _get_cookies(self):
        """
        Gets cookies needed for web and media streaming access.
        Returns ``True`` if the necessary cookies are found, ``False`` otherwise.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        handler = build_opener(HTTPCookieProcessor(self.web_cookies))
        req = Request(self.PLAY_URL, None, {})  # header
        handler.open(req)  # TODO is this necessary?

        return (
            self.get_web_cookie('sjsaid') is not None and
            self.get_web_cookie('xt') is not None
        )

    def get_web_cookie(self, name):
        """
        Finds the value of a cookie by name, returning None on failure.

        :param name: The name of the cookie to find.
        """
        if self.web_cookies is None:
            return None

        for cookie in self.web_cookies:
            if cookie.name == name:
                return cookie.value

        return None

    def login(self, email, password):
        """
        Attempts to create an authenticated session using the email and
        password provided.
        Return ``True`` if the login was successful, ``False`` otherwise.
        Raises AlreadyLoggedIn if the session is already authenticated.

        :param email: The email address of the account to log in.
        :param password: The password of the account to log in.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        self.client = ClientLogin(email, password, 'sj')
        tokenauth = TokenAuth('sj', self.PLAY_URL, 'jumper')

        if self.client.get_auth_token() is None:
            return False

        tokenauth.authenticate(self.client)
        self.web_cookies = tokenauth.get_cookies()

        self.logged_in = self._get_cookies()

        return self.logged_in

    def logout(self):
        """
        Resets the session to an unauthenticated default state.
        """
        self.__init__()

    def send(self, request, auth, session_options):
        """Send a request from a Call.

        :param request: filled requests.Request.
        :param auth: result of Call.get_auth().
        :param session_options: dict of kwargs to pass to requests.Session.send.
        """

        if any(auth) and not self.logged_in:
            raise NotLoggedIn

        send_xt, send_clientlogin, send_sso = auth

        if request.cookies is None:
            request.cookies = {}

        #Attach auth.
        if send_xt:
            request.params['u'] = 0
            request.params['xt'] = self.get_web_cookie('xt')

        if send_clientlogin:
            request.cookies['SID'] = self.client.get_sid_token()

        if send_sso:
            #dict <- CookieJar
            web_cookies = {c.name: c.value for c in self.web_cookies}
            request.cookies.update(web_cookies)

        prepped = request.prepare()
        s = requests.Session()

        res = s.send(prepped, **session_options)
        return res
Esempio n. 5
0
class PlaySession(object):
    """
    A Google Play Music session.

    It allows for authentication and the making of authenticated
    requests through the MusicManager API (protocol buffers), Web client requests,
    and the Skyjam client API.
    """

    # The URL for authenticating against Google Play Music
    PLAY_URL = 'https://play.google.com/music/listen?u=0&hl=en'

    # Common User Agent used for web requests
    _user_agent = ("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.6) "
                   "Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)")

    def __init__(self):
        """
        Initializes a default unauthenticated session.
        """
        self.client = None
        self.web_cookies = None
        self.logged_in = False

    def _get_cookies(self):
        """
        Gets cookies needed for web and media streaming access.
        Returns ``True`` if the necessary cookies are found, ``False`` otherwise.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        handler = build_opener(HTTPCookieProcessor(self.web_cookies))
        req = Request(self.PLAY_URL, None, {})  # header
        handler.open(req)  # TODO is this necessary?

        return (self.get_web_cookie('sjsaid') is not None
                and self.get_web_cookie('xt') is not None)

    def get_web_cookie(self, name):
        """
        Finds the value of a cookie by name, returning None on failure.

        :param name: The name of the cookie to find.
        """
        if self.web_cookies is None:
            return None

        for cookie in self.web_cookies:
            if cookie.name == name:
                return cookie.value

        return None

    def login(self, email, password):
        """
        Attempts to create an authenticated session using the email and
        password provided.
        Return ``True`` if the login was successful, ``False`` otherwise.
        Raises AlreadyLoggedIn if the session is already authenticated.

        :param email: The email address of the account to log in.
        :param password: The password of the account to log in.
        """
        if self.logged_in:
            raise AlreadyLoggedIn

        self.client = ClientLogin(email, password, 'sj')
        tokenauth = TokenAuth('sj', self.PLAY_URL, 'jumper')

        if self.client.get_auth_token() is None:
            return False

        tokenauth.authenticate(self.client)
        self.web_cookies = tokenauth.get_cookies()

        if self._get_cookies():
            self.logged_in = True
        else:
            self.logged_in = False

        return self.logged_in

    def logout(self):
        """
        Resets the session to an unauthenticated default state.
        """
        self.__init__()

    def send(self, request, auth, session_options):
        """Send a request from a Call.

        :param request: filled requests.Request.
        :param auth: result of Call.get_auth().
        :param session_options: dict of kwargs to pass to requests.Session.send.
        """

        if any(auth) and not self.logged_in:
            raise NotLoggedIn

        send_xt, send_clientlogin, send_sso = auth

        if request.cookies is None:
            request.cookies = {}

        #Attach auth.
        if send_xt:
            request.params['u'] = 0
            request.params['xt'] = self.get_web_cookie('xt')

        if send_clientlogin:
            request.cookies['SID'] = self.client.get_sid_token()

        if send_sso:
            #TODO merge this without overwriting
            request.cookies = self.web_cookies

        prepped = request.prepare()
        s = requests.Session()

        res = s.send(prepped, **session_options)
        return res