mirror of
https://github.com/zulip/zulip.git
synced 2025-11-15 03:11:54 +00:00
There seems to have been a confusion between two different uses of the word “optional”: • An optional parameter may be omitted and replaced with a default value. • An Optional type has None as a possible value. Sometimes an optional parameter has a default value of None, or None is otherwise a meaningful value to provide, in which case it makes sense for the optional parameter to have an Optional type. But in other cases, optional parameters should not have Optional type. Fix them. Signed-off-by: Anders Kaseorg <anders@zulip.com>
51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
import json
|
|
from typing import Any, Dict, Optional
|
|
|
|
from pyoembed import PyOembedException, oEmbed
|
|
|
|
|
|
def get_oembed_data(url: str,
|
|
maxwidth: int=640,
|
|
maxheight: int=480) -> Optional[Dict[str, Any]]:
|
|
try:
|
|
data = oEmbed(url, maxwidth=maxwidth, maxheight=maxheight)
|
|
except (PyOembedException, json.decoder.JSONDecodeError):
|
|
return None
|
|
|
|
oembed_resource_type = data.get('type', '')
|
|
image = data.get('url', data.get('image'))
|
|
thumbnail = data.get('thumbnail_url')
|
|
html = data.pop('html', '')
|
|
if oembed_resource_type == 'photo' and image:
|
|
return dict(
|
|
oembed=True,
|
|
image=image,
|
|
type=oembed_resource_type,
|
|
title=data.get('title'),
|
|
description=data.get('description'),
|
|
)
|
|
|
|
if oembed_resource_type == 'video' and html and thumbnail:
|
|
return dict(
|
|
oembed=True,
|
|
image=thumbnail,
|
|
type=oembed_resource_type,
|
|
html=strip_cdata(html),
|
|
title=data.get('title'),
|
|
description=data.get('description'),
|
|
)
|
|
|
|
# Otherwise, start with just the embed type.
|
|
return dict(
|
|
type=oembed_resource_type,
|
|
title=data.get('title'),
|
|
description=data.get('description'),
|
|
)
|
|
|
|
def strip_cdata(html: str) -> str:
|
|
# Work around a bug in SoundCloud's XML generation:
|
|
# <html><![CDATA[<iframe ...></iframe>]]></html>
|
|
if html.startswith('<![CDATA[') and html.endswith(']]>'):
|
|
html = html[9:-3]
|
|
return html
|