Skip to content

Commit

Permalink
Merge pull request #1953 from glensc/ruff-format
Browse files Browse the repository at this point in the history
Linter: Apply ruff-format to all files
  • Loading branch information
glensc authored Jun 8, 2024
2 parents f483565 + 7d32ab1 commit d95293b
Show file tree
Hide file tree
Showing 54 changed files with 567 additions and 245 deletions.
19 changes: 5 additions & 14 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
name: flake8 Lint
name: Ruff Lint

on:
- pull_request

env:
DEFAULT_PYTHON: 3.8

jobs:
flake8-lint:
ruff:
runs-on: ubuntu-latest
name: Lint
steps:
- name: Check out source repository
uses: actions/checkout@v4
- name: Set up Python environment
uses: actions/setup-python@v5
with:
python-version: ${{ env.DEFAULT_PYTHON }}
- name: flake8 Lint
uses: py-actions/flake8@v2
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1

# vim:ts=2:sw=2:et
39 changes: 26 additions & 13 deletions plextraktsync/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ def wrap(*args, **kwargs):
try:
cmd(*args, **kwargs)
except EOFError as e:
raise ClickException(f"Program requested terminal, No terminal is connected: {e}")
raise ClickException(
f"Program requested terminal, No terminal is connected: {e}"
)
except ClickException as e:
from plextraktsync.factory import logging

