2019-09-07 12:24:59 +02:00
|
|
|
import html
|
2018-03-13 00:33:39 +01:00
|
|
|
import re
|
|
|
|
import unicodedata
|
|
|
|
|
|
|
|
|
|
|
|
def ensure_unicode(s):
|
|
|
|
"""
|
|
|
|
Ensure string is a unicode string. If it isn't it assumed it is
|
|
|
|
utf-8 and decodes it to a unicode string.
|
|
|
|
"""
|
|
|
|
if isinstance(s, bytes):
|
2019-08-25 00:27:31 +02:00
|
|
|
s = s.decode("utf-8", "replace")
|
2018-03-13 00:33:39 +01:00
|
|
|
return s
|
|
|
|
|
|
|
|
|
|
|
|
def decode_html_entities(s):
|
|
|
|
"""
|
|
|
|
Replaces html entities with the character they represent.
|
|
|
|
|
|
|
|
>>> print(decode_html_entities("<3 &"))
|
|
|
|
<3 &
|
|
|
|
"""
|
|
|
|
|
|
|
|
def unesc(m):
|
2019-09-07 12:24:59 +02:00
|
|
|
return html.unescape(m.group())
|
2019-08-25 00:27:31 +02:00
|
|
|
|
|
|
|
return re.sub(r"(&[^;]+;)", unesc, ensure_unicode(s))
|
2018-03-13 00:33:39 +01:00
|
|
|
|
|
|
|
|
|
|
|
def filenamify(title):
|
|
|
|
"""
|
|
|
|
Convert a string to something suitable as a file name. E.g.
|
|
|
|
|
|
|
|
Matlagning del 1 av 10 - Räksmörgås | SVT Play
|
|
|
|
-> matlagning.del.1.av.10.-.raksmorgas.svt.play
|
|
|
|
"""
|
|
|
|
# ensure it is unicode
|
|
|
|
title = ensure_unicode(title)
|
|
|
|
|
|
|
|
# NFD decomposes chars into base char and diacritical mark, which
|
|
|
|
# means that we will get base char when we strip out non-ascii.
|
2019-08-25 00:27:31 +02:00
|
|
|
title = unicodedata.normalize("NFD", title)
|
2018-03-13 00:33:39 +01:00
|
|
|
|
|
|
|
# Convert to lowercase
|
|
|
|
# Drop any non ascii letters/digits
|
|
|
|
# Drop any leading/trailing whitespace that may have appeared
|
2019-08-25 00:27:31 +02:00
|
|
|
title = re.sub(r"[^a-z0-9 .-]", "", title.lower().strip())
|
2018-03-13 00:33:39 +01:00
|
|
|
|
|
|
|
# Replace whitespace with dot
|
2019-08-25 00:27:31 +02:00
|
|
|
title = re.sub(r"\s+", ".", title)
|
|
|
|
title = re.sub(r"\.-\.", "-", title)
|
2018-03-13 00:33:39 +01:00
|
|
|
|
|
|
|
return title
|
2018-05-12 15:38:10 +02:00
|
|
|
|
|
|
|
|
|
|
|
def exclude(config, name):
|
|
|
|
if config.get("exclude"):
|
|
|
|
excludes = config.get("exclude").split(",")
|
|
|
|
for exclude in excludes:
|
|
|
|
if exclude in name:
|
|
|
|
return True
|
|
|
|
return False
|