Exemple #1
0
def embedly_link(URL):
    #Takes a URL, returns a populated Link object
    #Returns "error" if Embedly API fails
    client = Embedly(embedly_key)
    response = client.extract(URL)
    try:
        #Get link information from Embedly
        headline = response['title']
        URL = clean_url(response['url'])
        summary = response['description']
        source = response['provider_name']
        path = page_path(headline)
        keywords_response = response['keywords']
        keyword1 = str(keywords_response[0]['name'])
        keyword2 = str(keywords_response[1]['name'])
        keyword3 = str(keywords_response[2]['name'])
        keyword4 = str(keywords_response[3]['name'])
        keyword5 = str(keywords_response[4]['name'])

        #Create Link object with info from Embedly
        link = Link(headline=headline,
                    url=URL,
                    source=source,
                    summary=summary,
                    path=path,
                    keyword1=keyword1,
                    keyword2=keyword2,
                    keyword3=keyword3,
                    keyword4=keyword4,
                    keyword5=keyword5,
                    votes=0)
        return link
    except:
        return "error"
Exemple #2
0
def replace(match):
    url = match.group('url')
    kind = match.group('kind')
    external_task = (match.group('kind') == 'externaltask')
    try:
        url_validate(url)
    except ValidationError:
        return '[%s:Invalid Url]' % kind
    for prefix in settings.P2PU_EMBEDS:
        if url.startswith(prefix):
            return render_to_string('richtext/_p2pu_embed.html', {'url': url})
    if not external_task:
        expiration_date = datetime.now() - settings.EMBEDLY_CACHE_EXPIRES
        embedded_urls = EmbeddedUrl.objects.filter(original_url=url,
            created_on__gte=expiration_date).order_by('-created_on')
        embedded_url = None
        if embedded_urls.exists():
            embedded_url = embedded_urls[0]
        else:
            embedly_key = getattr(settings, 'EMBEDLY_KEY', False)
            if embedly_key:
                client = Embedly(embedly_key)
                obj = client.oembed(url, maxwidth=460)
                embedded_url = EmbeddedUrl(original_url=obj.original_url,
                    html=(obj.html or ''), extra_data=obj.dict)
                embedded_url.save()
        if embedded_url and embedded_url.html:
            return embedded_url.html
    context = {'url': url, 'external_task': external_task}
    return render_to_string('richtext/_external_link.html', context)
Exemple #3
0
def replace(match):
    url = match.group('url')
    try:
        url_validate(url)
        if match.group('kind') == 'externaltask':
            return '<button class="external-task" data-url="%s">%s</button>' % (
                url, # TODO: Should we escape/encode this somehow?
                _('Start This Task')
                )
        expiration_date = datetime.now() - settings.EMBEDLY_CACHE_EXPIRES
        embedded_urls = EmbeddedUrl.objects.filter(original_url=url,
            created_on__gte=expiration_date).order_by('-created_on')
        embedded_url = None
        if embedded_urls.exists():
            embedded_url = embedded_urls[0]
        else:
            embedly_key = getattr(settings, 'EMBEDLY_KEY', False)
            if embedly_key:
                client = Embedly(embedly_key)
                obj = client.oembed(url, maxwidth=460)
                embedded_url = EmbeddedUrl(original_url=obj.original_url,
                    html=(obj.html or ''), extra_data=obj.dict)
                embedded_url.save()
        if embedded_url and embedded_url.html:
            return embedded_url.html
    except ValidationError:
        return '[embed:Invalid Url]'
    return DEFAULT_EMBED % (url, url)
Exemple #4
0
def _add_embedly_data(instance):
    import json
    from embedly import Embedly
    from main.api2 import APIException
    # for security, we can't let the client set embedly_data
    assert instance.original_url
    assert not instance.embedly_data
    client = Embedly(settings.EMBEDLY_KEY)
    obj = client.oembed(instance.original_url, 
        autoplay=False,
        maxwidth=600,
        # Fix overlay issues with flash under chrome/linux:
        wmode='transparent'
    )
    if obj.invalid:
        raise APIException('The submitted link is invalid')
    elif obj.type is 'error':
        raise APIException('Embedly error', obj.error_code)
    elif not obj.html:
        raise APIException('No embed html received')
    else:
        assert obj.provider_name.lower() in settings.ALLOWED_EMBEDLY_PROVIDERS
        instance.width = obj.width
        instance.height = obj.height
        instance.embedly_data = json.dumps(dict(obj))
Exemple #5
0
def replace(match):
    url = match.group('url')
    try:
        url_validate(url)
        expiration_date = datetime.now() - settings.EMBEDLY_CACHE_EXPIRES
        embedded_urls = EmbeddedUrl.objects.filter(
            original_url=url,
            created_on__gte=expiration_date).order_by('-created_on')
        embedded_url = None
        if embedded_urls.exists():
            embedded_url = embedded_urls[0]
        else:
            embedly_key = getattr(settings, 'EMBEDLY_KEY', False)
            if embedly_key:
                client = Embedly(embedly_key)
                obj = client.oembed(url, maxwidth=460)
                embedded_url = EmbeddedUrl(original_url=obj.original_url,
                                           html=(obj.html or ''),
                                           extra_data=obj.dict)
                embedded_url.save()
        if embedded_url and embedded_url.html:
            return embedded_url.html
    except ValidationError:
        return '[embed:Invalid Url]'
    return DEFAULT_EMBED % (url, url)
