Skip to content

Commit

Permalink
Late summer cleaning (#209)
Browse files Browse the repository at this point in the history
* Update changelog

* Re-arrange stuff in cli.py

* Use format strings throughout codebase
  • Loading branch information
theychx authored Aug 18, 2019
1 parent 2f47847 commit 0f9c9a3
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 42 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

### Fixes

* Adapt write_config to "new" get_chromecast (#208) [theychx]

* Try to eliminate spurious error msgs when seeking (#194) [theychx]


Expand Down
2 changes: 1 addition & 1 deletion catt/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, name: str = "", ip_addr: str = "", lazy: bool = False) -> Non
self._create_cast()

def __repr__(self) -> str:
return "<CattDevice: %s>" % (self.name or self.ip_addr)
return "<CattDevice: {}>".format(self.name or self.ip_addr)

def _create_cast(self) -> None:
self._cast = get_chromecast_with_ip(self.ip_addr) if self.ip_addr else get_chromecast(self.name)
Expand Down
66 changes: 33 additions & 33 deletions catt/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def convert(self, value, param, ctx):
if (tlen > 1 and any(t > 59 for t in tdesc)) or tlen > 3:
raise ValueError
except ValueError:
self.fail("%s is not a valid time description." % value, param, ctx)
self.fail("{} is not a valid time description.".format(value))

tdesc.reverse()
return sum(tdesc[p] * 60 ** p for p in range(tlen))
Expand All @@ -42,7 +42,7 @@ def convert(self, value, param, ctx):
class YtdlOptParamType(click.ParamType):
def convert(self, value, param, ctx):
if "=" not in value:
self.fail("%s is not a valid key/value pair." % value, param, ctx)
self.fail("{} is not a valid key/value pair.".format(value))

ykey, yval = value.split("=", 1)
yval = {"true": True, "false": False}.get(yval.lower().strip(), yval)
Expand Down Expand Up @@ -74,6 +74,17 @@ def process_path(ctx, param, value):
return path


def process_subtitles(ctx, param, value):
if not value:
return None
pval = urlparse(value).path if "://" in value else value
if not pval.lower().endswith((".srt", ".vtt")):
raise CliError("Invalid subtitles format, only srt and vtt are supported")
if "://" not in value and not Path(value).is_file():
raise CliError("Subtitles file [{}] does not exist".format(value))
return value


def process_device(ctx, param, value):
"""
Resolve real device name when value is an alias.
Expand All @@ -88,6 +99,13 @@ def process_device(ctx, param, value):
return ctx.default_map["aliases"].get(value, value)


def create_server_thread(server_args):
thr = Thread(target=serve_file, args=server_args)
thr.setDaemon(True)
thr.start()
return thr


CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])


Expand All @@ -113,24 +131,6 @@ def write_config(settings):
raise CliError("No device specified")


def create_server_thread(server_args):
thr = Thread(target=serve_file, args=server_args)
thr.setDaemon(True)
thr.start()
return thr


def process_subtitles(ctx, param, value):
if not value:
return None
pval = urlparse(value).path if "://" in value else value
if not pval.lower().endswith((".srt", ".vtt")):
raise CliError("Invalid subtitles format, only srt and vtt are supported")
if "://" not in value and not Path(value).is_file():
raise CliError("Subtitles file [{}] does not exist".format(value))
return value


@cli.command(short_help="Send a video to a Chromecast for playing.")
@click.argument("video_url", callback=process_url)
@click.option("-s", "--subtitles", callback=process_subtitles, metavar="SUB", help="Specify a subtitles file.")
Expand Down Expand Up @@ -180,7 +180,7 @@ def cast(settings, video_url, subtitles, force_default, random_play, no_subs, no
stream.set_playlist_entry(entry)

if playlist_playback:
click.echo("Casting remote playlist %s..." % video_url)
click.echo("Casting remote playlist {}...".format(video_url))
video_id = stream.video_id or stream.playlist_all_ids[0]
cst.play_playlist(stream.playlist_id, video_id=video_id)
else:
Expand All @@ -190,8 +190,8 @@ def cast(settings, video_url, subtitles, force_default, random_play, no_subs, no
subs = SubsInfo(subtitles, stream.local_ip, stream.port + 1)
su_thr = create_server_thread((subs.file, subs.local_ip, subs.port, "text/vtt;charset=utf-8"))

click.echo("Casting %s file %s..." % ("local" if stream.is_local_file else "remote", video_url))
click.echo('Playing "%s" on "%s"...' % (stream.video_title, cst.cc_name))
click.echo("Casting {} file {}...".format("local" if stream.is_local_file else "remote", video_url))
click.echo('Playing "{}" on "{}"...'.format(stream.video_title, cst.cc_name))
if cst.info_type == "url":
cst.play_media_url(
stream.video_url,
Expand All @@ -216,7 +216,7 @@ def cast(settings, video_url, subtitles, force_default, random_play, no_subs, no
@click.pass_obj
def cast_site(settings, url):
cst = setup_cast(settings["device"], controller="dashcast", action="load_url", prep="app")
click.echo('Casting %s on "%s"...' % (url, cst.cc_name))
click.echo('Casting {} on "{}"...'.format(url, cst.cc_name))
cst.load_url(url)


Expand All @@ -228,7 +228,7 @@ def add(settings, video_url, play_next):
cst, stream = setup_cast(settings["device"], video_url=video_url, action="add", prep="control")
if cst.name != stream.extractor or not (stream.is_remote_file or stream.is_playlist_with_active_entry):
raise CliError("This url cannot be added to the queue")
click.echo('Adding video id "%s" to the queue.' % stream.video_id)
click.echo('Adding video id "{}" to the queue.'.format(stream.video_id))
if play_next:
cst.add_next(stream.video_id)
else:
Expand All @@ -242,7 +242,7 @@ def remove(settings, video_url):
cst, stream = setup_cast(settings["device"], video_url=video_url, action="remove", prep="control")
if cst.name != stream.extractor or not stream.is_remote_file:
raise CliError("This url cannot be removed from the queue")
click.echo('Removing video id "%s" from the queue.' % stream.video_id)
click.echo('Removing video id "{}" from the queue.'.format(stream.video_id))
cst.remove(stream.video_id)


Expand Down Expand Up @@ -354,7 +354,7 @@ def info(settings, json_output):
echo_json(info)
else:
for (key, value) in info.items():
click.echo("%s: %s" % (key, value))
click.echo("{}: {}".format(key, value))


@cli.command(short_help="Scan the local network and show all Chromecasts and their IPs.")
Expand Down Expand Up @@ -429,23 +429,23 @@ def restore(settings, path):

def print_status(status):
if status.get("title"):
click.echo("Title: %s" % status["title"])
click.echo("Title: {}".format(status["title"]))

if status.get("current_time"):
current = human_time(status["current_time"])
if status.get("duration"):
duration = human_time(status["duration"])
remaining = human_time(status["remaining"])
click.echo("Time: %s / %s (%s%%)" % (current, duration, status["progress"]))
click.echo("Remaining time: %s" % remaining)
click.echo("Time: {} / {} ({}%)".format(current, duration, status["progress"]))
click.echo("Remaining time: {}".format(remaining))
else:
click.echo("Time: %s" % current)
click.echo("Time: {}".format(current))

if status.get("player_state"):
click.echo("State: %s" % status["player_state"])
click.echo("State: {}".format(status["player_state"]))

if status.get("volume_level"):
click.echo("Volume: %s" % status["volume_level"])
click.echo("Volume: {}".format(status["volume_level"]))


def writeconfig(settings):
Expand Down
6 changes: 3 additions & 3 deletions catt/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def get_app(id_or_name, cast_type=None, strict=False, show_warning=False):
if not cast_type:
raise AppSelectionError("Cast type is needed for app selection")
elif cast_type not in app.supported_device_types:
msg = "The %s app is not available for this device" % app.name.capitalize()
msg = "The {} app is not available for this device".format(app.name.capitalize())
if strict:
raise AppSelectionError("{} (strict is set)".format(msg))
elif show_warning:
Expand All @@ -142,7 +142,7 @@ def get_app(id_or_name, cast_type=None, strict=False, show_warning=False):
def get_controller(cast, app, action=None, prep=None):
controller = {"youtube": YoutubeCastController, "dashcast": DashCastController}.get(app.name, DefaultCastController)
if action and action not in dir(controller):
raise ControllerError("This action is not supported by the %s controller" % app.name)
raise ControllerError("This action is not supported by the {} controller".format(app.name))
return controller(cast, app, prep=prep)


Expand Down Expand Up @@ -209,7 +209,7 @@ def clear(self):
class Cache(CattStore):
def __init__(self):
vhash = hashlib.sha1(__version__.encode()).hexdigest()[:8]
cache_path = Path(tempfile.gettempdir(), "catt_%s_cache" % vhash, "chromecast_hosts")
cache_path = Path(tempfile.gettempdir(), "catt_{}_cache".format(vhash), "chromecast_hosts")
super(Cache, self).__init__(cache_path)
self._create_store_dir()

Expand Down
6 changes: 3 additions & 3 deletions catt/http_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ def parse_byte_range(byte_range):

match = BYTE_RANGE_RE.match(byte_range)
if not match:
raise ValueError("Invalid byte range %s" % byte_range)
raise ValueError("Invalid byte range {}".format(byte_range))

first, last = [x and int(x) for x in match.groups()]
if last and last < first:
raise ValueError("Invalid byte range %s" % byte_range)
raise ValueError("Invalid byte range {}".format(byte_range))
return first, last


Expand Down Expand Up @@ -75,7 +75,7 @@ def do_GET(self): # noqa
self.send_response(200)
else:
self.send_response(206)
self.send_header("Content-Range", "bytes %s-%s/%s" % (first, last, stats.st_size))
self.send_header("Content-Range", "bytes {}-{}/{}".format(first, last, stats.st_size))

self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-type", content_type)
Expand Down
2 changes: 1 addition & 1 deletion catt/stream_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def video_title(self):
@property
def video_url(self):
if self.is_local_file:
return "http://%s:%s/?loaded_from_catt" % (self.local_ip, self.port)
return "http://{}:{}/?loaded_from_catt".format(self.local_ip, self.port)
elif self.is_remote_file or self.is_playlist_with_active_entry:
return self._get_stream_url(self._info)
else:
Expand Down
2 changes: 1 addition & 1 deletion catt/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def get_local_ip(host):
except ValueError:
continue
ipt = [(ip, adapter_ip.network_prefix) for ip in (aip, host)]
catt_net, cc_net = [ipaddress.ip_network("%s/%s" % ip, strict=False) for ip in ipt]
catt_net, cc_net = [ipaddress.ip_network("{0}/{1}".format(*ip), strict=False) for ip in ipt]
if catt_net == cc_net:
return aip
else:
Expand Down

0 comments on commit 0f9c9a3

Please sign in to comment.