url preview: Show inline images as previews for oEmbed photo pages.

This commit is contained in:
Puneeth Chaganti 2019-05-26 09:57:01 +05:30 committed by Tim Abbott
parent a1590c613e
commit c8cb785950
4 changed files with 49 additions and 0 deletions

View File

@ -368,7 +368,23 @@ def add_a(
desc_div = markdown.util.etree.SubElement(summary_div, "desc")
desc_div.set("class", "message_inline_image_desc")
def add_oembed_data(root: Element, link: str, extracted_data: Dict[str, Any]) -> bool:
type_ = extracted_data.get('type', '')
title = extracted_data.get('title', link)
if type_ == 'photo':
image = extracted_data.get('image')
if image:
add_a(root, image, link, title=title)
return True
return False
def add_embed(root: Element, link: str, extracted_data: Dict[str, Any]) -> None:
oembed = extracted_data.get('oembed', False)
if oembed and add_oembed_data(root, link, extracted_data):
return
container = markdown.util.etree.SubElement(root, "div")
container.set("class", "message_embed")

View File

@ -11,4 +11,10 @@ def get_oembed_data(url: str,
return None
data['image'] = data.get('thumbnail_url')
type_ = data.get('type', '')
image = data.get('url', data.get('image'))
if type_ == 'photo' and image:
# Add a key to identify oembed metadata as opposed to other metadata
data['oembed'] = True
return data

View File

@ -81,6 +81,8 @@ def get_link_embed_data(url: str,
# 2. Open Graph
# 3. Meta tags
data = get_oembed_data(url, maxwidth=maxwidth, maxheight=maxheight) or {}
if data.get('oembed'):
return data
response = requests.get(url, stream=True, headers=HEADERS, timeout=TIMEOUT)
if response.ok:
og_data = OpenGraphParser(response.text).extract_data()

View File

@ -59,6 +59,31 @@ class OembedTestCase(ZulipTestCase):
assert data is not None # allow mypy to infer data is indexable
self.assertEqual(data['title'], response_data['title'])
@mock.patch('pyoembed.requests.get')
def test_photo_provider(self, get: Any) -> None:
get.return_value = response = mock.Mock()
response.headers = {'content-type': 'application/json'}
response.ok = True
response_data = {
'type': 'photo',
'thumbnail_url': 'https://scontent.cdninstagram.com/t51.2885-15/n.jpg',
'url': 'https://scontent.cdninstagram.com/t51.2885-15/n.jpg',
'thumbnail_width': 640,
'thumbnail_height': 426,
'title': 'NASA',
'html': '<p>test</p>',
'version': '1.0',
'width': 658,
'height': 400}
response.text = ujson.dumps(response_data)
url = 'http://imgur.com/photo/158727223'
data = get_oembed_data(url)
self.assertIsInstance(data, dict)
self.assertIn('title', data)
assert data is not None # allow mypy to infer data is indexable
self.assertEqual(data['title'], response_data['title'])
self.assertTrue(data['oembed'])
@mock.patch('pyoembed.requests.get')
def test_error_request(self, get: Any) -> None:
get.return_value = response = mock.Mock()