Exemple #6
0
def embedly_link(URL):
	#Takes a URL, returns a populated Link object
	#Returns "error" if Embedly API fails
	client = Embedly(embedly_key)
	response = client.extract(URL)
	try:
		#Get link information from Embedly
		headline = response['title']
		URL = clean_url(response['url'])
		summary = response['description']
		source = response['provider_name']
		path = page_path(headline)
		keywords_response = response['keywords']
		keyword1 = str(keywords_response[0]['name'])
		keyword2 = str(keywords_response[1]['name'])
		keyword3 = str(keywords_response[2]['name'])
		keyword4 = str(keywords_response[3]['name'])
		keyword5 = str(keywords_response[4]['name'])

		#Create Link object with info from Embedly
		link = Link(headline = headline, url = URL, source = source, summary = summary, 
			path = path, keyword1 = keyword1, keyword2 = keyword2, keyword3 = keyword3, 
			keyword4 = keyword4, keyword5 = keyword5, votes = 0)
		return link
	except:
		return "error"
Exemple #7
0
def getIframeForVideo(videoUrl):
    pwManager = getUtility(IPasswordManager, 'embedly')
    key = pwManager.username
    client = Embedly(key)
    embed = client.oembed(videoUrl, maxheight=377)
    if embed.error:
        return None
    return embed.html
Exemple #8
0
    def create_embed(self, options):
        embed = Embedly(settings.EMBEDLY_API_KEY)

        obj = embed.oembed(options['url'], width=options['width'], height=options['height'])
        el = etree.Element('div')
        el.set('class', 'post-embed')
        el.append(html.fromstring(obj.html))
        return html.tostring(el)
Exemple #9
0
def detect_embedded_content(text):
    results = []

    client = Embedly(key=EMBEDLY_KEY, user_agent=USER_AGENT)
    for url in re.findall(EMBED_REGEX, text):
        results.append(client.oembed(url))

    return results
Exemple #10
0
def cache_embed(request):
    if not request.POST:
        return HttpResponseBadRequest("cache_embed requires POST")
    url = request.POST.get('url')
    if not url:
        return HttpResponseBadRequest("POST a url, and I'll happily cache it")
    maxwidth = request.POST.get('maxwidth')
    
    #try memcache first
    key = make_cache_key(url, maxwidth)
    cached_response = cache.get(key)
    if cached_response and type(cached_response) == type(dict()):    
        cached_response['cache'] = 'memcache'
        return HttpResponse(json.dumps(cached_response), mimetype="application/json")

    #then the database
    try:
        saved = SavedEmbed.objects.get(url=url, maxwidth=maxwidth)
        response = saved.response
        response['html'] = saved.html
        response['cache'] = 'database'
        cache.set(key, response) #and save it to memcache
        return HttpResponse(json.dumps(response), mimetype="application/json")
    except SavedEmbed.DoesNotExist:
        pass

    #if we've never seen it before, call the embedly API
    client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
    if maxwidth:
       oembed = client.oembed(url, maxwidth=maxwidth)
    else:
       oembed = client.oembed(url)
    if oembed.error:
        return HttpResponseServerError('Error embedding %s.\n %s' % (url,oembed.error))

    #save result to database
    row, created = SavedEmbed.objects.get_or_create(url=url, maxwidth=maxwidth,
                    defaults={'type': oembed.type})
    row.provider_name = oembed.provider_name
    row.response = json.dumps(oembed.data)

    if oembed.type == 'photo':
        html = '<img src="%s" width="%s" height="%s" />' % (oembed.url,
               oembed.width, oembed.height)
    else:
        html = oembed.html

    if html:
        row.html = html
        row.last_updated = datetime.now()
        row.save()

    #and to memcache
    cache.set(key, row.response, 86400)
    response = row.response
    response['html'] = row.html #overwrite for custom oembed types
    response['cache'] = "none"
    return HttpResponse(json.dumps(response), mimetype="application/json")
Exemple #11
0
def get_oembed_data(context_var, maxwidth=None, maxheight=None):
    '''
    A custom templatetag that returns an object representing 
        all oembed data for a given url found in a context variable
    Usage:
    {% load embed_filters %}
    {% with context_var="Check out my cool photo: http://www.flickr.com/photos/visualpanic/233508614/" %}
        {{ context_var }}

        {% get_oembed_data context_var maxwidth=400 as oembed %}
        <div class="embed-data">
            {{oembed.title}} <br />
            {{oembed.description}} <br />
            {{oembed.html}} <br />
        </div>

    {% endwith %}

    Uses the Embedly API to get oembed data. Always look to the db/cache first,
        and then fall back to the Embedly API for speed 
        (at the cost of accuracy & updated urls).
    '''

    url = _get_url_from_context_variable(context_var)
    if not url:
        return {}

    #if maxwidth or maxheight is None, the unique_together constraint does not work
    #for now, just filter and check first element instead of using objects.get
    try:
        saved_embed = SavedEmbed.objects.filter(url=url, maxwidth=maxwidth, maxheight=maxheight)[0]
    except IndexError:
        client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
        try:
            if maxwidth and maxheight:
                oembed = client.oembed(url, maxwidth=maxwidth, maxheight=maxheight)
            elif maxwidth:
                oembed = client.oembed(url, maxwidth=maxwidth)
            elif maxheight:
                oembed = client.oembed(url, maxheight=maxheight)
            else:
                oembed = client.oembed(url)
        except: #TODO: don't catch all exceptions
            return {}

        if oembed.error:
            return {}

        saved_embed, created = SavedEmbed.objects.get_or_create(
                url=url,
                maxwidth=maxwidth,
                maxheight=maxheight,
                defaults={
                    'type': oembed.type,
                    'oembed_data': oembed.data
                })

    return saved_embed.oembed_data
