def get(self): # this must be a client ie subclass of GDClient, since that's what # OAuth2TokenFromCredentials.authorize() expects, *not* a service ie # subclass of GDataService. blogger = client.BloggerClient() auth_token = gauth.OAuth2TokenFromCredentials(oauth.credentials) auth_token.authorize(blogger) # get the current user blogs = blogger.get_blogs() logging.debug('Got blogs: %r' % str(blogs)) owner_name = blogs.entry[0].author[0].name.text if blogs.entry else None hostnames = [] for entry in blogs.entry: for link in entry.link: if link.type == 'text/html': domain = util.domain_from_link(link.href) if domain: hostnames.append(domain) break # redirect so that refreshing the page doesn't try to regenerate the oauth # token, which won't work. self.redirect('/?' + urllib.urlencode( { 'blogger_owner_name': owner_name, 'blogger_hostnames': hostnames, }, True))
def get(self): # this must be a client ie subclass of GDClient, since that's what # OAuth2TokenFromCredentials.authorize() expects, *not* a service ie # subclass of GDataService. blogger = client.BloggerClient() auth_token = gauth.OAuth2TokenFromCredentials(oauth.credentials) auth_token.authorize(blogger) # get the current user blogs = blogger.get_blogs() logging.debug('Got blogs: %r' % str(blogs)) owner_name = blogs.entry[0].author[0].name.text if blogs.entry else None hostnames = [] for entry in blogs.entry: for link in entry.link: if link.type == 'text/html': domain = util.domain_from_link(link.href) if domain: hostnames.append(domain) break # redirect so that refreshing the page doesn't try to regenerate the oauth # token, which won't work. self.redirect('/?' + urllib.urlencode({ 'blogger_owner_name': owner_name, 'blogger_hostnames': hostnames, }, True))
def new(cls, handler, blog_id, blog_url): """Creates and saves a WordPressRest entity. Args: handler: the current webapp.RequestHandler blog_id: string blog_url: string Returns: WordPressRest """ properties = dict(handler.request.params) key_name = util.domain_from_link(blog_url) return WordPressRest.get_or_insert(key_name, blog_id=blog_id, **properties)
def get(self): # handle errors error = self.request.get('error') if error: error_description = urllib.unquote_plus( self.request.get('error_description', '')) if error == 'access_denied': logging.info('User declined: %s', error_description) self.finish(None, state=self.request.get('state')) return else: raise exc.HTTPBadRequest('Error: %s %s ' % (error, error_description)) # extract auth code and request access token auth_code = self.request.get('code') assert auth_code data = { 'code': auth_code, 'client_id': appengine_config.WORDPRESS_CLIENT_ID, 'client_secret': appengine_config.WORDPRESS_CLIENT_SECRET, # redirect_uri here must be the same in the oauth code request! # (the value here doesn't actually matter since it's requested server side.) 'redirect_uri': self.request.path_url, 'grant_type': 'authorization_code', } logging.debug('Fetching %s with %r', GET_ACCESS_TOKEN_URL, data) resp = urllib2.urlopen(GET_ACCESS_TOKEN_URL, data=urllib.urlencode(data), timeout=appengine_config.HTTP_TIMEOUT).read() logging.debug('Access token response: %s', resp) try: resp = json.loads(resp) blog_id = resp['blog_id'] blog_url = resp['blog_url'] blog_domain = util.domain_from_link(resp['blog_url']) access_token = resp['access_token'] except: logging.exception('Could not decode JSON') raise auth = WordPressAuth(id=blog_domain, blog_id=blog_id, blog_url=blog_url, access_token_str=access_token) auth.user_json = auth.urlopen(API_USER_URL).read() auth.put() self.finish(auth, state=self.request.get('state'))
def get(self): # handle errors error = self.request.get('error') if error: error_description = urllib.unquote_plus( self.request.get('error_description', '')) if error == 'access_denied': logging.info('User declined: %s', error_description) self.finish(None, state=self.request.get('state')) return else: raise exc.HTTPBadRequest('Error: %s %s ' % (error, error_description)) # extract auth code and request access token auth_code = util.get_required_param(self, 'code') data = { 'code': auth_code, 'client_id': appengine_config.WORDPRESS_CLIENT_ID, 'client_secret': appengine_config.WORDPRESS_CLIENT_SECRET, # redirect_uri here must be the same in the oauth code request! # (the value here doesn't actually matter since it's requested server side.) 'redirect_uri': self.request.path_url, 'grant_type': 'authorization_code', } resp = util.urlopen(GET_ACCESS_TOKEN_URL, data=urllib.urlencode(data)).read() logging.debug('Access token response: %s', resp) try: resp = json.loads(resp) blog_id = resp['blog_id'] blog_url = resp['blog_url'] blog_domain = util.domain_from_link(resp['blog_url']) access_token = resp['access_token'] except: logging.exception('Could not decode JSON') raise auth = WordPressAuth(id=blog_domain, blog_id=blog_id, blog_url=blog_url, access_token_str=access_token) auth.user_json = auth.urlopen(API_USER_URL).read() auth.put() self.finish(auth, state=self.request.get('state'))
def discover_salmon_endpoint(self): """Discovers and returns the Salmon endpoint URL for this salmon. It'd be nice to use an XRD/LRDD library here, but I haven't found much. github.com/jcarbaugh/python-xrd is only for generating, not reading. pydataportability.net looks powerful but also crazy heavyweight; it requires Zope and strongly recommends running inside virtualenv. No thanks. Returns: string URL or None """ url = json.loads(self.vars)["in_reply_to"] logging.debug("Discovering salmon endpoint for %r", url) body = util.urlfetch(url) # first look in the document itself endpoint = django_salmon.discover_salmon_endpoint(body) if endpoint: logging.debug("Found in original document: %r", endpoint) return endpoint # next, look in its feed, if any # # background on feed autodiscovery: # http://blog.whatwg.org/feed-autodiscovery parsed = feedparser.parse(body) for link in parsed.feed.get("links", []): rels = link.get("rel").split() href = link.get("href") if href and ("feed" in rels or "alternate" in rels): endpoint = django_salmon.discover_salmon_endpoint(util.urlfetch(href)) if endpoint: logging.debug("Found in feed: %r", endpoint) return endpoint # next, look in /.well-known/host-meta host_meta_url = "http://%s/.well-known/host-meta" % util.domain_from_link(url) endpoint = django_salmon.discover_salmon_endpoint(util.urlfetch(host_meta_url)) if endpoint: logging.debug("Found in host-meta: %r", endpoint) return endpoint logging.debug("No salmon endpoint found!") return None
def get(self): # lookup the request token token_key = self.request.get('oauth_token') token = TumblrOAuthRequestToken.get_by_key_name(token_key) if token is None: raise exc.HTTPBadRequest('Invalid oauth_token: %s' % token_key) # generate and store the final token tp = tumblpy.Tumblpy(app_key=TUMBLR_APP_KEY, app_secret=TUMBLR_APP_SECRET, oauth_token=token_key, oauth_token_secret=token.secret) auth_token = tp.get_authorized_tokens( self.request.params['oauth_verifier']) final_token = auth_token['oauth_token'] final_secret = auth_token['oauth_token_secret'] TumblrOAuthFinalToken.new(final_token, final_secret) # get the user's blogs # http://www.tumblr.com/docs/en/api/v2#user-methods tp = tumblpy.Tumblpy(app_key=TUMBLR_APP_KEY, app_secret=TUMBLR_APP_SECRET, oauth_token=final_token, oauth_token_secret=final_secret) resp = tp.post('user/info') logging.debug(resp) user = resp['user'] hostnames = [util.domain_from_link(b['url']) for b in user['blogs']] hostnames = util.trim_nulls(hostnames) # titles = [b[title] for b in user['blogs']] # redirect so that refreshing the page doesn't try to regenerate the oauth # token, which won't work. self.redirect('/?' + urllib.urlencode( { 'tumblr_username': user['name'], 'tumblr_hostnames': hostnames, # 'tumblr_titles': titles, 'oauth_token': auth_token['oauth_token'], }, True))
def get(self): # lookup the request token token_key = self.request.get('oauth_token') token = TumblrOAuthRequestToken.get_by_key_name(token_key) if token is None: raise exc.HTTPBadRequest('Invalid oauth_token: %s' % token_key) # generate and store the final token tp = tumblpy.Tumblpy(app_key=TUMBLR_APP_KEY, app_secret=TUMBLR_APP_SECRET, oauth_token=token_key, oauth_token_secret=token.secret) auth_token = tp.get_authorized_tokens(self.request.params['oauth_verifier']) final_token = auth_token['oauth_token'] final_secret = auth_token['oauth_token_secret'] TumblrOAuthFinalToken.new(final_token, final_secret) # get the user's blogs # http://www.tumblr.com/docs/en/api/v2#user-methods tp = tumblpy.Tumblpy(app_key=TUMBLR_APP_KEY, app_secret=TUMBLR_APP_SECRET, oauth_token=final_token, oauth_token_secret=final_secret) resp = tp.post('user/info') logging.debug(resp) user = resp['user'] hostnames = [util.domain_from_link(b['url']) for b in user['blogs']] hostnames = util.trim_nulls(hostnames) # titles = [b[title] for b in user['blogs']] # redirect so that refreshing the page doesn't try to regenerate the oauth # token, which won't work. self.redirect('/?' + urllib.urlencode({ 'tumblr_username': user['name'], 'tumblr_hostnames': hostnames, # 'tumblr_titles': titles, 'oauth_token': auth_token['oauth_token'], }, True))
def post(self): domain = util.domain_from_link(self.request.get('domain')) TwitterSearch.create_new(self, domain=domain).save() self.redirect('/')
def display_name(self): return util.domain_from_link(self.xmlrpc_url())
class Handler(cls): @oauth_decorator.oauth_required def post(self): return self.get() @oauth_decorator.oauth_required def get(self): state = self.request.get('state') blogger = BloggerV2Auth.api_from_creds(oauth_decorator.credentials) try: blogs = blogger.get_blogs() except BaseException, e: # this api call often returns 401 Unauthorized for users who aren't # signed up for blogger and/or don't have any blogs. util.interpret_http_exception(e) # we can't currently intercept declines for Google or Blogger, so the # only time we return a None auth entity right now is on error. self.finish(None, state=state) return for id in ([a.uri.text for a in blogs.author if a.uri] + [l.href for l in blogs.link if l]): if not id: continue match = self.AUTHOR_URI_RE.match(id) if match: id = match.group(1) else: logging.warning("Couldn't parse %s , using entire value as id", id) break blog_ids = [] blog_titles = [] blog_hostnames = [] for blog in blogs.entry: blog_ids.append(blog.get_blog_id() or blog.get_blog_name()) blog_titles.append(blog.title.text) blog_hostnames.append(util.domain_from_link(blog.GetHtmlLink().href) if blog.GetHtmlLink() else None) creds_json = oauth_decorator.credentials.to_json() # extract profile picture URL picture_url = None for author in blogs.author: for child in author.children: if child.tag.split(':')[-1] == 'image': picture_url = child.get_attributes('src')[0].value break auth = BloggerV2Auth(id=id, name=author.name.text, picture_url=picture_url, creds_json=creds_json, user_atom=str(author), blogs_atom=str(blogs), blog_ids=blog_ids, blog_titles=blog_titles, blog_hostnames=blog_hostnames) auth.put() self.finish(auth, state=state)