<s> import datetime <EOL> import httplib2 <EOL> import re <EOL> import time <EOL> from urllib import urlencode <EOL> try : <EOL> import Image <EOL> except ImportError : <EOL> from PIL import Image <EOL> try : <EOL> from cStringIO import StringIO <EOL> except ImportError : <EOL> from StringIO import StringIO <EOL> from django . conf import settings <EOL> from django . contrib . sites . models import Site <EOL> from django . core . files import storage <EOL> from django . core . urlresolvers import get_resolver <EOL> from django . db . models . fields import DateTimeField , DateField <EOL> from django . db . models . fields . files import ImageField , ImageFieldFile <EOL> from django . template import RequestContext , Context <EOL> from django . template . loader import render_to_string , get_template <EOL> from django . utils import simplejson <EOL> from oembed . constants import OEMBED_ALLOWED_SIZES , OEMBED_THUMBNAIL_SIZE <EOL> from oembed . exceptions import OEmbedException , OEmbedHTTPException <EOL> from oembed . image_processors import image_processor <EOL> from oembed . resources import OEmbedResource <EOL> from oembed . utils import ( fetch_url , get_domain , mock_request , cleaned_sites , <EOL> size_to_nearest , relative_to_full , scale ) <EOL> resolver = get_resolver ( None ) <EOL> class BaseProvider ( object ) : <EOL> """<STR_LIT>""" <EOL> regex = None <EOL> provides = True <EOL> def request_resource ( self , url , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> raise NotImplementedError <EOL> class HTTPProvider ( BaseProvider ) : <EOL> """<STR_LIT>""" <EOL> endpoint_url = '<STR_LIT>' <EOL> provides = False <EOL> url_scheme = None <EOL> resource_type = None <EOL> def __init__ ( self ) : <EOL> self . _validate ( ) <EOL> def _validate ( self ) : <EOL> if self . provides and ( not self . url_scheme or not self . resource_type ) : <EOL> raise AttributeError ( <EOL> '<STR_LIT>' '<STR_LIT>' % self . __name__ ) <EOL> if self . provides and self . resource_type not in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> def _fetch ( self , url ) : <EOL> """<STR_LIT>""" <EOL> return fetch_url ( url ) <EOL> def convert_to_resource ( self , headers , raw_response , params ) : <EOL> if '<STR_LIT>' not in headers : <EOL> raise OEmbedException ( '<STR_LIT>' ) <EOL> content_type = headers [ '<STR_LIT>' ] . split ( '<STR_LIT:;>' ) [ <NUM_LIT:0> ] <EOL> if content_type in ( '<STR_LIT>' , '<STR_LIT:application/json>' ) : <EOL> try : <EOL> json_response = simplejson . loads ( raw_response ) <EOL> resource = OEmbedResource . create ( json_response ) <EOL> except ValueError : <EOL> raise OEmbedException ( '<STR_LIT>' ) <EOL> else : <EOL> raise OEmbedException ( '<STR_LIT>' % headers [ '<STR_LIT>' ] ) <EOL> return resource <EOL> def request_resource ( self , url , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> params = kwargs <EOL> params [ '<STR_LIT:url>' ] = url <EOL> params [ '<STR_LIT>' ] = '<STR_LIT>' <EOL> if '<STR_LIT:?>' in self . endpoint_url : <EOL> url_with_qs = '<STR_LIT>' % ( self . endpoint_url . rstrip ( '<STR_LIT:&>' ) , urlencode ( params ) ) <EOL> else : <EOL> url_with_qs = "<STR_LIT>" % ( self . endpoint_url , urlencode ( params ) ) <EOL> headers , raw_response = self . _fetch ( url_with_qs ) <EOL> resource = self . convert_to_resource ( headers , raw_response , params ) <EOL> return resource <EOL> class DjangoProviderOptions ( object ) : <EOL> model = None <EOL> named_view = '<STR_LIT>' <EOL> fields_to_match = { } <EOL> valid_sizes = OEMBED_ALLOWED_SIZES <EOL> thumbnail_sizes = OEMBED_THUMBNAIL_SIZE <EOL> image_processor = image_processor ( ) <EOL> force_fit = False <EOL> year_part = '<STR_LIT>' <EOL> month_part = '<STR_LIT>' <EOL> day_part = '<STR_LIT>' <EOL> context_varname = '<STR_LIT:object>' <EOL> abstract = False <EOL> def __init__ ( self , meta_options , provider_class ) : <EOL> for k , v in meta_options . __dict__ . items ( ) : <EOL> if not k . startswith ( '<STR_LIT:_>' ) : <EOL> self . __dict__ [ k ] = v <EOL> self . provider_class = provider_class <EOL> if not self . abstract : <EOL> self . _validate ( ) <EOL> if not getattr ( self , '<STR_LIT>' , None ) : <EOL> self . template_name = '<STR_LIT>' % ( <EOL> self . model . _meta . app_label , self . model . _meta . module_name <EOL> ) <EOL> def _validate ( self ) : <EOL> if self . model is None : <EOL> raise OEmbedException ( '<STR_LIT>' % self . provider_class . __name__ ) <EOL> if not self . named_view : <EOL> raise OEmbedException ( '<STR_LIT>' % self . provider_class . __name__ ) <EOL> def _image_field ( self ) : <EOL> """<STR_LIT>""" <EOL> for field in self . model . _meta . fields : <EOL> if isinstance ( field , ImageField ) : <EOL> return field . name <EOL> image_field = property ( _image_field ) <EOL> def _date_field ( self ) : <EOL> """<STR_LIT>""" <EOL> for field in self . model . _meta . fields : <EOL> if isinstance ( field , ( DateTimeField , DateField ) ) : <EOL> return field . name <EOL> date_field = property ( _date_field ) <EOL> class DjangoProviderMetaclass ( type ) : <EOL> def __new__ ( cls , name , bases , attrs ) : <EOL> """<STR_LIT>""" <EOL> meta = attrs . pop ( '<STR_LIT:Meta>' , None ) <EOL> provider_class = super ( DjangoProviderMetaclass , cls ) . __new__ ( <EOL> cls , name , bases , attrs ) <EOL> for b in bases : <EOL> base_meta = getattr ( b , '<STR_LIT>' , None ) <EOL> if not base_meta : <EOL> continue <EOL> for ( k , v ) in base_meta . __dict__ . items ( ) : <EOL> if not k . startswith ( '<STR_LIT:_>' ) and k != '<STR_LIT>' and k not in meta . __dict__ : <EOL> meta . __dict__ [ k ] = v <EOL> if meta : <EOL> _meta = DjangoProviderOptions ( meta , provider_class ) <EOL> provider_class . _meta = _meta <EOL> return provider_class <EOL> class DjangoProvider ( BaseProvider ) : <EOL> """<STR_LIT>""" <EOL> __metaclass__ = DjangoProviderMetaclass <EOL> resource_type = None <EOL> def __init__ ( self ) : <EOL> self . _validate ( ) <EOL> def _validate ( self ) : <EOL> if self . resource_type not in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> raise ValueError ( '<STR_LIT>' ) <EOL> def _build_regex ( self ) : <EOL> """<STR_LIT>""" <EOL> url_patterns = resolver . reverse_dict . get ( self . _meta . named_view ) <EOL> try : <EOL> regex = url_patterns [ <NUM_LIT:1> ] <EOL> except TypeError : <EOL> raise OEmbedException ( '<STR_LIT>' % self . _meta . named_view ) <EOL> cleaned_sites = self . get_cleaned_sites ( ) <EOL> site_regexes = [ ] <EOL> for site in self . get_sites ( ) : <EOL> site_regexes . append ( cleaned_sites [ site . pk ] [ <NUM_LIT:0> ] ) <EOL> sites = '<STR_LIT:|>' . join ( site_regexes ) <EOL> regex = re . compile ( '<STR_LIT>' % ( sites , regex ) ) <EOL> return regex <EOL> regex = property ( _build_regex ) <EOL> def get_sites ( self ) : <EOL> """<STR_LIT>""" <EOL> return Site . objects . all ( ) <EOL> def get_cleaned_sites ( self ) : <EOL> """<STR_LIT>""" <EOL> if not getattr ( self , '<STR_LIT>' , None ) : <EOL> self . _clean_sites = cleaned_sites ( ) <EOL> return self . _clean_sites <EOL> def provider_from_url ( self , url ) : <EOL> """<STR_LIT>""" <EOL> domain = get_domain ( url ) <EOL> site_tuples = self . get_cleaned_sites ( ) . values ( ) <EOL> for domain_re , name , normalized_domain in site_tuples : <EOL> if re . match ( domain_re , domain ) : <EOL> return normalized_domain , name <EOL> site = Site . objects . get_current ( ) <EOL> return site . domain , site . name <EOL> def get_params ( self , url ) : <EOL> """<STR_LIT>""" <EOL> match = re . match ( self . regex , url ) <EOL> if match is not None : <EOL> params = match . groupdict ( ) <EOL> if not params : <EOL> params = { } <EOL> for i , group in enumerate ( match . groups ( ) [ <NUM_LIT:1> : ] ) : <EOL> params [ '<STR_LIT>' % i ] = group <EOL> return params <EOL> raise OEmbedException ( '<STR_LIT>' % ( url ) ) <EOL> def get_queryset ( self ) : <EOL> return self . _meta . model . _default_manager . all ( ) <EOL> def get_object ( self , url ) : <EOL> """<STR_LIT>""" <EOL> params = self . get_params ( url ) <EOL> query = { } <EOL> for key , value in self . _meta . fields_to_match . iteritems ( ) : <EOL> try : <EOL> query [ value ] = params [ key ] <EOL> except KeyError : <EOL> raise OEmbedException ( '<STR_LIT>' % ( key , '<STR_LIT:U+002CU+0020>' . join ( params . keys ( ) ) ) ) <EOL> try : <EOL> obj = self . get_queryset ( ) . get ( ** query ) <EOL> except self . _meta . model . DoesNotExist : <EOL> raise OEmbedException ( '<STR_LIT>' ) <EOL> return obj <EOL> def render_html ( self , obj , context = None ) : <EOL> """<STR_LIT>""" <EOL> provided_context = context or Context ( ) <EOL> context = RequestContext ( mock_request ( ) ) <EOL> context . update ( provided_context ) <EOL> context . push ( ) <EOL> context [ self . _meta . context_varname ] = obj <EOL> rendered = render_to_string ( self . _meta . template_name , context ) <EOL> context . pop ( ) <EOL> return rendered <EOL> def map_attr ( self , mapping , attr , obj ) : <EOL> """<STR_LIT>""" <EOL> if attr not in mapping and hasattr ( self , attr ) : <EOL> if not callable ( getattr ( self , attr ) ) : <EOL> mapping [ attr ] = getattr ( self , attr ) <EOL> else : <EOL> mapping [ attr ] = getattr ( self , attr ) ( obj ) <EOL> def get_image ( self , obj ) : <EOL> """<STR_LIT>""" <EOL> if self . _meta . image_field : <EOL> return getattr ( obj , self . _meta . image_field ) <EOL> def resize ( self , image_field , new_width = None , new_height = None ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( image_field , ImageFieldFile ) and image_field . field . width_field and image_field . field . height_field : <EOL> current_width = getattr ( image_field . instance , image_field . field . width_field ) <EOL> current_height = getattr ( image_field . instance , image_field . field . height_field ) <EOL> else : <EOL> try : <EOL> file_obj = storage . default_storage . open ( image_field . name , '<STR_LIT:rb>' ) <EOL> img_obj = Image . open ( file_obj ) <EOL> current_width , current_height = img_obj . size <EOL> except IOError : <EOL> return ( image_field . url , <NUM_LIT:0> , <NUM_LIT:0> ) <EOL> if current_width < new_width : <EOL> if not new_height or current_height < new_height : <EOL> return ( image_field . url , current_width , current_height ) <EOL> new_width , new_height = scale ( current_width , current_height , new_width , new_height ) <EOL> return self . _meta . image_processor . resize ( image_field , new_width , new_height ) <EOL> def resize_photo ( self , obj , mapping , maxwidth = None , maxheight = None ) : <EOL> url , width , height = self . resize ( <EOL> self . get_image ( obj ) , <EOL> * size_to_nearest ( maxwidth , maxheight , self . _meta . valid_sizes ) ) <EOL> mapping . update ( url = url , width = width , height = height ) <EOL> def thumbnail ( self , obj , mapping ) : <EOL> url , width , height = self . resize ( <EOL> self . get_image ( obj ) , <EOL> * size_to_nearest ( allowed_sizes = self . _meta . thumbnail_sizes ) ) <EOL> mapping . update ( thumbnail_url = url , thumbnail_width = width , <EOL> thumbnail_height = height ) <EOL> def preprocess ( self , obj , mapping , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def postprocess ( self , obj , mapping , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> pass <EOL> def map_to_dictionary ( self , url , obj , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> maxwidth = kwargs . get ( '<STR_LIT>' , None ) <EOL> maxheight = kwargs . get ( '<STR_LIT>' , None ) <EOL> provider_url , provider_name = self . provider_from_url ( url ) <EOL> mapping = { <EOL> '<STR_LIT:version>' : '<STR_LIT:1.0>' , <EOL> '<STR_LIT:url>' : url , <EOL> '<STR_LIT>' : provider_name , <EOL> '<STR_LIT>' : provider_url , <EOL> '<STR_LIT:type>' : self . resource_type <EOL> } <EOL> self . preprocess ( obj , mapping , ** kwargs ) <EOL> if self . resource_type == '<STR_LIT>' and self . get_image ( obj ) : <EOL> self . resize_photo ( obj , mapping , maxwidth , maxheight ) <EOL> elif self . resource_type in ( '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) : <EOL> width , height = size_to_nearest ( <EOL> maxwidth , <EOL> maxheight , <EOL> self . _meta . valid_sizes , <EOL> self . _meta . force_fit <EOL> ) <EOL> mapping . update ( width = width , height = height ) <EOL> if self . get_image ( obj ) : <EOL> self . thumbnail ( obj , mapping ) <EOL> for attr in ( '<STR_LIT:title>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:html>' ) : <EOL> self . map_attr ( mapping , attr , obj ) <EOL> if '<STR_LIT:url>' in mapping : <EOL> mapping [ '<STR_LIT:url>' ] = relative_to_full ( mapping [ '<STR_LIT:url>' ] , url ) <EOL> if '<STR_LIT>' in mapping : <EOL> mapping [ '<STR_LIT>' ] = relative_to_full ( mapping [ '<STR_LIT>' ] , url ) <EOL> if '<STR_LIT:html>' not in mapping and mapping [ '<STR_LIT:type>' ] in ( '<STR_LIT>' , '<STR_LIT>' ) : <EOL> mapping [ '<STR_LIT:html>' ] = self . render_html ( obj , context = Context ( mapping ) ) <EOL> self . postprocess ( obj , mapping , ** kwargs ) <EOL> return mapping <EOL> def request_resource ( self , url , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> obj = self . get_object ( url ) <EOL> mapping = self . map_to_dictionary ( url , obj , ** kwargs ) <EOL> resource = OEmbedResource . create ( mapping ) <EOL> resource . content_object = obj <EOL> return resource <EOL> class DjangoDateBasedProvider ( DjangoProvider ) : <EOL> """<STR_LIT>""" <EOL> def _validate ( self ) : <EOL> super ( DjangoDateBasedProvider , self ) . _validate ( ) <EOL> if not self . _meta . date_field : <EOL> raise OEmbedException ( '<STR_LIT>' % self . __class__ . __name__ ) <EOL> def get_object ( self , url , month_format = '<STR_LIT>' , day_format = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> params = self . get_params ( url ) <EOL> try : <EOL> year = params [ self . _meta . year_part ] <EOL> month = params [ self . _meta . month_part ] <EOL> day = params [ self . _meta . day_part ] <EOL> except KeyError : <EOL> try : <EOL> year , month , day = params [ '<STR_LIT>' ] , params [ '<STR_LIT>' ] , params [ '<STR_LIT>' ] <EOL> except KeyError : <EOL> raise OEmbedException ( '<STR_LIT>' ) <EOL> try : <EOL> tt = time . strptime ( '<STR_LIT>' % ( year , month , day ) , <EOL> '<STR_LIT>' % ( '<STR_LIT>' , month_format , day_format ) ) <EOL> date = datetime . date ( * tt [ : <NUM_LIT:3> ] ) <EOL> except ValueError : <EOL> raise OEmbedException ( '<STR_LIT>' % url ) <EOL> if isinstance ( self . _meta . model . _meta . get_field ( self . _meta . date_field ) , DateTimeField ) : <EOL> min_date = datetime . datetime . combine ( date , datetime . time . min ) <EOL> max_date = datetime . datetime . combine ( date , datetime . time . max ) <EOL> query = { '<STR_LIT>' % self . _meta . date_field : ( min_date , max_date ) } <EOL> else : <EOL> query = { self . _meta . date_field : date } <EOL> for key , value in self . _meta . fields_to_match . iteritems ( ) : <EOL> try : <EOL> query [ value ] = params [ key ] <EOL> except KeyError : <EOL> raise OEmbedException ( '<STR_LIT>' % ( key , '<STR_LIT:U+002CU+0020>' . join ( params . keys ( ) ) ) ) <EOL> try : <EOL> obj = self . get_queryset ( ) . get ( ** query ) <EOL> except self . _meta . model . DoesNotExist : <EOL> raise OEmbedException ( '<STR_LIT>' ) <EOL> return obj </s>
