Commits

Mike Griffith committed 6afbb6b

lots of cleanup to code and messages. no logic changes.

  • Participants
  • Parent commits c56428a

Comments (0)

Files changed (1)

File zine/plugins/twitter/__init__.py

 from zine.utils.http import redirect_to
 from zine.utils import forms
 try:
-    #from twitter import Api as twitter_api
     import tweepy as twitter_api
 except ImportError:
     twitter_api = None
 
 
+# Directories
 SHARED = join(dirname(__file__), 'shared')
 TEMPLATES = join(dirname(__file__), 'templates')
 
-
+# Settings
 DEFAULT_MESSAGE = 'Blogged: {title} {url} #zine'
-
-
 URL_SHORTENERS = (
         'bit.ly',
         'tinyurl',
 
 
 def setup(app, plugin):
-    app.add_config_var('twitter/oauth_pin', forms.TextField(default=u''))
-    app.add_config_var('twitter/oauth_key', forms.TextField(default=u''))
-    app.add_config_var('twitter/oauth_secret', forms.TextField(default=u''))
-    app.add_config_var('twitter/message_template',
-            forms.TextField(default=DEFAULT_MESSAGE))
-    app.add_config_var('twitter/url_shortener', forms.TextField(default=u''))
-    app.add_config_var('twitter/bitly_login', forms.TextField(default=u''))
-    app.add_config_var('twitter/bitly_apikey', forms.TextField(default=u''))
+    """Main entry point.  Configure the plugin
+
+    """
+    def add_config_var(name, default=u''):
+        app.add_config_var('twitter/{0}'.format(name),
+                forms.TextField(default=default))
+
+    add_config_var('oauth_pin')
+    add_config_var('oauth_key')
+    add_config_var('oauth_secret')
+    add_config_var('message_template', default=DEFAULT_MESSAGE)
+    add_config_var('url_shortener')
+    add_config_var('bitly_login')
+    add_config_var('bitly_apikey')
 
     app.add_url_rule('/options/twitter', prefix='admin',
-                     endpoint='twitter/config', view=show_twitter_config)
+                     endpoint='twitter/config', view=twitter_options_view)
 
-    app.connect_event('after-post-saved', do_tweet_post) #view.admin#385
+    app.connect_event('after-post-saved', tweet_post)
     app.connect_event('modify-admin-navigation-bar', add_twitter_links)
     app.connect_event('before-admin-response-rendered',
-            inject_post_to_twitter_script)
+            inject_javascript)
+
     app.add_shared_exports('twitter', SHARED)
     app.add_template_searchpath(TEMPLATES)
 
 
-def inject_post_to_twitter_script(request, context):
-    add_header_snippet("\n".join((
-        '<script type="text/javascript">',
-        'var path = "' + request.path + '";'
-        '</script>'
-        )))
-    add_script(url_for('twitter/shared', filename='twitter.js'))
+def inject_javascript(request, context):
+    """Add the twitter.js javascript file to admin pages
 
+    """
+    if _is_configured():
+        add_script(url_for('twitter/shared', filename='twitter.js'))
 
-def _shortened_url_for(post, config):
-    url = url_for(post)
 
+def shorten_url(url, config):
+    """Shorten the given url using the user's specified shortener
+
+    """
     url_shortener = config['twitter/url_shortener']
     if url_shortener == "bit.ly":
         from bitly import Api as bitly_api
     elif url_shortener == "tinyurl":
         import tinyurl
         url = tinyurl.create_one(url)
-
     return url
 
 
 def _get_oauth_handler():
+    """Initialize an oauth handler using this plugin's consumer key and secret
+
+    """
     return twitter_api.OAuthHandler("skkK7xEihChO42RSOx0w",
             "Dv08Nb5Zw51HZG8lJAZc7McpfFJ57PrKC0k3nXhnE")
 
 
 def _is_published(post):
+    """Determine whether or not the post is published
+
+    """
     return post.status == STATUS_PUBLISHED
 
 
-def do_tweet_post(post):
-    """Send a twitter announcement about the post."""
-    if not twitter_api:
-        flash(_('oauth-python-twitter library could not be located'))
-        return
+def _is_configured():
+    """Determine whether or not the twitter credentials have been set-up
 
+    """
+    config = get_application().cfg
+    token_key = config["twitter/oauth_key"]
+    token_secret = config["twitter/oauth_secret"]
+    return token_key and token_secret
+
+
+def tweet_post(post):
+    """Send a twitter announcement about the post
+
+    """
     if "tweet" not in get_request().values:
-        #flash(_('Skipped tweeting post. Unchecked.'))
+        # user opted out of tweeting post
         return
 
     if not _is_published(post):
-        flash(_("Posts cannot be tweeted until they are published."))
+        flash(_("Post cannot be tweeted until it is published"), 'warning')
+        return
+
+    if not _is_configured():
+        flash(_('Twitter key and secret not initialized. Please configure '
+                'this plugin using the twitter options menu.'), 'error')
+        return
+
+    if not twitter_api:
+        flash(_('tweepy library could not be located'), 'error')
         return
 
     config = get_application().cfg
-    token_key = config["twitter/oauth_key"]
-    token_secret = config["twitter/oauth_secret"]
-    if not token_key or not token_secret:
-        flash(_('oauth twitter key and secret not initialized. '
-            'please configure them on the twitter options screen.'))
-        return
+    oauth_key = config["twitter/oauth_key"]
+    oauth_secret = config["twitter/oauth_secret"]
+    message_template = config["twitter/message_template"]
 
     auth = _get_oauth_handler()
