changeset 12:63ea847bfa75

added more stuff
author Atul Varma <avarma@mozilla.com>
date Sat, 12 Jun 2010 22:37:20 -0700
parents 727b82d4b596
children 775e00932285
files .hgignore file_storage.py oauth_experiment.py static-files/index.html static-files/main.js static-files/twitter.ico static_file_serving.py twitter_client.py
diffstat 8 files changed, 167 insertions(+), 28 deletions(-) [+]
line wrap: on
line diff
--- a/.hgignore	Sat Jun 12 20:27:48 2010 -0700
+++ b/.hgignore	Sat Jun 12 22:37:20 2010 -0700
@@ -1,3 +1,4 @@
 syntax: glob
 *.pyc
 config.json
+storage
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/file_storage.py	Sat Jun 12 22:37:20 2010 -0700
@@ -0,0 +1,60 @@
+import re
+import os
+import json
+
+class FileStorage(object):
+    """
+    >>> fs = FileStorage(os.getcwd())
+    >>> 'blah' in fs
+    False
+    >>> os.path.exists('blah.json')
+    False
+    >>> fs['blah'] = {'foo': 1}
+    >>> 'blah' in fs
+    True
+    >>> os.path.exists('blah.json')
+    True
+    >>> open('blah.json').read()
+    '{"foo": 1}'
+    >>> fs['blah']
+    {u'foo': 1}
+    >>> del fs['blah']
+    >>> 'blah' in fs
+    False
+    >>> '9-p' in fs
+    False
+    >>> os.path.exists('blah.json')
+    False
+    """
+
+    keypattern = re.compile('^[A-Za-z0-9\-]+$')
+
+    def __init__(self, dirname):
+        self.dirname = dirname
+
+    def __filename(self, name):
+        if not self.keypattern.match(name):
+            raise ValueError('invalid key name: %s' % name)
+        return os.path.join(self.dirname, "%s.json" % name)
+
+    def __contains__(self, name):
+        return os.path.exists(self.__filename(name))
+
+    def __delitem__(self, name):
+        if not name in self:
+            raise KeyError(name)
+        os.remove(self.__filename(name))
+
+    def __getitem__(self, name):
+        if not name in self:
+            raise KeyError(name)
+        return json.loads(open(self.__filename(name)).read())
+
+    def __setitem__(self, name, value):
+        open(self.__filename(name), 'w').write(json.dumps(value))
+
+if __name__ == '__main__':
+    import doctest
+
+    doctest.testmod()
+    print "done running tests"
--- a/oauth_experiment.py	Sat Jun 12 20:27:48 2010 -0700
+++ b/oauth_experiment.py	Sat Jun 12 22:37:20 2010 -0700
@@ -1,40 +1,66 @@
 import os
 import json
 import oauth2 as oauth
+import wsgiref.util
+
 import twitter_client
+import file_storage
+from static_file_serving import StaticFileApp
+
+class MyTwitterApp(object):
+    def __init__(self, default, access_tokens):
+        self.default = default
+        self.twitter = None
+        self.access_tokens = access_tokens
+
+    def onsuccess(self, environ, start_response):
+        access_token = environ['oauth.access_token']
+        tokid = access_token['oauth_token']
+        if tokid not in self.access_tokens:
+            self.access_tokens[tokid] = access_token
+        start_response('200 OK', [('Content-Type', 'text/html')])
+        js = 'window.opener.onLogin(window, "%s");' % tokid
+        return ['<script>%s</script>' % js]
+
+    def __call__(self, environ, start_response):
+        path = environ['PATH_INFO']
+
+        if path.startswith('/twitter/') and self.twitter is not None:
+            wsgiref.util.shift_path_info(environ)
+            return self.twitter(environ, start_response)
+
+        return self.default(environ, start_response)
+
+def ensure_dirs(*paths):
+    for path in paths:
+        if not os.path.exists(path):
+            os.mkdir(path)
+
+mydir = os.getcwd()
+staticfilesdir = os.path.join(mydir, 'static-files')
+storagedir = os.path.join(mydir, 'storage')
+reqdir = os.path.join(storagedir, 'request-tokens')
+accdir = os.path.join(storagedir, 'access-tokens')
+
+ensure_dirs(storagedir, reqdir, accdir)
+
+static_files = StaticFileApp(staticfilesdir)
+
+app = MyTwitterApp(
+    default=static_files,
+    access_tokens=file_storage.FileStorage(accdir)
+    )
 
 config = json.loads(open("config.json").read())
 
 consumer = oauth.Consumer(config['consumer_key'],
                           config['consumer_secret'])
 
