Skip to content

Commit 7b87b02

Browse files
committed
Encode filename to system locale
1 parent 9f32ac7 commit 7b87b02

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

pafy/backend_shared.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from . import __version__, g
2323
from .pafy import call_gdata
2424
from .playlist import get_playlist2
25+
from .util import xenc
2526

2627
dbg = logging.debug
2728

@@ -454,7 +455,7 @@ def generate_filename(self, meta=False, max_length=None):
454455
filename = filename[:max_length-3] + '...'
455456

456457
filename += "." + self.extension
457-
return filename
458+
return xenc(filename)
458459

459460
@property
460461
def rawbitrate(self):

pafy/util.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
import sys
3+
import os
34

45
if sys.version_info[:2] >= (3, 0):
56
# pylint: disable=E0611,F0401,I0011
@@ -12,6 +13,11 @@
1213

1314
from . import g
1415

16+
17+
mswin = os.name == "nt"
18+
not_utf8_environment = mswin or "UTF-8" not in sys.stdout.encoding
19+
20+
1521
class GdataError(Exception):
1622
"""Gdata query failed."""
1723
pass
@@ -35,3 +41,22 @@ def call_gdata(api, qs):
3541
raise GdataError(errmsg)
3642

3743
return json.loads(data)
44+
45+
46+
def utf8_replace(txt):
47+
"""
48+
Replace unsupported characters in unicode string.
49+
50+
:param txt: text to filter
51+
:type txt: str
52+
:returns: Unicode text without any characters unsupported by locale
53+
:rtype: str
54+
"""
55+
sse = sys.stdout.encoding
56+
txt = txt.encode(sse, "replace").decode(sse)
57+
return txt
58+
59+
60+
def xenc(stuff):
61+
""" Replace unsupported characters. """
62+
return utf8_replace(stuff) if not_utf8_environment else stuff

0 commit comments

Comments
 (0)