Exemple #12
0
def get_embed_object(url):
    if not settings.EMBEDLY_KEY:
        raise ImproperlyConfigured("You have not specified an Embedly key in your settings file.")

    try:
        client = Embedly(settings.EMBEDLY_KEY)
        resp = client.oembed(url, maxwidth=settings.EMBED_MAX_WIDTH, maxheight=settings.EMBED_MAX_HEIGHT)
    except Exception, e:
        raise EmbedlyException("There was an issue with your embed URL. Please check that it is valid and try again")
def get_info_if_active(url):
    oembed = None
    if not ACTIVE:
        return oembed
    client = Embedly(settings.EMBEDLY_KEY)
    try:
        oe = client.oembed(url, maxwidth=None if not hasattr(settings,'EMBEDLY_MAXWIDTH') else settings.EMBEDLY_MAXWIDTH)
        if not oe.error:
            oembed = oe
    except httplib2.ServerNotFoundError, e:
        pass # Can't connect to server.
Exemple #14
0
  def noembed(self):
    """
    use noembed MILLER_EMBEDLY_API_KEY to get videos from url
    """
    if self.url:
      logger.debug('document {pk:%s, url:%s} init embedly' % (self.pk, self.url))

      from embedly import Embedly

      client = Embedly(settings.MILLER_EMBEDLY_API_KEY)
      embed = client.oembed(self.url, raw=True)
      self.contents = embed['raw']
Exemple #15
0
def get_article():
    url = request.args.get('url')
    client = Embedly('f2f84ff5013b443ab711b204590d9aa2')
    result = client.extract(url)

    article = {}
    article["url"] = result["url"]
    article["headline"] = result["title"]
    article["description"] = result["description"]
    article["content"] = result["content"]
    response = make_response(json.dumps(article, indent=4))
    response.headers['Access-Control-Allow-Origin'] = "*"
    return response
Exemple #16
0
def set_media():
	link = request.form.get('value')
	contribution = get_contribution(get_referer())
	client = Embedly('a54233f91473419f9a947e1300f27f9b')
	obj    = client.oembed(link)
	meta   = obj.__dict__
	media  = {
		'type'    : request.form.get('type'),
		'url'     : meta.get('url'),
		'meta'    : meta
	}
	contrib = update_media(media, get_referer())
	return dumps(contrib)
def embedly(url):
  try:
    client = Embedly(settings.EMBEDLY_KEY)
    obj = client.oembed(url)

  except:
    return None

  if obj.type == "photo":
    return '<a href="%s" class="embed"><img src="%s"></a>' % (
      obj.url, obj.url)

  return None
Exemple #18
0
def get_article():
	url = request.args.get('url')
	client = Embedly('f2f84ff5013b443ab711b204590d9aa2')
	result = client.extract(url)

	article = {}
	article["url"] = result["url"]
	article["headline"] = result["title"]
	article["description"] = result["description"]
	article["content"] = result["content"]
	response = make_response(json.dumps(article, indent=4))
	response.headers['Access-Control-Allow-Origin'] = "*"
	return response
Exemple #19
0
def get_list_from_embedly(bitly_url_links,KEY):
	client = Embedly(KEY)
	data_dict = dict()
	temp_dict = dict()
	for p,link in enumerate(bitly_url_links):
		link = client.oembed(link)
		temp_dict['title'] = link['title']
		temp_dict['url'] = link['url']
		temp_dict['thumbnail_url'] = link['thumbnail_url']
		temp_dict['thumbnail_width'] = link['thumbnail_width']
		temp_dict['description'] = link['description']
		data_dict[p] = temp_dict
	return data_dict
Exemple #20
0
def embedly(url):
    try:
        client = Embedly(settings.EMBEDLY_KEY)
        obj = client.oembed(url)

    except:
        return None

    if obj.type == "photo":
        return '<a href="%s" class="embed"><img src="%s"></a>' % (obj.url,
                                                                  obj.url)

    return None
Exemple #21
0
def set_media():
    link = request.form.get('value')
    contribution = get_contribution(get_referer())
    client = Embedly('a54233f91473419f9a947e1300f27f9b')
    obj = client.oembed(link)
    meta = obj.__dict__
    media = {
        'type': request.form.get('type'),
        'url': meta.get('url'),
        'meta': meta
    }
    contrib = update_media(media, get_referer())
    return dumps(contrib)
Exemple #22
0
def get_links(text):
    url_regex = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|'
                           '(?:%[0-9a-fA-F][0-9a-fA-F]))+')

    urls = url_regex.findall(text)

    embedly = []

    client = Embedly(app.config['EMBEDLY_KEY'])

    for url in urls:
        embedly.append(client.oembed(url))

    return embedly
Exemple #23
0
    def find_embed(self, url, max_width=None, key=None):
        from embedly import Embedly

        # Get embedly key
        if key is None:
            key = self.get_key()

        # Get embedly client
        client = Embedly(key=key)

        # Call embedly
        if max_width is not None:
            oembed = client.oembed(url, maxwidth=max_width, better=False)
        else:
            oembed = client.oembed(url, better=False)

        # Check for error
        if oembed.get('error'):
            if oembed['error_code'] in [401, 403]:
                raise AccessDeniedEmbedlyException
            elif oembed['error_code'] == 404:
                raise EmbedNotFoundException
            else:
                raise EmbedlyException

        # Convert photos into HTML
        if oembed['type'] == 'photo':
            html = '<img src="%s" />' % (oembed['url'], )
        else:
            html = oembed.get('html')

        # Return embed as a dict
        return {
            'title':
            oembed['title'] if 'title' in oembed else '',
            'author_name':
            oembed['author_name'] if 'author_name' in oembed else '',
            'provider_name':
            oembed['provider_name'] if 'provider_name' in oembed else '',
            'type':
            oembed['type'],
            'thumbnail_url':
            oembed.get('thumbnail_url'),
            'width':
            oembed.get('width'),
            'height':
            oembed.get('height'),
            'html':
            html,
        }