-class Storage(object):
-    def __filename(self, name):
-        return "__REQUEST_TOKEN_%s.json" % name
-
-    def __contains__(self, name):
-        return os.path.exists(self.__filename(name))
-
-    def __delitem__(self, name):
-        if not name in self:
-            raise KeyError(name)
-        os.remove(self.__filename(name))
-
-    def __getitem__(self, name):
-        if not name in self:
-            raise KeyError(name)
-        return json.loads(open(self.__filename(name)).read())
-
-    def __setitem__(self, name, value):
-        open(self.__filename(name), 'w').write(json.dumps(value))
-
-def success_app(environ, start_response):
-    start_response('200 OK', [('Content-Type', 'text/plain')])
-    return ['woot %s' % repr(environ['oauth.access_token'])]
-
-app = twitter_client.TwitterOauthClientApp(
+twitter = twitter_client.TwitterOauthClientApp(
     consumer=consumer,
     oauth=oauth,
-    request_tokens=Storage(),
-    onsuccess=success_app
+    request_tokens=file_storage.FileStorage(reqdir),
+    onsuccess=app.onsuccess
     )
+
+app.twitter = twitter
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/static-files/index.html	Sat Jun 12 22:37:20 2010 -0700
@@ -0,0 +1,10 @@
+<html>
+<head>
+  <title>My Twittery App</title>
+</head>
+<body>
+<img src="twitter.ico" style="cursor: pointer;"
+ onclick="openLogin();">
+<script src="main.js"></script>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/static-files/main.js	Sat Jun 12 22:37:20 2010 -0700
@@ -0,0 +1,8 @@
+function onLogin(popup, token) {
+  popup.close();
+  console.log("O YEA ", token);
+}
+
+function openLogin() {
+  window.open('twitter/', 'login', 'width=640,height=480');
+}
Binary file static-files/twitter.ico has changed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/static_file_serving.py	Sat Jun 12 22:37:20 2010 -0700
@@ -0,0 +1,31 @@
+import mimetypes
+import os
+import wsgiref.util
+
+class StaticFileApp(object):
+    def __init__(self, root_dir):
+        self.root_dir = root_dir
+
+    def __call__(self, environ, start_response):
+        path = environ['PATH_INFO']
+
+        def error_404():
+            start_response('404 Not Found',
+                           [('Content-Type', 'text/plain')])
+            return ['Not Found: %s' % path]
+
+        if path == '/':
+            path = '/index.html'
+
+        if path.startswith('/') and environ['REQUEST_METHOD'] == 'GET':
+            filename = path.split('/')[1]
+            if filename in os.listdir(self.root_dir):
+                mimetype, enc = mimetypes.guess_type(filename)
+                f = open(os.path.join(self.root_dir, filename))
+                start_response('200 OK',
+                               [('Content-Type', mimetype)])
+                return wsgiref.util.FileWrapper(f)
+            else:
+                return error_404()
+
+        return error_404()
--- a/twitter_client.py	Sat Jun 12 20:27:48 2010 -0700
+++ b/twitter_client.py	Sat Jun 12 22:37:20 2010 -0700
@@ -24,7 +24,10 @@
             # having the user authorize an access token and to sign the request to obtain 
             # said access token.
 
-            oauth_callback = '%scallback' % application_uri(environ)
+            appuri = application_uri(environ)
+            if not appuri.endswith('/'):
+                appuri += '/'
+            oauth_callback = '%scallback' % appuri
 
             url = '%s?%s' % (
                 self.request_token_url,