]> jfr.im git - z_archive/twitter.git/blobdiff - twitter/oauth.py
Add a simple prompt thing to twitter cmdline.
[z_archive/twitter.git] / twitter / oauth.py
index bf81f42807e4d28eff667d5112083a58351e3d72..96cc4e65a280f5aab9c724340a38b5f916dfd258 100644 (file)
@@ -6,11 +6,35 @@ from time import time
 import urllib
 import hashlib
 import hmac
+import base64
+
+def write_token_file(filename, oauth_token, oauth_token_secret):
+    """
+    Write a token file to hold the oauth token and oauth token secret.
+    """
+    oauth_file = open(filename, 'w')
+    print >> oauth_file, oauth_token
+    print >> oauth_file, oauth_token_secret
+    oauth_file.close()
+
+def read_token_file(filename):
+    """
+    Read a token file and return the oauth token and oauth token secret.
+    """
+    f = open(filename)
+    return f.readline().strip(), f.readline().strip()
 
 
-# An OAuth implementation with various helpers...
 class OAuth(Auth):
+    """
+    An OAuth authenticator.
+    """
     def __init__(self, token, token_secret, consumer_key, consumer_secret):
+        """
+        Create the authenticator. If you are in the initial stages of
+        the OAuth dance and don't yet have a token or token_secret,
+        pass empty strings for these params.
+        """
         self.token = token
         self.token_secret = token_secret
         self.consumer_key = consumer_key
@@ -19,7 +43,9 @@ class OAuth(Auth):
     def encode_params(self, base_url, method, params):
         params = params.copy()
 
-        params['oauth_token'] = self.token
+        if self.token:
+            params['oauth_token'] = self.token
+
         params['oauth_consumer_key'] = self.consumer_key
         params['oauth_signature_method'] = 'HMAC-SHA1'
         params['oauth_version'] = '1.0'
@@ -32,9 +58,10 @@ class OAuth(Auth):
 
         message = '&'.join(
             urllib.quote(i, '') for i in [method.upper(), base_url, enc_params])
-    
-        signature = hmac.new(
-            key, message, hashlib.sha1).digest().encode('base64')[:-1]
+
+        signature = (base64.b64encode(hmac.new(
+                    key.encode('ascii'), message.encode('ascii'), hashlib.sha1)
+                                      .digest()))
         return enc_params + "&" + "oauth_signature=" + urllib.quote(signature, '')
 
     def generate_headers(self):
@@ -48,7 +75,7 @@ def urlencode_noplus(query):
     if hasattr(query,"items"):
         # mapping objects
         query = query.items()
-    
+
     encoded_bits = []
     for n, v in query:
         # and do unicode here while we are at it...