Skip to content

Commit

Permalink
Save dark/light mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Commandcracker committed Jun 2, 2024
1 parent bdcbb68 commit 7277b19
Show file tree
Hide file tree
Showing 18 changed files with 1,315 additions and 11 deletions.
3 changes: 3 additions & 0 deletions src/gucken/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
import warnings
warnings.filterwarnings('ignore', message='Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning')

__version__ = "0.1.12"
71 changes: 60 additions & 11 deletions src/gucken/gucken.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import warnings
warnings.filterwarnings('ignore', message='Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning')

from textual._types import IgnoreReturnCallbackType
from textual.command import Hits, Provider as TextualProvider, Hit, DiscoveryHit
import argparse
import logging
from asyncio import gather
Expand Down Expand Up @@ -200,7 +199,48 @@ def move_item(lst: list, from_index: int, to_index: int) -> list:
return lst


client_id = "1238219157464416266"
CLIENT_ID = "1238219157464416266"


class GuckenCommands(TextualProvider):

@property
def _commands(self) -> tuple[tuple[str, IgnoreReturnCallbackType, str], ...]:
return (
(
"Toggle light/dark mode", # 🌇 / 🌃
self.app.action_toggle_dark,
"Toggle the application between light and dark mode",
),
(
"Quit the application", # ❌
self.app.action_quit,
"Quit the application as soon as possible",
),
)

"""
(
"Application folders", # 📁
self.app.action_quit,
"Displays a list of all folders used",
),
(
"Create Shortcut", # 🔗
self.app.action_quit,
"The will create shortcuts to gucken",
)
"""

async def discover(self) -> Hits:
for name, runnable, help_text in self._commands:
yield DiscoveryHit(name, runnable, help=help_text)

async def search(self, query: str) -> Hits:
matcher = self.matcher(query)
for name, runnable, help_text in self._commands:
if (match := matcher.match(name)) > 0:
yield Hit(match, matcher.highlight(name), runnable, help=help_text)


class GuckenApp(App):
Expand All @@ -214,6 +254,7 @@ class GuckenApp(App):
BINDINGS: ClassVar[list[BindingType]] = [
Binding("q", "quit", "Quit", show=False, priority=False),
]
COMMANDS = {GuckenCommands}

def __init__(self, debug: bool, search: str):
super().__init__(watch_css=debug)
Expand Down Expand Up @@ -409,6 +450,13 @@ def select_changed(self, event: Select.Changed) -> None:

# TODO: dont lock - no async
async def on_mount(self) -> None:
self.dark = gucken_settings_manager.settings["settings"]["ui"]["dark"]

def update_dark(value: bool):
gucken_settings_manager.settings["settings"]["ui"]["dark"] = value

self.watch(self, "dark", update_dark)

lang = self.query_one("#lang", DataTable)
lang.add_columns("Language")
for l in self.language:
Expand Down Expand Up @@ -445,7 +493,7 @@ def set_search():

async def enable_RPC(self):
if self.RPC is None:
self.RPC = AioPresence(client_id)
self.RPC = AioPresence(CLIENT_ID)
try:
await self.RPC.connect()
except DiscordNotFound:
Expand Down Expand Up @@ -489,11 +537,11 @@ def fuzzy_sort_key(result):
items = []
for series in final_results:
items.append(ClickableListItem(
Markdown(
f"##### {series.name} {series.production_year} [{series.provider_name}]"
f"\n{series.description}"
)
))
Markdown(
f"##### {series.name} {series.production_year} [{series.provider_name}]"
f"\n{series.description}"
)
))
await results_list_view.extend(items)
results_list_view.loading = False
if len(final_results) > 0:
Expand Down Expand Up @@ -709,7 +757,8 @@ def delete_chapters_file():
if len(script_opts) > 0:
args.append(f"--script-opts={','.join(script_opts)}")

args.append("--scripts-append=" + str(Path(__file__).parent.joinpath("resources", "mpv_gucken.lua")))
args.append(
"--scripts-append=" + str(Path(__file__).parent.joinpath("resources", "mpv_gucken.lua")))

if isinstance(_player, VLCPlayer):
prepend_data = []
Expand Down
3 changes: 3 additions & 0 deletions src/gucken/resources/default_settings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,8 @@ enabled = true
aniworld_to = true
serienstream_to = false

[settings.ui]
dark = true

[meta]
version = "0.0.0"
58 changes: 58 additions & 0 deletions test/benchmark/extract_html.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import re
import time
from bs4 import BeautifulSoup

html = '''
<input type="hidden" id="recaptcha-token" value="03AFcWeA63UNMq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cpHLglNP-ekJcKW2k1rwArPsN6YGlKKlXIp4Q-k60VPJRPw3cpIzGfZ6HzCO4dWG5nMqEFsJxWJIt574aIaOBoYt9ZBCWBJcsayRpDwiUOsYaYR646gp35dHowVR9GdNHUmJsCEyhEDweyJZY3xGNqs7GSeBSpnIr-OMurrxEdlvJOhX5GCPl-_JLc1wXmoOP2iJAh1s6i-h9tzCdhtHj32xGccz-yh48Gi4nEPxfAk7TFlj0Ti0w5M2WVQ0v87oHjlStmj17vOAge4wcAN8kQZ-BrqWYSMO6DtoL45_3TdD42V-2hG0hOcxV8HsOYHnoymZqHg_WApHsENg5CfO6OywSNbRnNUaE9dDxsqt9KAUG0g8HIMGzuilefp2EdVTyiNbVtjcuBTg3agGvcS7UMsRLDXAyCqSRI3CLcBVvDaTuQXKovxUZpzDEtQQqtUUmvSuNbK0rHCpBKSQubqONThBTeegy3o3CIuKiA">
'''


