def shorten_url(matchobj): url = matchobj.group() result = urlfetch.fetch( "http://api.bitly.com/v3/shorten?login="******"&apiKey=" + BITLY_APIKEY + "&format=txt&domain=j.mp&longUrl=" + escape(url) ) if result.status_code != 200: logging.error("Cannot shorten URL. (%d %s)\n%s", result.status_code, result.content, url) raise Exception return result.content.rstrip()
def post(self): account = self.get_account() if not account or not account.twitter_user: logging.debug("Not Logged in.") self.error(400) return if account.session_token != self.request.headers.get("X-Imakoko-Token"): logging.warning("(%d) session_token mismatch.", account.key().id()) self.error(500) return logging.debug("(%d) Twit: %s", account.key().id(), account.twitter_user) data = self.request.body try: parsed = cgi.parse_qs(data) parsed["status"][0] = shorten_url_pattern.sub(shorten_url, parsed["status"][0], 1) data = "&".join(escape(k) + "=" + escape(parsed[k][0]) for k in parsed) except: pass headers = oauth_client.build_oauth_header( "POST", TWITTER_POST_URL, data, account.twitter_token, account.twitter_secret ) result = urlfetch.fetch(TWITTER_POST_URL, data, urlfetch.POST, headers) status_code = result.status_code if status_code == 401: logging.info('(%d) Leave: twitter="%s"', account.key().id(), account.twitter_user) account.twitter_user = None account.twitter_token = None account.twitter_secret = None account.put() self.error(400) return self.response.status_int = status_code