Commits

Julian Rosse  committed 4d5129d

twitter images; mako caching

  • Participants
  • Parent commits 1b687d7
  • Branches optional

Comments (0)

Files changed (6)

File sleepy/facebookish.py

 def picture( id ):
     return Picture( cacher( cache_name="facebook_pictures",
                             key=id,
+                            cache_expire=None,
                             createfunc=lambda:
                                         _service()
                                          .get_object( id )))

File sleepy/shorties.py

 from email.utils import formatdate
 import smtplib
 from mimetypes import guess_type
+from urlparse import urlparse
+from httplib import HTTPConnection
+
 
 log = logging.getLogger( __name__ )
 if not logging.root.handlers:
     logging.basicConfig()
 log.setLevel( logging.DEBUG )
 
+def xre( regex ):
+    return re.compile( regex,
+                       re.X )
+
+# from zacwitte.com
+def resolve_http_redirect( url,
+                           depth=0 ):
+    if depth > 10:
+        raise Exception( "Redirected "
+                          + depth
+                          + " times, giving up." )
+    parsed_url = urlparse( url,
+                           allow_fragments=True )
+    conn = HTTPConnection( parsed_url
+                            .netloc )
+    path = parsed_url.path
+    if parsed_url.query:
+        path += '?' + parsed_url.query
+    conn.request( "HEAD",
+                  path )
+    res = conn.getresponse()
+    headers = dict( res.getheaders())
+    if headers.has_key( 'location' ) and headers[ 'location' ] != url:
+        return resolve_http_redirect( headers[ 'location' ],
+                                      depth + 1 )
+    else:
+        return url
+
 def date_parse( str_or_datetime ):
     return ( str_or_datetime
               if isinstance( str_or_datetime,

File sleepy/templates/default_project/+package+/config/environment.py_tmpl

                                                module_directory=join( app_conf[ "cache_dir" ],
                                                                       "templates" ),
                                                input_encoding="utf-8",
+                                               cache_impl="beaker",
+                                               cache_args=dict( manager=config
+                                                                         [ "pylons.app_globals" ]
+                                                                         .cache ),
                                                default_filters=[ "_raw",
                                                                  "escape" ],
                                                imports=[ "from sleepy.shorties import _raw",

File sleepy/templates/default_project/development.ini_tmpl

 beaker.session.secret = somesecret
 beaker.session.type = memory
 
-#profiler = true
+; profiler = true
+; sleepy.versioned_css = true
  
 # WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT*
 # Debug mode will enable the interactive debugging tool, allowing ANYONE to
 # execute malicious code after an exception is raised.
-#set debug = false
+; set debug = false
 
 #filter-with = proxy-prefix
 #[filter:proxy-prefix]

File sleepy/templates/sleepy/util.mako

     </script>
 </%def>
 <%def
+        cached="True"
+        cache_key="sleepy.versioned_css.${ name }"
         name="css( name=None )">
     <%
         if not name:
                    link )">
     <a
             href="${ link }"
-            class="feedLink">
-        <img
+            class="feedLink"><img
                 class="${ name }Icon icon"
-                src="/images/${ name }_icon.png" />
-        <span
-                class="feedDate">
-            Posted ${ entry.ago }
-        </span>
-    </a>
+                src="/images/${ name }_icon.png" /><span
+                class="feedDate">Posted ${ entry.ago }</span></a>
+</%def>
+<%def
+        name="favicon( image )">
+    <link
+            rel="shortcut icon"
+            href="/images/${ image }" />
 </%def>
 <%def
         name="span_first( text )">

File sleepy/twitterish.py

 import twitter
 
-from sleepy.shorties import date_parse, PubUpMixin
-from sleepy.lonsies import Entries
+from sleepy.shorties import date_parse, PubUpMixin, xre, resolve_http_redirect
+from sleepy.lonsies import Entries, cacher
 from sleepy.tipes import TipeMixin
 
+_redirect_link_re = xre( """
+                          http://t.co/
+                          \S +
+                         """ )
+
+class ImageProvider( object ):
+    pass
+
+class ImgLy( ImageProvider ):
+    re = xre( """
+               img.ly/
+               (
+                \w +
+               )
+              """ )
+
+    @staticmethod
+    def src( match ):
+        return "http://img.ly/show/medium/" + match.group( 1 )
+
+image_providers = ( ImgLy, )
+
 class Tweet( TipeMixin,
              PubUpMixin ):
     def __init__( self,
                   d,
                   user=None,
-                  use_cache=True ):
+                  use_cache=True,
+                  resolve_links=True ):
         self._published = self._updated = d.created_at
         self.message = d.text
         self.id = d.id
+        if resolve_links:
+            match = ( _redirect_link_re
+                       .search( self.message ))
+            if match:
+                def _image( tco_url ):
+                    url = resolve_http_redirect( tco_url )
+                    for image_provider in image_providers:
+                        image_match = ( image_provider
+                                         .re
+                                         .search( url ))
+                        if image_match:
+                            print "match"
+                            return ( image_provider
+                                      .src( image_match ))
+
+                self.image = cacher( cache_name="twitter_images",
+                                     key=match
+                                          .group(),
+                                     cache_expire=None,
+                                     createfunc=lambda:
+                                                 _image( match.group()))
 
 posts = Entries( entry_class=Tweet,
                  user_config_key="twitter_user",