Exemple #24
0
def embedly(url, max_width=None, key=None):
    from embedly import Embedly

    # Get embedly key
    if key is None:
        try:
            key = settings.WAGTAILEMBEDS_EMBEDLY_KEY
        except AttributeError:
            key = settings.EMBEDLY_KEY
            warnings.warn(
                "EMBEDLY_KEY is now deprecated. Use WAGTAILEMBEDS_EMBEDLY_KEY instead",
                RemovedInWagtail14Warning)

    # Get embedly client
    client = Embedly(key=key)

    # Call embedly
    if max_width is not None:
        oembed = client.oembed(url, maxwidth=max_width, better=False)
    else:
        oembed = client.oembed(url, better=False)

    # Check for error
    if oembed.get('error'):
        if oembed['error_code'] in [401, 403]:
            raise AccessDeniedEmbedlyException
        elif oembed['error_code'] == 404:
            raise EmbedNotFoundException
        else:
            raise EmbedlyException

    # Convert photos into HTML
    if oembed['type'] == 'photo':
        html = '<img src="%s" />' % (oembed['url'], )
    else:
        html = oembed.get('html')

    # Return embed as a dict
    return {
        'title': oembed['title'] if 'title' in oembed else '',
        'author_name':
        oembed['author_name'] if 'author_name' in oembed else '',
        'provider_name':
        oembed['provider_name'] if 'provider_name' in oembed else '',
        'type': oembed['type'],
        'thumbnail_url': oembed.get('thumbnail_url'),
        'width': oembed.get('width'),
        'height': oembed.get('height'),
        'html': html,
    }
Exemple #25
0
    def find_embed(self, url, max_width=None, key=None):
        from embedly import Embedly

        # Get embedly key
        if key is None:
            key = self.get_key()

        # Get embedly client
        client = Embedly(key=key)

        # Call embedly
        if max_width is not None:
            oembed = client.oembed(url, maxwidth=max_width, better=False)
        else:
            oembed = client.oembed(url, better=False)

        # Check for error
        if oembed.get("error"):
            if oembed["error_code"] in [401, 403]:
                raise AccessDeniedEmbedlyException
            elif oembed["error_code"] == 404:
                raise EmbedNotFoundException
            else:
                raise EmbedlyException

        # Convert photos into HTML
        if oembed["type"] == "photo":
            html = '<img src="%s" alt="">' % (oembed["url"], )
        else:
            html = oembed.get("html")

        # Return embed as a dict
        return {
            "title":
            oembed["title"] if "title" in oembed else "",
            "author_name":
            oembed["author_name"] if "author_name" in oembed else "",
            "provider_name":
            oembed["provider_name"] if "provider_name" in oembed else "",
            "type":
            oembed["type"],
            "thumbnail_url":
            oembed.get("thumbnail_url"),
            "width":
            oembed.get("width"),
            "height":
            oembed.get("height"),
            "html":
            html,
        }
def embed_replace(match, maxwidth=None):
    url = match.group(1)

    key = make_cache_key(url, maxwidth)
    cached_html = cache.get(key)

    if cached_html:
        return cached_html

    # call embedly API
    client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
    if maxwidth:
        oembed = client.oembed(url, maxwidth=maxwidth)
    else:
        oembed = client.oembed(url)

    # check database
    if oembed.error:
        try:
            html = SavedEmbed.objects.get(url=url, maxwidth=maxwidth).html
            cache.set(key, html)
            return html
        except SavedEmbed.DoesNotExist:
            err_code = (oembed.data['error_code']
                        if 'error_code' in oembed.data else 'Unknown')
            LOG.warn('Error fetching %s (%s)', url, err_code)
            return url

    # save result to database
    row, created = SavedEmbed.objects.get_or_create(url=url, maxwidth=maxwidth,
                defaults={'type': oembed.type})

    if oembed.type == 'photo':
        html = '<img src="%s" ' % oembed.url
        if maxwidth:
            html += 'width="%s" />' % maxwidth
        else:
            html += 'width="%s" height="%s" />' % (oembed.width, oembed.height)
    else:
        html = oembed.html

    if html:
        row.html = html
        row.last_updated = datetime.now()
        row.save()

    # set cache
    cache.set(key, html, 86400)
    return html
def wrap_with_embedly(url):
    logger.debug(u"calling embedly for {url}".format(
        url=url))

    client = Embedly(os.getenv("EMBEDLY_API_KEY"))
    # if not client.is_supported(url):
    #     return None

    response_dict = client.oembed(url, maxwidth=580, width=580)
    try:
        html = response_dict["html"]
        html = html.replace("http://docs.google", "https://docs.google")
        return html
    except (KeyError, AttributeError):
        return None
