ΔaZy<ddlmZ eZgdZ ddlmZddl Z ddl Z ddl Z ddl m Z ddl Z ddlmZddlZ ddlmZ ddlmZddlZdd lmZmZdd lmZeeureZneZdd l m!Z!dd l"m#Z$m%Z%m&Z&m'Z'dd l(m)Z)dZ*dZ+dZ,dZ-dZ.e/e0e1fZ2dZ3dZ4Gdde&Z5Gdde$Z#Gdde$Z6Gdde7Z8Gdde8Z9Gdd e8Z:Gd!d"e8Z;Gd#d$e7Z<Gd%d&e<Z=Gd'd(e=Z>Gd)d*e?Z@Gd+d,e@ZAGd-d.e@ZBGd/d0eBZCGd1d2eBZDGd3d4eDZEGd5d6e@ZFGd7d8e@ZGGd9d:e@ZHGd;d ct}|j||j}t|tr|j d}|S)zeTurn this object into a string. This should probably be moved into OAuthAuthorizer. utf-8)r savegetvalue isinstance unicode_typeencode)selfsio serializeds r serializezCredentials.serializesA j #\\^ j, /#**73Jrc|}t|ts|jd}|jt ||S)z}Create a `Credentials` object from a serialized string. This should probably be moved into OAuthAuthorizer. r8)r;r<decodeloadr )clsvalue credentialss r from_stringzCredentials.from_strings; e %.LL)E%)rc|jJd|jJdtj|}t |jj dd}|t z}d|i}||jk(rd|d<t|||\}}t|tr|jd }||jk(r8tj|}|||d <tj||_|Stj#||_|t$d |j j }|||j _|d |zz }|S) aRequest an OAuth token to Launchpad. Also store the token in self._request_token. This method must not be called on an object with no consumer specified or if an access token has already been obtained. :param context: The context of this token, that is, its scope of validity within Launchpad. :param web_root: The URL of the website on which the token should be requested. :token_format: How the token should be presented. URI_TOKEN_FORMAT means just return the URL to the page that authorizes the token. DICT_TOKEN_FORMAT means return a dictionary describing the token and the site's authentication policy. :return: If token_format is URI_TOKEN_FORMAT, the URL for the user to authorize the `AccessToken` provided by Launchpad. If token_format is DICT_TOKEN_FORMAT, a dict of information about the new access token. zConsumer not specified.zAccess token already obtained. PLAINTEXT&)oauth_consumer_keyoauth_signature_methodoauth_signatureRefererzapplication/jsonAcceptr8 lp.context ?oauth_token=z&lp.context=%s)consumer access_tokenrlookup_web_rootr5keyrequest_token_pageDICT_TOKEN_FORMATr2r;bytesrCjsonloadsr from_params_request_tokenrHauthorize_token_pagecontext) r>r_web_root token_formatr.r-r&r0r1s r get_request_tokenzCredentials.get_request_tokensW8}}(C*CC(  (J*JJ(''1#}}00#.  ++h' 411 1 2GH &sGV<' gu %nnW-G 411 1ZZ(F"'.|$"-"9"9&"AD M"-"9"9'"BD $##''C ".5##+''11Jrc^|jJdtj|}t|jj d|jj d|jj z}|tz}d|i}t|||\}}tj||_ y)adExchange the previously obtained request token for an access token. This method must not be called unless get_request_token() has been called and completed successfully. The access token will be stored as self.access_token. :param web_root: The base URL of the website that granted the request token. Nz5get_request_token() doesn't seem to have been called.rJz&%s)rLrM oauth_tokenrNrO) r]rrUr5rSrVsecretaccess_token_pager2rrHrT)r>r`r.r-r&r0r1s r 'exchange_request_token_for_access_tokenz3Credentials.exchange_request_token_for_access_tokens    + C B C +''1#}}00#.++//!D$7$7$>$>>   **h'&sGV<''33G<r)__name__ __module__ __qualname____doc__r]URI_TOKEN_FORMATrXITEM_SEPARATORNEWLINErA classmethodrHrSTAGING_WEB_ROOTrbrgrrr r r rsdNNG   &&% ;|,,=rr c0eZdZdZedZedZy)rzAn OAuth access token.cL|d}|d}|jd}||||S)z:Create and return a new `AccessToken` from the given dict.rdoauth_token_secretrQ)r)rEr.rVrer_s r r\zAccessToken.from_paramss6]#,-**\*3((rcHt|ts|jd}t|d}|d}t |dk(sJd|d}|d}t |dk(sJd |d}|j d }|t |dk(sJd |d}||||S) z __class__s r r|zAnonymousAccessToken.__init__s "D22r:r)rhrirjrkr| __classcell__r}s@r rrs ;;rrc0eZdZdZddZdZdZdZdZy) rzStore OAuth credentials locally. This is a generic superclass. To implement a specific way of storing credentials locally you'll need to subclass this class, and implement `do_save` and `do_load`. Nc||_y)aConstructor. :param credential_save_failed: A callback to be invoked if the save to local storage fails. You should never invoke this callback yourself! Instead, you should raise an exception from do_save(). N)credential_save_failed)r>rs r r|zCredentialStore.__init__&s '=#rc |j|||S#t$rt$r)}|j||jYd}~|Sd}~wwxYw)zSave the credentials and invoke the callback on failure. Do not override this method when subclassing. Override do_save() instead. N)do_saveEXPLOSIVE_ERRORS Exceptionr)r>rGunique_consumer_ides r r9zCredentialStore.save0sa  * LL&8 9     ***2  ' ' ) )  *sAA  Act)zStore newly-authorized credentials locally for later use. :param credentials: A Credentials object to save. :param unique_consumer_id: A string uniquely identifying an OAuth consumer on a Launchpad instance. NotImplementedError)r>rGrs r rzCredentialStore.do_save@s "##rc$|j|S)a0Retrieve credentials from a local store. This method is the inverse of `save`. There's no special behavior in this method--it just calls `do_load`. There _is_ special behavior in `save`, and this way, developers can remember to implement `do_save` and `do_load`, not `do_save` and `load`. :param unique_key: A string uniquely identifying an OAuth consumer on a Launchpad instance. :return: A `Credentials` object if one is found in the local store, and None otherise. )do_loadr> unique_keys r rDzCredentialStore.loadIs ||J''rct)a@Retrieve credentials from a local store. This method is the inverse of `do_save`. :param unique_key: A string uniquely identifying an OAuth consumer on a Launchpad instance. :return: A `Credentials` object if one is found in the local store, and None otherise. rrs r rzCredentialStore.do_load[s "##rN) rhrirjrkr|r9rrDrrrr rrs = $($ $rrcDeZdZdZdZdfd ZedZdZdZ xZ S)KeyringCredentialStorezStore credentials in the GNOME keyring or KDE wallet. This is a good solution for desktop applications and interactive scripts. It doesn't work for non-interactive scripts, or for integrating third-party websites into Launchpad. sc`tt| |d|_|rt ||_yyr)r{rr| _fallbackMemoryCredentialStore)r>rfallbackr}s r r|zKeyringCredentialStore.__init__ss0 $d45KL 23IJDN rcvdtvrddladtvr ddlmayy#t$r t aYywxYw)aGEnsure the keyring module is imported (postponing side effects). The keyring module initializes the environment-dependent backend at import time (nasty). We want to avoid that initialization because it may do things like prompt the user to unlock their password store (e.g., KWallet). keyringrNNoKeyringError)r)globalsrkeyring.errorsr ImportError RuntimeErrorrrr _ensure_keyring_importedz/KeyringCredentialStore._ensure_keyring_importedys> GI %  79 , .9 - .!- .s &88cx|j|j}|jt|z} tj d||j dy#t$rO}ttk(rdt|vr|jr|jj||nYd}~yd}~wwxYw)z2Store newly-authorized credentials in the keyring. launchpadlibr8$No recommended backend was availableN) rrA B64MARKERrr set_passwordrCrrstrrr9)r>rGrr@rs r rzKeyringCredentialStore.do_saves %%' **, ^^i &;;     J,=,=g,F  ,.:#a&H~~##K<= s&A!! B9*AB44B9c0|j tjd|}|vt|tr|jd}|j|jr" t|t|jd} t j#|}|Sy#t$rM}ttk(rdt |vr|j r |j j|cYd}~Sd}~wwxYw#t$rYywxYw#t$$rYywxYw)z&Retrieve credentials from the keyring.rrNutf8)rr get_passwordrrrrrDr;r<r= startswithrrrv TypeErrorr rHr)r>rcredential_stringrrGs r rzKeyringCredentialStore.do_loads %%'  ' 4 4 !   (+\:$5$<$rrr}s r r|z'UnencryptedFileCredentialStore.__init__s ,d< " ! rc:|j|jy)zSave the credentials to disk.N) save_to_pathrr>rGrs r rz&UnencryptedFileCredentialStore.do_saves  /rctjj|jrRtj|jtj dk(st j|jSy)zLoad the credentials from disk.rN)rpathexistsrstatST_SIZEr load_from_pathrs r rz&UnencryptedFileCredentialStore.do_loadsN GGNN4== )GGDMM*4<<8A=--dmm< <rrrhrirjrkr|rrr~rs@r rrs ! 0rrc0eZdZdZdfd ZdZdZxZS)rzCredentialStore that stores keys only in memory. This can be used to provide a CredentialStore instance without actually saving any key to persistent storage. c:tt| |i|_yr)r{rr| _credentials)r>rr}s r r|zMemoryCredentialStore.__init__s #T34JKrc"||j|<y)z!Store the credentials in our dictN)rrs r rzMemoryCredentialStore.do_saves(3*%rc8|jj|S)z&Retrieve the credentials from our dict)rrrs r rzMemoryCredentialStore.do_loads  $$Z00rrrrs@r rrs 41rrcJeZdZdZdZ d dZedZdZdZ dZ d Z y) ra/The superclass of all request token authorizers. This base class does not implement request token authorization, since that varies depending on how you want the end-user to authorize a request token. You'll need to subclass this class and implement `make_end_user_authorize_token`. UNAUTHORIZEDNc$tj||_tj||_| | t d||t d|d|d|dg}t |}n t|}|}||_||_ |xsg|_ y)aDBase class initialization. :param service_root: The root of the Launchpad instance being used. :param application_name: The name of the application that wants to use launchpadlib. This is used in conjunction with a desktop-wide integration. If you specify this argument, your values for consumer_name and allow_access_levels are ignored. :param consumer_name: The OAuth consumer name, for an application that wants its own point of integration into Launchpad. In almost all cases, you want to specify application_name instead and do a desktop-wide integration. The exception is when you're integrating a third-party website into Launchpad. :param allow_access_levels: A list of the Launchpad access levels to present to the user. ('READ_PUBLIC' and so on.) Your value for this argument will be ignored during a desktop-wide integration. :type allow_access_levels: A list of strings. Nz:You must provide either application_name or consumer_name.zOYou must provide only one of application_name and consumer_name. (You provided z and z.)DESKTOP_INTEGRATION) rlookup_service_root service_rootweb_root_for_service_rootr` ValueErrorrr rSapplication_nameallow_access_levels)r>rr consumer_namerrSs r r|z(RequestTokenAuthorizationEngine.__init__ s@!44\B66|D  # (=L   'M,E$]4   $9"9 )*:;H .H,   0#6#<" rcN|jjdz|jzS)z7Return a string identifying this consumer on this host.@)rSrVr)r>s r rz2RequestTokenAuthorizationEngine.unique_consumer_idIs$}}  3&):):::rctd|}d}t|jdkDr!|||j|jzz }t |j |S)zReturn the authorization URL for a request token. This is the URL the end-user must visit to authorize the token. How exactly does this happen? That depends on the subclass implementation. rRz&allow_permission=r)r^rvrjoinrr`)r> request_tokenpageallow_permissions r authorization_urlz1RequestTokenAuthorizationEngine.authorization_urlNsc';MJ/ t'' (1 , $'7'<'<((( Dt}}d++rc|j|}|j|||jy|j||j|S)adAuthorize a token and associate it with the given credentials. If the credential store runs into a problem storing the credential locally, the `credential_save_failed` callback will be invoked. The callback will not be invoked if there's a problem authorizing the credentials. :param credentials: A `Credentials` object. If the end-user authorizes these credentials, this object will have its .access_token property set. :param credential_store: A `CredentialStore` object. If the end-user authorizes the credentials, they will be persisted locally using this object. :return: If the credentials are successfully authorized, the return value is the `Credentials` object originally passed in. Otherwise the return value is None. N)rbmake_end_user_authorize_tokenrTr9r)r>rGcredential_storerequest_token_strings r __call__z(RequestTokenAuthorizationEngine.__call__]sQ( $55kB **;8LM  # # +k4+B+BCrcb|j|jtj}|dS)z\Get a new request token from the server. :param return: The request token. )r`rard)rbr`r rX)r>rGauthorization_jsons r rbz1RequestTokenAuthorizationEngine.get_request_token{s6 )::]]1N1N; "-00rct)a5Authorize the given request token using the given credentials. Your subclass must implement this method: it has no default implementation. Because an access token may expire or be revoked in the middle of a session, this method may be called at arbitrary points in a launchpadlib session, or even multiple times during a single session (with a different request token each time). In most cases, however, this method will be called at the beginning of a launchpadlib session, or not at all. r)r>rGrs r rz=RequestTokenAuthorizationEngine.make_end_user_authorize_tokens "##rNNN) rhrirjrkUNAUTHORIZED_ACCESS_LEVELr|propertyrrrrbrrrr rrsH!/  >=@;; ,<1$rrc6eZdZdZdZdZdZdZdZdZ dZ y ) AuthorizeRequestTokenWithURLzAuthorize using a URL. This authorizer simply shows the URL for the user to open for authorization, and waits until the server responds. zPlease open this authorization page: (%s) in your browser. Use your browser to authorize this program to access Launchpad on your behalf.z.Press Enter after authorizing in your browser.ct|y)zDisplay a message. By default, prints the message to standard output. The message does not require any user interaction--it's solely informative. N)print)r>messages r outputz#AuthorizeRequestTokenWithURL.outputs  grc@|j|j|zy)Notify the end-user of the URL.N)rWAITING_FOR_USER)r>rs r !notify_end_user_authorization_urlz>AuthorizeRequestTokenWithURL.notify_end_user_authorization_urls D)),==>rc\ |j|j|jduS#t$rw}|jjdk(rt |j |jjdk7rtdt|t|j d}~wwxYw)z Check if the end-user authorizediiz#Unexpected response from Launchpad:N) rgr`rr0r,EndUserDeclinedAuthorizationr1rEndUserNoAuthorizationrT)r>rGrs r check_end_user_authorizationz9AuthorizeRequestTokenWithURL.check_end_user_authorizations 8  ? ? N''t33 8zz  C'3199==::$$+?@!H,QYY77 8s+ B+A2B&&B+c|j|jtj|j |y)"Wait for the end-user to authorizeN)rWAITING_FOR_LAUNCHPADr readliner)r>rGs r wait_for_end_user_authorizationzrGrrs r rz:AuthorizeRequestTokenWithURL.make_end_user_authorize_tokens0 22=A ../@A ,,[9rN) rhrirjrkrrrrrrrrrr rrs3 ; M?4$7 :rrcNeZdZdZdZdZdZdZdZ d fd Z fdZ d Z xZ S) raSAuthorize using a URL that pops-up automatically in a browser. This authorizer simply opens up the end-user's web browser to a Launchpad URL and lets the end-user authorize the request token themselves. This is the same as its superclass, except this class also performs the browser automatic opening of the URL. zThe authorization page: (%s) should be opening in your browser. Use your browser to authorize this program to access Launchpad on your behalf.z/Press Enter to continue or wait (%d) seconds...)z www-browserlinkslinks2lynxelinksz elinks-litenetrikw3mz5Waiting to hear from Launchpad about your decision...c2tt| ||d|y)aoConstructor. :param service_root: See `RequestTokenAuthorizationEngine`. :param application_name: See `RequestTokenAuthorizationEngine`. :param consumer_name: The value of this argument is ignored. If we have the capability to open the end-user's web browser, we must be running on the end-user's computer, so we should do a full desktop integration. :param credential_save_failed: See `RequestTokenAuthorizationEngine`. :param allow_access_levels: The value of this argument is ignored, for the same reason as consumer_name. N)r{rr|)r>rrrrrr}s r r|z)AuthorizeRequestTokenWithBrowser.__init__s . .> *D2H rctt| | tj}t |dd}||j v}|r_|j|j|jzttggg|j\}}}|rtj|tj|yy#tj$rd}d}YwxYw)rbasenameNF)r{rr webbrowserrgetattrTERMINAL_BROWSERSErrorrTIMEOUT_MESSAGETIMEOUTr r ropen)r>r browser_objbrowserconsole_browserrlist_r}s r rzBAuthorizeRequestTokenWithBrowser.notify_end_user_authorization_url s ,d ,,= > $$..*Kk:trG start_times r rz@AuthorizeRequestTokenWithBrowser.wait_for_end_user_authorization&s D../YY[ &&. JJ- . 44[AByy{j+DDD014MM&&. *  sB(( B43B4r) rhrirjrkrrrrrr|rrr~rs@r rrsL ; HOG  @#  6/2rrc eZdZy)TokenAuthorizationExceptionNrhrirjrrr rr7rrc eZdZy)RequestTokenAlreadyAuthorizedNrrrr rr;rrrceZdZdZy)EndUserAuthorizationFailedz?Superclass exception for all failures of end-user authorizationNrhrirjrkrrr rr?sIrrceZdZdZy)rzEnd-user declined authorizationNrrrr rrEs)rrceZdZdZy)rz*End-user did not perform any authorizationNrrrr rrKs4rrceZdZdZy)rzr8s"&:  "   !&!$ ,C<LL/%#)#!2J? P =/=D),)@;<;H$fH$Vc_cL_61O1(U$fU$p8:#B8:vc'CcL )  $?  !<  #=  7  !7  -  -  4  $? C!  !!  !s3E(E:F ( E76E7: F F  FF