from .interfaces import IStatusUpdate
from .interfaces import IURLPreview
from requests.exceptions import Timeout
from zope.component import adapter
from zope.interface import implementer

import lxml.html
import requests


@implementer(IURLPreview)
@adapter(IStatusUpdate)
class URLPreview:
    def __init__(self, context):
        self.context = context

    def generate_preview(self, url):
        try:
            resp = requests.get(url, timeout=2)
        except Timeout:
            return []
        doc = lxml.html.fromstring(resp.content)
        links = doc.xpath("//img/@src")
        ogs = doc.xpath('//meta[@property="og:image"]/@content')
        return ogs + links