Exemple #28
0
def embedly(url, max_width=None, key=None):
    from embedly import Embedly

    # Get embedly key
    if key is None:
        try:
            key = settings.WAGTAILEMBEDS_EMBEDLY_KEY
        except AttributeError:
            key = settings.EMBEDLY_KEY
            warnings.warn(
                "EMBEDLY_KEY is now deprecated. Use WAGTAILEMBEDS_EMBEDLY_KEY instead",
                RemovedInWagtail14Warning)

    # Get embedly client
    client = Embedly(key=key)

    # Call embedly
    if max_width is not None:
        oembed = client.oembed(url, maxwidth=max_width, better=False)
    else:
        oembed = client.oembed(url, better=False)

    # Check for error
    if oembed.get('error'):
        if oembed['error_code'] in [401, 403]:
            raise AccessDeniedEmbedlyException
        elif oembed['error_code'] == 404:
            raise EmbedNotFoundException
        else:
            raise EmbedlyException

    # Convert photos into HTML
    if oembed['type'] == 'photo':
        html = '<img src="%s" />' % (oembed['url'], )
    else:
        html = oembed.get('html')

    # Return embed as a dict
    return {
        'title': oembed['title'] if 'title' in oembed else '',
        'author_name': oembed['author_name'] if 'author_name' in oembed else '',
        'provider_name': oembed['provider_name'] if 'provider_name' in oembed else '',
        'type': oembed['type'],
        'thumbnail_url': oembed.get('thumbnail_url'),
        'width': oembed.get('width'),
        'height': oembed.get('height'),
        'html': html,
    }
Exemple #29
0
class Content(ParseObject):
    # Class Properties
    _embedly_client = Embedly("74388f950f1d4a4f965cd185bfff2df3")
    _parse_client = parse_rest.connection.register(
        "OLjnAy2bGdU2J1AcQ118Ay5MV20ekLPqCb8U299K",
        "9rTz13ih8HEXNqnzT5jvBR0ExfkFNSl3kJA2J7G8")

    # Initializers
    def __init__(self, source_url):
        ParseObject.__init__(self)

        obj = Content._embedly_client.oembed(source_url)

        self.object_description = obj[
            'description'] if 'description' in obj else None
        self.title = obj['title'] if 'title' in obj else None
        self.url = source_url
        self.thumbnail_url = obj[
            'thumbnail_url'] if 'thumbnail_url' in obj else None
        self.provider_name = obj[
            'provider_name'] if 'provider_name' in obj else None
        self.type = obj['type'] if 'type' in obj else 'unknown'

    # Push Handlers
    def push(self):
        message = "Your next Mystery Box is ready to be opened!"
        ParsePush.message(message, channels=[""])
Exemple #30
0
    def clean(self):
        # http://embed.ly/docs/api/extract/endpoints/1/extract#error-codes
        self.data = {}
        if settings.DJANGOCMS_EMBED_API_KEY is None:
            msg = _(
                'DJANGOCMS_EMBED_API_KEY is not defined in the project settings.'
            )
            logger.error(msg)
            raise ImproperlyConfigured(msg)

        client = Embedly(settings.DJANGOCMS_EMBED_API_KEY)

        try:
            data = client.extract(self.url)
        except ValueError, e:
            raise ValidationError(str(e))
Exemple #31
0
def get_embed_embedly(url, max_width=None):
    # Check database
    try:
        return Embed.objects.get(url=url, max_width=max_width)
    except Embed.DoesNotExist:
        pass

    try:
        # Call embedly API
        client = Embedly(key=settings.EMBEDLY_KEY)
    except AttributeError:
        return None
    if max_width is not None:
        oembed = client.oembed(url, maxwidth=max_width, better=False)
    else:
        oembed = client.oembed(url, better=False)

    # Check for error
    if oembed.get('error'):
        return None

    # Save result to database
    row, created = Embed.objects.get_or_create(
        url=url,
        max_width=max_width,
        defaults={
            'type': oembed['type'],
            'title': oembed['title'],
            'thumbnail_url': oembed.get('thumbnail_url'),
            'width': oembed.get('width'),
            'height': oembed.get('height')
        }
    )

    if oembed['type'] == 'photo':
        html = '<img src="%s" />' % (oembed['url'], )
    else:
        html = oembed.get('html')

    if html:
        row.html = html
        row.last_updated = datetime.now()
        row.save()

    # Return new embed
    return row
 def __init__(self):
     try:
         key = getattr(settings, 'EMBEDLY_KEY')
     except AttributeError:
         from django.core.exceptions import ImproperlyConfigured
         raise ImproperlyConfigured(
             '%s requires an API key be specified in settings' %
             type(self).__name__)
     self.client = EmbedlyAPI(key)
Exemple #33
0
def embed_replace(match, maxwidth=None):
    url = match.group(1)

    key = make_cache_key(url, maxwidth)
    cached_html = cache.get(key)

    if cached_html:
        return cached_html

    # call embedly API
    client = Embedly(key=settings.EMBEDLY_KEY, user_agent=USER_AGENT)
    if maxwidth:
        oembed = client.oembed(url, maxwidth=maxwidth)
    else:
        oembed = client.oembed(url)

    # check database
    if oembed.error:
        try:
            html = SavedEmbed.objects.get(url=url, maxwidth=maxwidth).html
            cache.set(key, html)
            return html
        except SavedEmbed.DoesNotExist:
            return "Error embedding %s" % url

    # save result to database
    row, created = SavedEmbed.objects.get_or_create(url=url, maxwidth=maxwidth, defaults={"type": oembed.type})

    if oembed.type == "photo":
        html = u'<img src="%s" width="%s" height="%s" />' % (oembed.url, oembed.width, oembed.height)
    elif oembed.type == "link":
        html = u'Link to: <a href="{url}">{title}</a>'.format(url=oembed.url, title=oembed.title)
    else:
        html = oembed.html

    if html:
        row.html = html
        row.last_updated = datetime.now()
        row.save()

    # set cache
    cache.set(key, html, 86400)
    return html