-    auth.set_access_token(token_key, token_secret)
+    auth.set_access_token(oauth_key, oauth_secret)
     api = twitter_api.API(auth)
 
-    url = _shortened_url_for(post, config)
-
-    message_template = config["twitter/message_template"]
+    url = shorten_url(url_for(post), config)
     message = message_template.format(title=post.title, url=url)
 
     status = api.update_status(message)
-    flash(_('Tweeted: {0}').format(status.text))
+    flash(_('Tweeted: {0}').format(status.text), 'ok')
 
 
 def add_twitter_links(req, navigation_bar):
-    """Add a button for twitter configuration options."""
+    """Add a button for twitter configuration options
+
+    """
     if not req.user.has_privilege(BLOG_ADMIN):
         return
     for link_id, url, title, children in navigation_bar:
 
 
 @require_privilege(BLOG_ADMIN)
-def show_twitter_config(req):
-    """Show the twitter control panel."""
+def twitter_options_view(req):
+    """Show the twitter options page
+
+    """
     if not twitter_api:
-        flash(_('python-twitter library could not be located'))
-
+        raise Exception('tweepy library could not be located. '
+                        'Please install all dependencies before proceeding.')
     handler = _get_oauth_handler()
     oauth_url = handler.get_authorization_url()
+    oauth_request_key = handler.request_token.key
+    oauth_request_secret = handler.request_token.secret
     form = ConfigurationForm(initial=dict(
         oauth_pin=req.app.cfg['twitter/oauth_pin'],
         oauth_pin_changed="",
-        oauth_request_token_key=handler.request_token.key,
-        oauth_request_token_secret=handler.request_token.secret,
+        oauth_request_token_key=oauth_request_key,
+        oauth_request_token_secret=oauth_request_secret,
         message_template=req.app.cfg['twitter/message_template'],
         url_shortener=req.app.cfg['twitter/url_shortener'],
         bitly_login=req.app.cfg['twitter/bitly_login'],
 
     if req.method == 'POST' and form.validate(req.form):
         if form.has_changed:
-            pin = form['oauth_pin']
-            pin_changed = form["oauth_pin_changed"]
-            req.app.cfg.change_single('twitter/oauth_pin', pin)
-            req.app.cfg.change_single('twitter/message_template', form['message_template'])
-            req.app.cfg.change_single('twitter/url_shortener', form['url_shortener'])
-            req.app.cfg.change_single('twitter/bitly_login', form['bitly_login'])
-            req.app.cfg.change_single('twitter/bitly_apikey', form['bitly_apikey'])
+            _process_update(req, form)
+        return redirect_to('twitter/config')
 
-            if pin_changed and pin:
-                handler = _get_oauth_handler()
-                handler.set_request_token(form['oauth_request_token_key'],
-                                          form['oauth_request_token_secret'])
-                token = handler.get_access_token(verifier=pin)
-                req.app.cfg.change_single('twitter/oauth_key', token.key)
-                req.app.cfg.change_single('twitter/oauth_secret', token.secret)
-                flash(_('Twitter posting has been successfully enabled.'), 'ok')
-            elif pin_changed:
-                req.app.cfg.change_single('twitter/oauth_key', "")
-                req.app.cfg.change_single('twitter/oauth_secret', "")
-                flash(_('Twitter posting has been disabled.'), 'ok')
-            else:
-                flash(_('Twitter oauth settings were not changed.'))
-        return redirect_to('twitter/config')
-    return render_admin_response('admin/twitter.html',
-                                 'options.twitter',
-                                 form=form.as_widget(),
-                                 oauth_url=oauth_url)
+    env = {"form": form.as_widget(),
+           "oauth_url": oauth_url}
+    return render_admin_response('admin/twitter.html', 'options.twitter', **env)
+
+
+def _process_update(req, form):
+    """Process the form POST
+
+    """
+    pin = form['oauth_pin']
+    pin_changed = form["oauth_pin_changed"]
+
+    def update_config(name, value):
+        req.app.cfg.change_single('twitter/{0}'.format(name), value)
+    update_config('oauth_pin', pin)
+    update_config('message_template', form['message_template'])
+    update_config('url_shortener', form['url_shortener'])
+    update_config('bitly_login', form['bitly_login'])
+    update_config('bitly_apikey', form['bitly_apikey'])
+
+    if pin_changed and pin:
+        handler = _get_oauth_handler()
+        handler.set_request_token(form['oauth_request_token_key'],
+                                  form['oauth_request_token_secret'])
+        token = handler.get_access_token(verifier=pin)
+        update_config('oauth_key', token.key)
+        update_config('oauth_secret', token.secret)
+        flash(_('Twitter posting has been successfully enabled.'), 'ok')
+    elif pin_changed:
+        update_config('oauth_key', '')
+        update_config('oauth_secret', '')
+        flash(_('Twitter posting has been disabled.'), 'ok')
+    else:
+        flash(_('Twitter oauth settings were not changed.'))
 
 
 class ConfigurationForm(forms.Form):
-    """The configuration form."""
+    """The configuration form widget
+
+    """
     oauth_pin = forms.TextField()
     oauth_pin_changed = forms.TextField(widget=forms.HiddenInput)
     oauth_request_token_key = forms.TextField(widget=forms.HiddenInput)