def request_resource(self, url, **kwargs): maxwidth = kwargs.get('maxwidth', None) maxheight = kwargs.get('maxheight', None) # calculate the appropriate width and height w, h = size_to_nearest(maxwidth, maxheight, self.MAP_SIZES, True) # prepare the dictionary of data to be returned as an oembed resource data = { 'type': 'rich', 'provider_name': 'Google', 'version': '1.0', 'width': w, 'height': h, 'title': '', 'author_name': '', 'author_url': '' } url_params = re.match(self.regex, url).groups()[0] url_params = url_params.replace('&', '&').split('&') map_params = ['output=embed'] for param in url_params: k, v = param.split('=', 1) if k in self.VALID_PARAMS: map_params.append(param) data['html'] = '<iframe width="%d" height="%d" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?%s"></iframe>' % \ (w, h, '&'.join(map_params)) return OEmbedResource.create(data)
def request_resource(self, url, **kwargs): pattern = settings.SITEURL.replace('/', '\/') + 'maps\/\d+' result = re.match(pattern, url) if result is None: return HttpResponse(("Invalid oEmbed URL"), status=400, mimetype="text/plain") else: map_id = int(urlparse(url).path.split('/')[2]) map_obj = get_object_or_404(Map, id=map_id) # we don't have a request object to use to find the current user so # let's just assume the user is anonymous and check the publishing status if map_obj.publish.status == 'Private': raise PermissionDenied() maxwidth = kwargs.get('maxwidth', None) maxheight = kwargs.get('maxheight', None) # prepare the dictionary of data to be returned as an oembed resource data = { 'type': 'rich', 'provider_name': 'MapStory', 'version': '1.0', 'width': maxwidth, 'height': maxheight, 'title': map_obj.title, 'author_name': map_obj.owner.username, 'author_url': settings.SITEURL[:-1] + map_obj.owner.get_absolute_url() } embed_url = settings.SITEURL[:-1] + map_obj.get_absolute_url() + '/embed' data['html'] = '<iframe style="border: none;" height="%s" width="%s" src="%s"></iframe>' % (maxheight, maxwidth, embed_url) return OEmbedResource.create(data)
def test_json_handling(self): resource = oembed.site.embed(self.category_url) json = resource.json another_resource = OEmbedResource.create_json(json) self.assertEqual(resource.get_data(), another_resource.get_data())
def request_resource(self, url, **kwargs): maxwidth = kwargs.get('maxwidth', None) maxheight = kwargs.get('maxheight', None) # calculate the appropriate bounds for width and height w, h = size_to_nearest(maxwidth, maxheight, self.IMAGE_SIZES, True) # get the path, i.e. /media/img/kitties.jpg image_path = re.match(self.regex, url).groups()[0] # create the entire url as it would be on site, minus the filename base_url, ext = url.rsplit('.', 1) # create the file path minus the extension base_path, ext = image_path.rsplit('.', 1) append = '_%sx%s.%s' % (w, h, ext) new_path = '%s%s' % (base_path, append) if not default_storage.exists(new_path): # open the original to calculate its width and height source_file = default_storage.open(image_path) img = Image.open(source_file) # retrieve image format and dimensions format = img.format img_width, img_height = img.size # do the math-y parts new_width, new_height = scale(img_width, img_height, w, h) img = img.resize((new_width, new_height), Image.ANTIALIAS) img_buffer = StringIO() img.MAXBLOCK = 1024 * 1024 img.save(img_buffer, format=format) source_file.close() default_storage.save(new_path, ContentFile(img_buffer.getvalue())) new_url = '%s%s' % (base_url, append) # get just the filename, i.e. test.jpg - used for generated the title # of the returned oembed resource image_filename = image_path.rsplit('/', 1)[-1] data = { 'type': 'photo', 'provider_name': '', 'version': '1.0', 'width': w, 'height': h, 'title': image_filename, 'url': new_url, 'author_name': '', 'author_url': '' } return OEmbedResource.create(data)
def request_resource(self, url, **kwargs): maxwidth = kwargs.get('maxwidth', None) maxheight = kwargs.get('maxheight', None) # calculate the appropriate bounds for width and height w, h = size_to_nearest(maxwidth, maxheight, self.IMAGE_SIZES, True) # get the path, i.e. /media/img/kitties.jpg image_path = re.match(self.regex, url).groups()[0] # create the entire filename as it would be on disk filename = settings.MEDIA_ROOT + image_path # create the entire url as it would be on site, minus the filename base_url, ext = url.rsplit('.', 1) # create the file path on disk minus the extension base_file, ext = filename.rsplit('.', 1) append = '_%sx%s.%s' % (w, h, ext) new_filename = '%s%s' % (base_file, append) if not os.path.isfile(new_filename): # open the original to calculate its width and height img = Image.open(filename) img_width, img_height = img.size # do the math-y parts new_width, new_height = scale(img_width, img_height, w, h) img = img.resize((new_width, new_height), Image.ANTIALIAS) img.save(new_filename) new_url = '%s%s' % (base_url, append) # get just the filename, i.e. test.jpg - used for generated the title # of the returned oembed resource image_filename = image_path.rsplit('/', 1)[1] data = { 'type': 'photo', 'provider_name': '', 'version': '1.0', 'width': w, 'height': h, 'title': image_filename, 'url': new_url, 'author_name': '', 'author_url': '' } return OEmbedResource.create(data)
def embed(self, url, **kwargs): """ The heart of the matter """ try: # first figure out the provider provider = self.provider_for_url(url) except OEmbedMissingEndpoint: raise else: try: # check the database for a cached response, because of certain # race conditions that exist with get_or_create(), do a filter # lookup and just grab the first item stored_match = StoredOEmbed.objects.filter( match=url, maxwidth=kwargs.get('maxwidth', None), maxheight=kwargs.get('maxheight', None), date_expires__gte=datetime.datetime.now())[0] return OEmbedResource.create_json(stored_match.response_json) except IndexError: # query the endpoint and cache response in db # prevent None from being passed in as a GET param params = dict([(k, v) for k, v in kwargs.items() if v]) # request an oembed resource for the url resource = provider.request_resource(url, **params) try: cache_age = int(resource.cache_age) if cache_age < MIN_OEMBED_TTL: cache_age = MIN_OEMBED_TTL except: cache_age = DEFAULT_OEMBED_TTL date_expires = datetime.datetime.now() + datetime.timedelta(seconds=cache_age) stored_oembed, created = StoredOEmbed.objects.get_or_create( match=url, maxwidth=kwargs.get('maxwidth', None), maxheight=kwargs.get('maxheight', None)) stored_oembed.response_json = resource.json stored_oembed.resource_type = resource.type stored_oembed.thumbnail_url = resource.thumbnail_url stored_oembed.date_expires = date_expires if resource.content_object: stored_oembed.content_object = resource.content_object stored_oembed.save() return resource
def embed(self, url, **kwargs): """ The heart of the matter """ try: # first figure out the provider provider = self.provider_for_url(url) except OEmbedMissingEndpoint: raise else: try: # check the database for a cached response, because of certain # race conditions that exist with get_or_create(), do a filter # lookup and just grab the first item stored_match = StoredOEmbed.objects.filter( match=url, maxwidth=kwargs.get('maxwidth', None), maxheight=kwargs.get('maxheight', None), date_expires__gte=datetime.datetime.now())[0] return OEmbedResource.create_json(stored_match.response_json) except IndexError: # query the endpoint and cache response in db # prevent None from being passed in as a GET param params = dict([(k, v) for k, v in kwargs.items() if v]) # request an oembed resource for the url resource = provider.request_resource(url, **params) try: cache_age = int(resource.cache_age) if cache_age < MIN_OEMBED_TTL: cache_age = MIN_OEMBED_TTL except: cache_age = DEFAULT_OEMBED_TTL date_expires = datetime.datetime.now() + datetime.timedelta( seconds=cache_age) stored_oembed, created = StoredOEmbed.objects.get_or_create( match=url, maxwidth=kwargs.get('maxwidth', None), maxheight=kwargs.get('maxheight', None)) stored_oembed.response_json = resource.json stored_oembed.resource_type = resource.type stored_oembed.date_expires = date_expires if resource.content_object: stored_oembed.content_object = resource.content_object stored_oembed.save() return resource
def request_resource(self, url, **kwargs): maxwidth = kwargs.get('maxwidth', None) maxheight = kwargs.get('maxheight', None) # calculate the appropriate bounds for width and height w, h = size_to_nearest(maxwidth, maxheight, self.IMAGE_SIZES, True) # get the path, i.e. /media/img/kitties.jpg image_path = re.match(self.regex, url).groups()[0] # create the entire url as it would be on site, minus the filename base_url, ext = url.rsplit('.', 1) # create the file path minus the extension base_path, ext = image_path.rsplit('.', 1) append = '_%sx%s.%s' % (w, h, ext) new_path = '%s%s' % (base_path, append) if not default_storage.exists(new_path): # open the original to calculate its width and height source_file = default_storage.open(image_path) img = Image.open(source_file) # retrieve image format and dimensions format = img.format img_width, img_height = img.size # do the math-y parts new_width, new_height = scale(img_width, img_height, w, h) img = img.resize((new_width, new_height), Image.ANTIALIAS) img_buffer = StringIO() img.MAXBLOCK = 1024*1024 img.save(img_buffer, format=format) source_file.close() default_storage.save(new_path, ContentFile(img_buffer.getvalue())) new_url = '%s%s' % (base_url, append) # get just the filename, i.e. test.jpg - used for generated the title # of the returned oembed resource image_filename = image_path.rsplit('/', 1)[-1] data = {'type': 'photo', 'provider_name': '', 'version': '1.0', 'width': w, 'height': h, 'title': image_filename, 'url': new_url, 'author_name': '', 'author_url': ''} return OEmbedResource.create(data)
def convert_to_resource(self, headers, raw_response, params): if 'content-type' not in headers: raise OEmbedException('Missing mime-type in response') if headers['content-type'] in ('text/javascript', 'application/json'): try: json_response = simplejson.loads(raw_response) resource = OEmbedResource.create(json_response) except ValueError: raise OEmbedException('Unable to parse response json') else: raise OEmbedException('Invalid mime-type - %s' % headers['content-type']) return resource
def convert_to_resource(self, headers, raw_response, params): if "content-type" not in headers: raise OEmbedException("Missing mime-type in response") if headers["content-type"] in ("text/javascript", "application/json"): try: json_response = simplejson.loads(raw_response) resource = OEmbedResource.create(json_response) except ValueError: raise OEmbedException("Unable to parse response json") else: raise OEmbedException("Invalid mime-type - %s" % headers["content-type"]) return resource
def request_resource(self, url, **kwargs): """ Request an OEmbedResource for a given url. Some valid keyword args: - format - maxwidth - maxheight """ obj = self.get_object(url) mapping = self.map_to_dictionary(url, obj, **kwargs) resource = OEmbedResource.create(mapping) resource.content_object = obj return resource
def request_resource(self, url, **kwargs): maxwidth = kwargs.get('maxwidth', None) maxheight = kwargs.get('maxheight', None) # calculate the appropriate bounds for width and height w, h = size_to_nearest(maxwidth, maxheight, self.IMAGE_SIZES, True) # get the path, i.e. /media/img/kitties.jpg image_path = re.match(self.regex, url).groups()[0] # create the entire filename as it would be on disk filename = settings.MEDIA_ROOT + image_path # create the entire url as it would be on site, minus the filename base_url, ext = url.rsplit('.', 1) # create the file path on disk minus the extension base_file, ext = filename.rsplit('.', 1) append = '_%sx%s.%s' % (w, h, ext) new_filename = '%s%s' % (base_file, append) if not os.path.isfile(new_filename): # open the original to calculate its width and height img = Image.open(filename) img_width, img_height = img.size # do the math-y parts new_width, new_height = scale(img_width, img_height, w, h) img = img.resize((new_width, new_height), Image.ANTIALIAS) img.save(new_filename) new_url = '%s%s' % (base_url, append) # get just the filename, i.e. test.jpg - used for generated the title # of the returned oembed resource image_filename = image_path.rsplit('/', 1)[1] data = {'type': 'photo', 'provider_name': '', 'version': '1.0', 'width': w, 'height': h, 'title': image_filename, 'url': new_url, 'author_name': '', 'author_url': ''} return OEmbedResource.create(data)
def request_resource(self, url, **kwargs): pattern = settings.SITEURL.replace('/', '\/') + 'maps\/\d+' result = re.match(pattern, url) if result is None: return HttpResponse(("Invalid oEmbed URL"), status=400, mimetype="text/plain") else: map_id = int(urlparse(url).path.split('/')[2]) map_obj = get_object_or_404(Map, id=map_id) # we don't have a request object to use to find the current user so # let's just assume the user is anonymous and check the publishing status if map_obj.publish.status == 'Private': raise PermissionDenied() maxwidth = kwargs.get('maxwidth', None) maxheight = kwargs.get('maxheight', None) # prepare the dictionary of data to be returned as an oembed resource data = { 'type': 'rich', 'provider_name': 'MapStory', 'version': '1.0', 'width': maxwidth, 'height': maxheight, 'title': map_obj.title, 'author_name': map_obj.owner.username, 'author_url': settings.SITEURL[:-1] + map_obj.owner.get_absolute_url() } embed_url = settings.SITEURL[:-1] + map_obj.get_absolute_url( ) + '/embed' data[ 'html'] = '<iframe style="border: none;" height="%s" width="%s" src="%s"></iframe>' % ( maxheight, maxwidth, embed_url) return OEmbedResource.create(data)