Exemple #34
0
    def find_embed(self, url, max_width=None, key=None):
        from embedly import Embedly

        # Get embedly key
        if key is None:
            key = self.get_key()

        # Get embedly client
        client = Embedly(key=key)

        # Call embedly
        if max_width is not None:
            oembed = client.oembed(url, maxwidth=max_width, better=False)
        else:
            oembed = client.oembed(url, better=False)

        # Check for error
        if oembed.get('error'):
            if oembed['error_code'] in [401, 403]:
                raise AccessDeniedEmbedlyException
            elif oembed['error_code'] == 404:
                raise EmbedNotFoundException
            else:
                raise EmbedlyException

        # Convert photos into HTML
        if oembed['type'] == 'photo':
            html = '<img src="%s" />' % (oembed['url'], )
        else:
            html = oembed.get('html')

        # Return embed as a dict
        return {
            'title': oembed['title'] if 'title' in oembed else '',
            'author_name': oembed['author_name'] if 'author_name' in oembed else '',
            'provider_name': oembed['provider_name'] if 'provider_name' in oembed else '',
            'type': oembed['type'],
            'thumbnail_url': oembed.get('thumbnail_url'),
            'width': oembed.get('width'),
            'height': oembed.get('height'),
            'html': html,
        }
Exemple #35
0
def embedly(url, max_width=None, key=None):
    from embedly import Embedly

    # Get embedly key
    if key is None:
        key = settings.EMBEDLY_KEY

    # Get embedly client
    client = Embedly(key=key)

    # Call embedly
    if max_width is not None:
        oembed = client.oembed(url, maxwidth=max_width, better=False)
    else:
        oembed = client.oembed(url, better=False)

    # Check for error
    if oembed.get("error"):
        if oembed["error_code"] in [401, 403]:
            raise AccessDeniedEmbedlyException
        elif oembed["error_code"] == 404:
            raise EmbedNotFoundException
        else:
            raise EmbedlyException

    # Convert photos into HTML
    if oembed["type"] == "photo":
        html = '<img src="%s" />' % (oembed["url"],)
    else:
        html = oembed.get("html")

    # Return embed as a dict
    return {
        "title": oembed["title"] if "title" in oembed else "",
        "author_name": oembed["author_name"] if "author_name" in oembed else "",
        "provider_name": oembed["provider_name"] if "provider_name" in oembed else "",
        "type": oembed["type"],
        "thumbnail_url": oembed.get("thumbnail_url"),
        "width": oembed.get("width"),
        "height": oembed.get("height"),
        "html": html,
    }
Exemple #36
0
def replace(match):
    url = match.group('url')
    try:
        url_validate(url)
        expiration_date = datetime.now() - settings.EMBEDLY_CACHE_EXPIRES
        embedded_urls = EmbeddedUrl.objects.filter(original_url=url,
            created_on__gte=expiration_date).order_by('-created_on')
        embedded_url = None
        if embedded_urls.exists():
            embedded_url = embedded_urls[0]
        else:
            embedly_key = getattr(settings, 'EMBEDLY_KEY', False)
            if embedly_key:
                client = Embedly(embedly_key)
                obj = client.oembed(url)
                embedded_url = EmbeddedUrl(original_url=obj.original_url,
                    html=obj.html, extra_data=obj.dict)
                embedded_url.save()
        if embedded_url and embedded_url.html:
            return embedded_url.html
    except ValidationError:
        return '[embed:Invalid Url]'
    return DEFAULT_EMBED % (url, url)
Exemple #37
0
def get_embed_embedly(url, max_width=None):
    # Check database
    try:
        return Embed.objects.get(url=url, max_width=max_width)
    except Embed.DoesNotExist:
        pass

    client = Embedly(key=settings.EMBEDLY_KEY)
    
    if max_width is not None:
        oembed = client.oembed(url, maxwidth=max_width, better=False)
    else:
        oembed = client.oembed(url, better=False)

    # Check for error
    if oembed.get('error'):
        if oembed['error_code'] in [401,403]:
            raise AccessDeniedEmbedlyException
        elif oembed['error_code'] == 404:
            raise NotFoundEmbedlyException
        else:
            raise EmbedlyException

    return save_embed(url, max_width, oembed)
Exemple #38
0
def oembed_replace(srcurl=""):
    r = ""
    client = Embedly()
    obj = client.oembed(srcurl, maxwidth=480)
    # for idx,item in enumerate(oembed_json):
    try:
        title = obj["title"]
    except KeyError:
        title = ""
    try:
        url = obj["url"]
    except KeyError:
        url = ""
    try:
        thumbnail_url = obj["thumbnail_url"]
    except KeyError:
        thumbnail_url = ""

    if obj["type"] == "photo":
        r = (
            ' <a href="http://'
            + srcurl
            + '" target="_blank"><img style="width:480px" src="'
            + url
            + '" alt="'
            + title
            + '"/></a>'
        )
    if obj["type"] == "video":
        r = " " + obj["html"]
    if obj["type"] == "rich":
        r = " " + obj["html"]
    if obj["type"] == "link":
        r = ' <a href="' + url + '">' + title + "</a>"

    return r