Expand All @@ -48,17 +50,22 @@ def wrap(*args, **kwargs):
@click.option("--version", is_flag=True, help="Print version and exit")
@click.option("--no-cache", is_flag=True, help="Disable cache for Trakt HTTP requests")
@click.option("--no-progressbar", is_flag=True, help="Disable progressbar")
@click.option("--batch-delay", default=5, show_default=True,
help="Time in seconds between each collection batch submit to Trakt")
@click.option(
"--batch-delay",
default=5,
show_default=True,
help="Time in seconds between each collection batch submit to Trakt",
)
@click.option("--server", help="Plex Server name from servers.yml", metavar="NAME")
@click.pass_context
def cli(ctx,
version: bool,
no_cache: bool,
no_progressbar: bool,
batch_delay: int,
server: str,
):
def cli(
ctx,
version: bool,
no_cache: bool,
no_progressbar: bool,
batch_delay: int,
server: str,
):
"""
Plex-Trakt-Sync is a two-way-sync between trakt.tv and Plex Media Server
"""
Expand All @@ -76,7 +83,9 @@ def cli(ctx,

if not ctx.invoked_subcommand:
logger = factory.logger
logger.warning('plextraktsync without command is deprecated. Executing "plextraktsync sync"')
logger.warning(
'plextraktsync without command is deprecated. Executing "plextraktsync sync"'
)
sync()


Expand Down Expand Up @@ -186,7 +195,9 @@ def plex_login():
@click.option(
"--sync",
"sync_option",
type=click.Choice(["all", "movies", "tv", "shows", "watchlist"], case_sensitive=False),
type=click.Choice(
["all", "movies", "tv", "shows", "watchlist"], case_sensitive=False
),
default="all",
show_default=True,
help="Specify what to sync",
Expand Down Expand Up @@ -331,7 +342,9 @@ def watched_shows():


@command()
@click.option("--urls-expire-after", is_flag=True, help="Print urls_expire_after configuration")
@click.option(
"--urls-expire-after", is_flag=True, help="Print urls_expire_after configuration"
)
@click.option("--edit", is_flag=True, help="Open config file in editor")
@click.option("--locate", is_flag=True, help="Locate config file in file browser")
def config():
Expand Down
18 changes: 11 additions & 7 deletions plextraktsync/commands/bug_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,24 @@ def bug_url():
config = factory.config
version = factory.version

q = urlencode({
'os': version.py_platform,
'python': version.py_version,
'version': version.full_version,
'config': config.dump(),
})
q = urlencode(
{
"os": version.py_platform,
"python": version.py_version,
"version": version.full_version,
"config": config.dump(),
}
)

return URL_TEMPLATE.format(q)


def bug_report():
url = bug_url()

print("Opening bug report URL in browser, if that doesn't work open the link manually:")
print(
"Opening bug report URL in browser, if that doesn't work open the link manually:"
)
print("")
print(url)
openurl(url)
8 changes: 6 additions & 2 deletions plextraktsync/commands/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ def get_sorted_cache(session: CachedSession, sorting: str, reverse: bool):
yield from sorter(session.cache.responses.values())


def responses_by_url(session: CachedSession, url: str) -> Generator[CachedRequest, Any, None]:
def responses_by_url(
session: CachedSession, url: str
) -> Generator[CachedRequest, Any, None]:
return (
response for response in session.cache.responses.values() if response.url == url
)
Expand Down Expand Up @@ -73,7 +75,9 @@ def inspect_url(session: CachedSession, url: str):
matches = responses_by_url(session, url)
for m in matches:
content_type = m.headers["Content-Type"]
if content_type.startswith("text/xml") or content_type.startswith("application/xml"):
if content_type.startswith("text/xml") or content_type.startswith(
"application/xml"
):
print(f"<!-- {m} -->")
for name, value in m.headers.items():
print(f"<!-- {name}: {value} -->")
Expand Down
1 change: 1 addition & 0 deletions plextraktsync/commands/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def config(urls_expire_after: bool, edit: bool, locate: bool):

if edit or locate:
import click

click.launch(config.config_yml, locate=locate)
return

Expand Down
14 changes: 8 additions & 6 deletions plextraktsync/commands/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@ def download_subtitles(plex: PlexApi, pm: PlexLibraryItem, savepath: Path):
f" Subtitle {index}: ({sub.language}) {sub.title} (codec: {sub.codec}, selected: {sub.selected}, transient: {sub.transient})"
)

filename = ''.join([
f"{sub.id}. ",
f"{sub.title}" if sub.title else "",
f"{sub.language}." if sub.language else "",
f"{sub.languageCode}.{sub.codec}"
])
filename = "".join(
[
f"{sub.id}. ",
f"{sub.title}" if sub.title else "",
f"{sub.language}." if sub.language else "",
f"{sub.languageCode}.{sub.codec}",
]
)

filename = Path(savepath, filename)
if filename.exists():
Expand Down
8 changes: 6 additions & 2 deletions plextraktsync/commands/imdb_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,16 @@ def imdb_import(input: PathLike, dry_run: bool):
print = factory.print

for r in read_csv(input):
print(f"Importing [blue]{r.media_type} {r.imdb}[/]: {r.title} ({r.year}), rated at {r.rate_date}")
print(
f"Importing [blue]{r.media_type} {r.imdb}[/]: {r.title} ({r.year}), rated at {r.rate_date}"
)
m = trakt.search_by_id(r.imdb, "imdb", r.media_type)
rating = trakt.rating(m)
if r.rating == rating:
print(f"Rating {rating} already exists")
continue
print(f"{'Would rate' if dry_run else 'Rating'} {m} with {r.rating} (was {rating})")
print(
f"{'Would rate' if dry_run else 'Rating'} {m} with {r.rating} (was {rating})"
)
if not dry_run:
trakt.rate(m, r.rating, r.rate_date)
16 changes: 12 additions & 4 deletions plextraktsync/commands/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,15 @@ def inspect_media(plex_id: PlexId):

print("Subtitles:")
for index, subtitle in enumerate(pm.subtitle_streams, start=1):
print(f" Subtitle {index}: ({subtitle.language}) {subtitle.title} (codec: {subtitle.codec}, selected: {subtitle.selected}, transient: {subtitle.transient})")
print(
f" Subtitle {index}: ({subtitle.language}) {subtitle.title} (codec: {subtitle.codec}, selected: {subtitle.selected}, transient: {subtitle.transient})"
)

print("Parts:")
for index, part in enumerate(pm.parts, start=1):
print(f" Part {index} (exists: {part.exists}): [link=file://{quote_plus(part.file)}]{escape(part.file)}[/link] {part.size} bytes")
print(
f" Part {index} (exists: {part.exists}): [link=file://{quote_plus(part.file)}]{escape(part.file)}[/link] {part.size} bytes"
)

print("Markers:")
for marker in pm.markers:
Expand All @@ -70,12 +74,16 @@ def inspect_media(plex_id: PlexId):

print("Guids:")
for guid in pm.guids:
print(f" Guid: {guid.provider_link}, Id: {guid.id}, Provider: '{guid.provider}'")
print(
f" Guid: {guid.provider_link}, Id: {guid.id}, Provider: '{guid.provider}'"
)

print(f"Metadata: {pm.to_json()}")
print(f"Played on Plex: {pm.is_watched}")

history = plex.history(media, device=True, account=True) if not pm.is_discover else []
history = (
plex.history(media, device=True, account=True) if not pm.is_discover else []
)
print("Plex play history:")
for h in history:
d = h.device
Expand Down
7 changes: 4 additions & 3 deletions plextraktsync/commands/login.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from plextraktsync.commands.plex_login import plex_login_autoconfig
from plextraktsync.commands.trakt_login import (has_trakt_token,
trakt_login_autoconfig)
from plextraktsync.commands.trakt_login import has_trakt_token, trakt_login_autoconfig
from plextraktsync.factory import factory
from plextraktsync.style import highlight, success

Expand All @@ -19,7 +18,9 @@ def login():
print(highlight("Checking Plex and Trakt login credentials existence"))
print("")
print("It will not test if the credentials are valid, only that they are present.")
print('If you need to re-login use "plex-login" or "trakt-login" commands respectively.')
print(
'If you need to re-login use "plex-login" or "trakt-login" commands respectively.'
)
print("")
ensure_login()
print(success("Done!"))
30 changes: 24 additions & 6 deletions plextraktsync/commands/plex_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def server_urls(server: MyPlexResource):
connections = server.preferred_connections(
None,
locations=server.DEFAULT_LOCATION_ORDER,
schemes=server.DEFAULT_SCHEME_ORDER
schemes=server.DEFAULT_SCHEME_ORDER,
)
yield from connections
yield local_url()
Expand All @@ -64,7 +64,9 @@ def server_urls(server: MyPlexResource):
def myplex_login(username, password):
while True:
username = Prompt.ask(PROMPT_PLEX_USERNAME, default=username)
password = Prompt.ask(PROMPT_PLEX_PASSWORD, password=True, default=password, show_default=False)
password = Prompt.ask(
PROMPT_PLEX_PASSWORD, password=True, default=password, show_default=False
)
code = Prompt.ask(PROMPT_PLEX_CODE)
try:
return MyPlexAccount(username=username, password=password, code=code)
Expand Down Expand Up @@ -106,7 +108,9 @@ def format_server(s):
lines = []
product = f"{s.product}/{s.productVersion}"
platform = f"{s.device}: {s.platform}/{s.platformVersion}"
lines.append(f"{s.name}: Last seen: {str(s.lastSeenAt)}, Server: {product} on {platform}")
lines.append(
f"{s.name}: Last seen: {str(s.lastSeenAt)}, Server: {product} on {platform}"
)
c: ResourceConnection
for c in s.connections:
lines.append(f" {c.uri}")
Expand Down Expand Up @@ -178,7 +182,14 @@ def choose_server(account: MyPlexAccount) -> tuple[MyPlexResource, PlexServer]:
plex = server.connect()
return server, plex
except NotFound as e:
print(Panel.fit(f"{e}. Try another server", padding=1, title="[b red]ERROR", border_style="red"))
print(
Panel.fit(
f"{e}. Try another server",
padding=1,
title="[b red]ERROR",
border_style="red",
)
)


def plex_login_autoconfig():
Expand All @@ -197,8 +208,15 @@ def login(username: str, password: str):
return

account = myplex_login(username, password)
print(Panel.fit("Login to MyPlex was successful", title="Plex Login",
title_align="left", padding=1, border_style="bright_blue"))
print(
Panel.fit(
"Login to MyPlex was successful",
title="Plex Login",
title_align="left",
padding=1,
border_style="bright_blue",
)
)

(server, plex) = choose_server(account)
print(success(f"Connection to {plex.friendlyName} established successfully!"))
Expand Down
4 changes: 3 additions & 1 deletion plextraktsync/commands/self_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ def self_update(pr: int):
execp(f"pipx uninstall plextraktsync@{pr}")

print(f"Updating PlexTraktSync to the pull request #{pr} version using pipx")
execp(f"pipx install --suffix=@{pr} --force git+https://github.com/Taxel/PlexTraktSync@refs/pull/{pr}/head")
execp(
f"pipx install --suffix=@{pr} --force git+https://github.com/Taxel/PlexTraktSync@refs/pull/{pr}/head"
)
return

print("Updating PlexTraktSync to the latest version using pipx")
Expand Down
8 changes: 6 additions & 2 deletions plextraktsync/commands/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,14 @@ def sync(
dry_run=dry_run,
)
if server:
logger.warning('"plextraktsync sync --server=<name>" is deprecated use "plextraktsync --server=<name> sync"')
logger.warning(
'"plextraktsync sync --server=<name>" is deprecated use "plextraktsync --server=<name> sync"'
)
config.update(server=server)
if no_progress_bar:
logger.warning('"plextraktsync sync --no-progress-bar" is deprecated use "plextraktsync --no-progressbar sync"')
logger.warning(
'"plextraktsync sync --no-progress-bar" is deprecated use "plextraktsync --no-progressbar sync"'
)
config.update(progress=False)
if batch_delay:
logger.warning(
Expand Down
10 changes: 7 additions & 3 deletions plextraktsync/commands/watch.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
from __future__ import annotations

from plextraktsync.factory import factory
from plextraktsync.watch.events import (ActivityNotification, Error,
PlaySessionStateNotification,
ServerStarted, TimelineEntry)
from plextraktsync.watch.events import (
ActivityNotification,
Error,
PlaySessionStateNotification,
ServerStarted,
TimelineEntry,
)


def watch(server: str):
Expand Down
Loading

0 comments on commit d95293b

Please sign in to comment.