# String manipulation method
def extract_value_string(html):
start = html.find('id="recaptcha-token"')
if start != -1:
start = html.find('value="', start) + len('value="')
end = html.find('"', start)
return html[start:end]
return None


# Regex method
def extract_value_regex(html):
pattern = r'<input[^>]*id="recaptcha-token"[^>]*value="([^"]+)"'
match = re.search(pattern, html)
if match:
return match.group(1)
return None


# BeautifulSoup method
def extract_value_bs4(html):
soup = BeautifulSoup(html, 'html.parser')
input_tag = soup.find('input', {'id': 'recaptcha-token'})
if input_tag:
return input_tag.get('value')
return None


# Measure performance of string manipulation method
start_time = time.time()
for _ in range(100000):
token = extract_value_string(html)
string_duration = time.time() - start_time

# Measure performance of regex method
start_time = time.time()
for _ in range(100000):
token = extract_value_regex(html)
regex_duration = time.time() - start_time

# Measure performance of BeautifulSoup method
start_time = time.time()
for _ in range(100000):
token = extract_value_bs4(html)
bs4_duration = time.time() - start_time

print(f"String manipulation duration: {string_duration:.6f} seconds")
print(f"Regex duration: {regex_duration:.6f} seconds")
print(f"BeautifulSoup duration: {bs4_duration:.6f} seconds")
9 changes: 9 additions & 0 deletions test/benchmark/http/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "benchmark"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
may_minihttp = "0.1.3"
72 changes: 72 additions & 0 deletions test/benchmark/http/new_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import time
import asyncio
import requests
import httpx
import aiohttp
import urllib.request
import http.client

HOST = "127.0.0.1"
PORT = 8080
URL = f"http://{HOST}:{PORT}"


def benchmark_http_client_sync():
# Has no sessions
start_time = time.time()
for _ in range(1000):
conn = http.client.HTTPConnection(HOST, port=PORT)
conn.request("GET", "/")
conn.close()
end_time = time.time()
return end_time - start_time

def benchmark_requests():
start_time = time.time()
for _ in range(100):
with requests.Session() as session:
session.get(URL)
end_time = time.time()
return end_time - start_time


async def benchmark_aiohttp():
start_time = time.time()
for _ in range(100):
async with aiohttp.ClientSession() as session:
await session.get(URL)
end_time = time.time()
return end_time - start_time


def benchmark_httpx():
start_time = time.time()
for _ in range(100):
with httpx.Client() as client:
client.get(URL)
end_time = time.time()
return end_time - start_time


def benchmark_urllib():
start_time = time.time()
for _ in range(100):
opener = urllib.request.build_opener()
opener.open(URL)
opener.close()
end_time = time.time()
return end_time - start_time


if __name__ == "__main__":
sync_time = benchmark_requests()
async_time = asyncio.run(benchmark_aiohttp())
httpx_time = benchmark_httpx()
urllib_time = benchmark_urllib()
http_client_sync_time = benchmark_http_client_sync()

print(f"HTTP: {http_client_sync_time} seconds")
print(f"Requests: {sync_time} seconds")
print(f"Aiohttp: {async_time} seconds")
print(f"HTTPX: {httpx_time} seconds")
print(f"Urllib: {urllib_time} seconds")
72 changes: 72 additions & 0 deletions test/benchmark/http/same_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import time
import asyncio
import requests
import httpx
import aiohttp
import urllib.request
import http.client

HOST = "127.0.0.1"
PORT = 8080
URL = f"http://{HOST}:{PORT}"


def benchmark_http_client_sync():
start_time = time.time()
for _ in range(1000):
conn = http.client.HTTPConnection(HOST, port=PORT)
conn.request("GET", "/")
conn.close()
end_time = time.time()
return end_time - start_time


def benchmark_requests():
start_time = time.time()
with requests.Session() as session:
for _ in range(1000):
session.get(URL)
end_time = time.time()
return end_time - start_time


async def benchmark_aiohttp():
start_time = time.time()
async with aiohttp.ClientSession() as session:
for _ in range(1000):
await session.get(URL)
end_time = time.time()
return end_time - start_time


def benchmark_httpx():
start_time = time.time()
with httpx.Client() as client:
for _ in range(1000):
client.get(URL)
end_time = time.time()
return end_time - start_time


def benchmark_urllib():
start_time = time.time()
opener = urllib.request.build_opener()
for _ in range(1000):
opener.open(URL)
opener.close()
end_time = time.time()
return end_time - start_time


if __name__ == "__main__":
sync_time = benchmark_requests()
async_time = asyncio.run(benchmark_aiohttp())
httpx_time = benchmark_httpx()
urllib_time = benchmark_urllib()
http_client_sync_time = benchmark_http_client_sync()

print(f"HTTP: {http_client_sync_time} seconds")
print(f"Requests: {sync_time} seconds")
print(f"Aiohttp: {async_time} seconds")
print(f"HTTPX: {httpx_time} seconds")
print(f"Urllib: {urllib_time} seconds")
18 changes: 18 additions & 0 deletions test/benchmark/http/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
extern crate may_minihttp;

use std::io;
use may_minihttp::{HttpServer, HttpService, Request, Response};

#[derive(Clone)]
struct HelloWorld;

impl HttpService for HelloWorld {
fn call(&mut self, _req: Request, _res: &mut Response) -> io::Result<()> {
Ok(())
}
}

fn main() {
let server = HttpServer(HelloWorld).start("0.0.0.0:8080").unwrap();
server.join().unwrap();
}
Loading

0 comments on commit 7277b19

Please sign in to comment.