class EmbedlyBackend(object):
    """
    The response object from oembed() is a dict that should look like this:
        response.__dict__ ->
        {'data': {'type': 'error', 'error_code': 400, 'error': True}, 'method': 'oembed', 'original_url': 'bad_url'}
        - or -
        {'data': {u'provider_url': u'http://vimeo.com/', u'description': ...}, 'method': 'oembed', 'original_url': 'http://vimeo.com/1111'}

    """
    response_class = EmbedlyResponse

    def __init__(self):
        try:
            key = getattr(settings, 'EMBEDLY_KEY')
        except AttributeError:
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(
                '%s requires an API key be specified in settings' %
                type(self).__name__)
        self.client = EmbedlyAPI(key)

    @proxy
    def call(self, url):
        if not url:
            return None

        logger.debug("Embedly call to oembed('%s')" % url)
        try:
            response = self.client.oembed(url)
        except ServerNotFoundError:
            #PY3 use PEP 3134 exception chaining
            import sys
            exc_cls, msg, trace = sys.exc_info()
            raise (InvalidResponseError,
                   "%s: %s" % (exc_cls.__name__, msg),
                   trace)

        response = self.wrap_response_data(
            getattr(response, 'data', None), fresh=True)
        if not response.is_valid():
            logger.warn("%s error: %s" %
                        (type(response).__name__, response._data))
        return response

    @proxy
    def wrap_response_data(self, data, **kwargs):
        return self.response_class(data, **kwargs)
Exemple #40
0
    def handle(self, *args, **options):
        client = Embedly(key=os.environ.get('EMBEDLY_KEY'),
                         timeout=settings.EMBEDLY_TIMEOUT)

        qs = (
            Video.objects
            # skip source-less videos
            .filter(~Q(source_url='') & ~Q(source_url__isnull=True)).filter(
                # attempt to obtain embed code for videos
                Q(embed='') |
                # or fix youtube videos with broken embed code
                (Q(source_url__contains='youtube.com')
                 & ~Q(embed__contains='embed'))))

        for video in qs:
            video.fetch_embed(client=client)
            video.save()
            self.stdout.write(u'Updated %s' % video.title)
Exemple #41
0
def fetch_embed(self, client=None):
    """
    Update the embed data fields (embed and thumbnail_url) using embedly.

    :param client: Embedly instance
    :return:
    """
    if not 'EMBEDLY_KEY' in os.environ:
        return
    client = client or Embedly(key=os.environ['EMBEDLY_KEY'],
                               timeout=settings.EMBEDLY_TIMEOUT)
    try:
        data = client.oembed(self.source_url).data
    except socket.timeout:
        return
    # check for errors
    if data['type'] not in ('video', ):
        return
    self.embed = data['html']
    self.thumbnail_url = data.get('thumbnail_url', None)
Exemple #42
0
class UrlPreview(object):

    FIELDS = [
        'author_name', 'description', 'provider_name', 'provider_url',
        'thumbnail_url', 'thumbnail_width', 'thumbnail_height', 'title', 'url'
    ]

    def __init__(self):
        self.client = Embedly(KEY)

    def getPreview(self, url):
        obj = self.client.oembed(url)

        if obj.get('error'):
            return ''

        # fill in some blanks
        for field in self.FIELDS:
            if field not in obj.data:
                obj.data[field] = ''

        return PREVIEW_HTML.format(**obj.data)

    def getData(self, url):
        return self.client.oembed(url)

    def getDataAsText(self, url):
        obj = self.getData(url)
        keys = sorted(obj.data.keys())
        o = ''
        for k in keys:
            o += '%-17s: %s' % (k, obj.data[k]) + '\n'
        return o

    def run(self):
        '''Command line interface'''

        from vlib.cli import CLI

        commands = ['preview_html <url>', 'get_data <url>']
        options = {}
        self.cli = CLI(self.process, commands, options)
        self.cli.process()

    def process(self, *args):
        '''Process Command line requests'''

        from vlib.utils import validate_num_args

        args = list(args)
        cmd = args.pop(0)

        if cmd == 'preview_html':
            validate_num_args('preview_html', 1, args)
            url = args.pop(0)
            return self.getPreview(url)

        elif cmd == 'get_data':
            validate_num_args('get_data', 1, args)
            url = args.pop(0)
            return self.getDataAsText(url)

        else:
            raise UrlPreviewError('Unrecognized command: %s' % cmd)
Exemple #43
0

# session for interactions outside of app context.
def gen_session():
    return scoped_session(sessionmaker(bind=engine))

db_session = gen_session()
db_session.execute('SET TIMEZONE TO UTC')


# redis connection
rds = redis.from_url(settings.REDIS_URL)

# task queues
queues = {k: Queue(k, connection=rds) for k in TASK_QUEUE_NAMES}

# migrations
migrate = Migrate(app, db)

# gzip compression
Compress(app)

# optional bitly api for shortening
if settings.BITLY_ENABLED:
    bitly_api = bitly.Connection(
        access_token=settings.BITLY_ACCESS_TOKEN)

# optional embedly api for shortening
if settings.EMBEDLY_ENABLED:
    embedly_api = Embedly(settings.EMBEDLY_API_KEY)
Exemple #44
0
 def set_link_data(self):
     # connect to embedly + get url data
     client = Embedly(EMBEDLY_KEY)
     self.data = client.oembed(self.url).__dict__['data']
     self.name = self.data['title']
Exemple #45
0
def get_client(key):
    if not key:
        return None
    return Embedly(key)
Exemple #46
0
 def __init__(self, url):
     self.url = url
     client = Embedly(settings.EMBEDLY_API_KEY)
     self.obj = client.extract(self.url)
Exemple #47
0
# using embedly with python
import csv
import itertools
import json
import requests
from urlparse import urljoin

# below currently works in the command line, but not sure how to translate it into this python document, run it and have it work

from embedly import Embedly

# key = 'f2f84ff5013b443ab711b204590d9aa2'

client = Embedly('f2f84ff5013b443ab711b204590d9aa2')
result = client.extract(
    'https://medium.com/message/yes-to-the-dress-5ec06c06aca4')

article = {}
article["url"] = result["url"]
article["headline"] = result["title"]
article["description"] = result["description"]
article["content"] = result["content"]

print "URL:", result["url"]
print "Headline:", result["title"]
print "Description:", result["description"]
print "Article:", result["content"]

subjects_file = open("../articles/dressarticle.json", "w")
print >> json.dump(article, subjects_file, indent=4)
Exemple #48
0
 def __init__(self):
     self.client = Embedly(KEY)
Exemple #49
0
from config import SECRET_KEY, GOOGLE_ID, GOOGLE_SECRET, EMBEDLY_KEY, CELERY_BROKER, REDIS_CACHE_URL
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_oauthlib.client import OAuth
from embedly import Embedly
from celery import Celery
from config import CELERY_BROKER
import redis

app = Flask(__name__)
app.config.from_object('config')
app.secret_key = SECRET_KEY

db = SQLAlchemy(app)

cli = Embedly(EMBEDLY_KEY)

redis_cache = redis.from_url(REDIS_CACHE_URL)

celery = Celery('app', broker=CELERY_BROKER)

oauth = OAuth(app)
google = oauth.remote_app(
    'google',
    consumer_key=GOOGLE_ID,
    consumer_secret=GOOGLE_SECRET,
    request_token_params={'scope': 'email'},
    base_url='https://www.googleapis.com/oauth2/v1/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://accounts.google.com/o/oauth2/token',
Exemple #50
0
from embedly import Embedly

from chappy.config import Config

client = Embedly(Config.EMBEDLY_API_KEY)


def get_video_metadata(video_url):
    data = client.extract(video_url)
    data_dict = {
        'source': data.get('provider_display'),
        'length': data.get('media').get('duration'),
        'html': data.get('media').get('html')
    }
    return data_dict


def get_img_metadata(img_url):
    data = client.extract(img_url)
    data_dict = {
        'height': data.get('media').get('height'),
        'width': data.get('media').get('width'),
    }
    return data_dict
Exemple #51
0
from django import forms

from tendenci.apps.videos.models import Video
from tendenci.libs.tinymce.widgets import TinyMCE
from tendenci.apps.perms.forms import TendenciBaseForm
from embedly import Embedly

# Create Embedly instance
client = Embedly("438be524153e11e18f884040d3dc5c07")


class VideoForm(TendenciBaseForm):

    description = forms.CharField(required=False,
                                  widget=TinyMCE(
                                      attrs={'style': 'width:100%'},
                                      mce_attrs={
                                          'storme_app_label':
                                          Video._meta.app_label,
                                          'storme_model':
                                          Video._meta.model_name.lower()
                                      }))

    status_detail = forms.ChoiceField(choices=(('active', 'Active'),
                                               ('pending', 'Pending')))

    clear_image = forms.BooleanField(required=False)

    class Meta:
        model = Video
        fields = (
Exemple #52
0
@app.route('/search/lol', methods=['GET', 'POST'])
def wew():
    form = forms.SearchTrace(request.form)
    trends = ''
    if request.method == 'POST' and form.validate():
        key = request.form["searchTrace"]
        trends = models.Search.query.filter_by(tweet=key).order_by(
            models.Search.id.desc())
        print trends
    else:
        trends = models.Search.query.order_by(models.Search.id.desc())
    return render_template('trace.html', result=trends, form=form)


key = '29fd40eda47344aa93268b96a3e86879'
client = Embedly(key)


@app.route('/track/<path:key>')
def lol(key):
    api = auth()
    for item in api.request('statuses/filter', {'track': key}):
        res = item['text'] if 'text' in item else item
        retweet = item['retweet_count'] if 'text' in item else item
        favorites = item['favorite_count'] if 'text' in item else item
        name = item['user']['screen_name'] if 'text' in item else item
        real = item['user']['name'] if 'text' in item else item
        pic = item['user'][
            'profile_image_url_https'] if 'text' in item else item
        followers = item['user']['followers_count'] if 'text' in item else item
        date = item['created_at'] if 'text' in item else item
Exemple #53
0
from rest_framework.renderers import JSONRenderer
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.utils import timezone
from django.contrib.admin.views.decorators import staff_member_required
from embedly import Embedly
from settings import EMBEDLY_KEY
from notifications import notify
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from forms import UsernameForm
from django.template.loader import render_to_string
from django.template import RequestContext
from django.core.urlresolvers import reverse
embedly_client = Embedly(EMBEDLY_KEY)


def index(request):
    """ List all topics. """
    if 'login_prefix' in request.session:
        del request.session['login_prefix']
    TOPICS_PER_PAGE = 6

    paginator = Paginator(Topic.objects.filter(hidden=False).order_by(
        '-featured', '-pinned', '-last_post'), TOPICS_PER_PAGE)

    page = request.GET.get('page')

    if request.user.is_authenticated():
        p = request.user.profile
Exemple #54
0
def get_embedly_client():
    api_key = get_setting('module', 'videos', 'embedly_apikey')
    if not api_key:
        api_key = "438be524153e11e18f884040d3dc5c07"
    return Embedly(api_key)