lol
This commit is contained in:
1 parent
2095c1f071
commit
1b7ec29d26
52 files changed
+18934
No files matched your search
@@ -0,0 +1,100 @@
|
||||
import os
|
||||
|
||||
from fabric.core.service import Service, Signal, Property
|
||||
from fabric.utils import exec_shell_command, exec_shell_command_async, monitor_file
|
||||
from gi.repository import GLib
|
||||
|
||||
# In the future, use GUdev to get ehe brightness devices
|
||||
|
||||
|
||||
# BUG This will open a new file every single time for some
|
||||
# reason, seems like brightnessctil does not stop function after completion
|
||||
def exec_brightnessctl_async(args: str):
|
||||
exec_shell_command_async(f"brightnessctl {args}", lambda _: None)
|
||||
|
||||
|
||||
screen = str(exec_shell_command("ls -w1 /sys/class/backlight")).split("\n")[0]
|
||||
leds = str(exec_shell_command("ls -w1 /sys/class/leds")).split("\n")
|
||||
|
||||
kbd = ""
|
||||
if "tpacpi::kbd_backlight" in leds:
|
||||
kbd = "tpacpi::kbd_backlight"
|
||||
|
||||
|
||||
class NoBrightnessError(ImportError):
|
||||
def __init__(self, *args):
|
||||
super().__init__(
|
||||
"Playerctl is not installed, please install it first",
|
||||
*args,
|
||||
)
|
||||
|
||||
|
||||
class Brightness(Service):
|
||||
# __gsignals__ = SignalContainer(
|
||||
# Signal("screen", "run-first", None, (int,)),
|
||||
# Signal("kbd", "run-first", None, (int,)),
|
||||
# )
|
||||
|
||||
@Signal
|
||||
def screen(self, value: int) -> None:
|
||||
...
|
||||
|
||||
@Signal
|
||||
def kbd(self, value: int) -> None:
|
||||
...
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.screen_backlight_path = "/sys/class/backlight/" + screen
|
||||
self.kbd_backlight_path = "/sys/class/leds/" + kbd
|
||||
self.max_kbd = -1
|
||||
self.max_screen = -1
|
||||
|
||||
if os.path.exists(self.screen_backlight_path + "/max_brightness"):
|
||||
with open(self.screen_backlight_path + "/max_brightness") as f:
|
||||
self.max_screen = int(f.read())
|
||||
if os.path.exists(self.kbd_backlight_path + "/max_brightness"):
|
||||
with open(self.kbd_backlight_path + "/max_brightness") as f:
|
||||
self.max_kbd = int(f.read())
|
||||
|
||||
self.screen_monitor = monitor_file(self.screen_backlight_path + "/brightness")
|
||||
self.screen_monitor.connect(
|
||||
"changed",
|
||||
lambda _, file, *args: self.emit( # type: ignore
|
||||
"screen",
|
||||
round(int(file.load_bytes()[0].get_data())),
|
||||
),
|
||||
)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@Property(int, "read-write")
|
||||
def screen_brightness(self) -> int: # type: ignore
|
||||
return (
|
||||
int(
|
||||
os.read(
|
||||
os.open(self.screen_backlight_path + "/brightness", os.O_RDONLY), 6
|
||||
),
|
||||
)
|
||||
if os.path.exists(self.screen_backlight_path + "/brightness")
|
||||
else -1
|
||||
)
|
||||
|
||||
@screen_brightness.setter
|
||||
def screen_brightness(self, value: int):
|
||||
if value < 0 or value > self.max_screen:
|
||||
return 0 if value < 0 else self.max_screen
|
||||
try:
|
||||
exec_brightnessctl_async(f"--device '{screen}' set {value}")
|
||||
self.emit("screen", int((value / self.max_screen) * 100)) # type: ignore
|
||||
except GLib.Error as e: # type: ignore
|
||||
print(e.message)
|
||||
|
||||
def set_kbd(self, value: int):
|
||||
if not kbd:
|
||||
return -1
|
||||
if value < 0 or value > self.max_kbd:
|
||||
return None
|
||||
try:
|
||||
exec_brightnessctl_async(f"--device '{kbd}' set {value}")
|
||||
self.emit("kbd", value) # type: ignore
|
||||
except GLib.Error as e: # type: ignore
|
||||
print(e.message)
|
||||
@@ -0,0 +1,82 @@
|
||||
import subprocess
|
||||
from gi.repository import GLib
|
||||
from fabric.core.service import Service
|
||||
from fabric.utils import exec_shell_command_async
|
||||
|
||||
|
||||
class CliphistItem:
|
||||
def __init__(self, id: int, content: str, content_type: str):
|
||||
self.id = id
|
||||
self.content = content
|
||||
self.content_type = content_type
|
||||
|
||||
|
||||
async def query(filter: str):
|
||||
fzf_args = '-f ""' if filter == "" else f"-f {filter}"
|
||||
|
||||
try:
|
||||
result = exec_shell_command_async(
|
||||
["bash", "-c", f"cliphist list | fzf {fzf_args} | head -n 16"]
|
||||
)
|
||||
items = set() # Using a set to ensure uniqueness
|
||||
|
||||
for line in result.split("\n"):
|
||||
if line:
|
||||
match = GLib.regex_match(r"(\d+)\s+(.*)", line)
|
||||
if match:
|
||||
id = int(match.group(1))
|
||||
content = match.group(2)
|
||||
content_type = "text"
|
||||
if content.startswith("[["):
|
||||
binary_match = GLib.regex_match(
|
||||
r"\[\[\s+binary data.*(jpg|png|webp|jpeg|bmp)", content
|
||||
)
|
||||
if binary_match:
|
||||
content_type = binary_match.group(1)
|
||||
|
||||
items.add(CliphistItem(id, content, content_type))
|
||||
|
||||
return list(items)
|
||||
|
||||
except Exception as err:
|
||||
print(err)
|
||||
return []
|
||||
|
||||
|
||||
async def run(args: CliphistItem):
|
||||
try:
|
||||
output = exec_shell_command_async(
|
||||
["bash", "-c", f"cliphist decode {args.id} | wl-copy"]
|
||||
)
|
||||
print(f":cliphist {args.id}:")
|
||||
print(output)
|
||||
except Exception as err:
|
||||
print("hello")
|
||||
|
||||
|
||||
async def get_file(item: CliphistItem):
|
||||
filepath = f"/tmp/cliphist-{item.id}.{item.content_type}"
|
||||
if not GLib.file_test(filepath, GLib.FileTest.EXISTS):
|
||||
exec_shell_command_async(
|
||||
["bash", "-c", f"cliphist decode {item.id} > {filepath}"]
|
||||
)
|
||||
return filepath
|
||||
|
||||
|
||||
class Cliphist(Service):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
async def get_file(self, item: CliphistItem):
|
||||
return await get_file(item)
|
||||
|
||||
async def query(self, filter: str):
|
||||
return await query(filter)
|
||||
|
||||
async def run(self, args: CliphistItem):
|
||||
await run(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cliphist = Cliphist()
|
||||
Service.register(cliphist)
|
||||
@@ -0,0 +1,55 @@
|
||||
import json
|
||||
import os
|
||||
from loguru import logger
|
||||
from fabric.utils import exec_shell_command_async
|
||||
import subprocess
|
||||
|
||||
|
||||
class EmojiItem:
|
||||
def __init__(self, str: str, name: str, slug: str, group: str):
|
||||
self.str = str
|
||||
self.name = name
|
||||
self.slug = slug
|
||||
self.group = group
|
||||
|
||||
|
||||
class EmojiService:
|
||||
def __init__(self):
|
||||
self.emoji = None
|
||||
self.load_emojis()
|
||||
|
||||
def load_emojis(self):
|
||||
try:
|
||||
# Construct the path using os.path.expanduser to handle the '~' correctly
|
||||
emoji_path = os.path.expanduser("~/fabric/assets/emoji.json")
|
||||
with open(emoji_path, "r") as f:
|
||||
data = json.load(f)
|
||||
self.emoji = [
|
||||
EmojiItem(str, item["name"], item["slug"], item["group"])
|
||||
for str, item in data.items()
|
||||
]
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load emoji data: {e}")
|
||||
self.emoji = []
|
||||
|
||||
def get_emojis(self):
|
||||
return self.emoji
|
||||
|
||||
def query(self, filter: str):
|
||||
if self.emoji is None:
|
||||
return []
|
||||
return [
|
||||
e
|
||||
for e in self.emoji
|
||||
if filter in e.name or filter in e.slug or filter in e.group
|
||||
][:44]
|
||||
|
||||
def copy(self, emoji_item: EmojiItem):
|
||||
try:
|
||||
# Use subprocess to run the wl-copy command to copy emoji
|
||||
subprocess.run(["wl-copy"], input=emoji_item.str.encode(), check=True)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to copy emoji: {e}")
|
||||
|
||||
|
||||
emoji_service = EmojiService()
|
||||
@@ -0,0 +1,43 @@
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
|
||||
class Inhibit:
|
||||
def __init__(self):
|
||||
self._id = None
|
||||
|
||||
@property
|
||||
def is_inhibit(self):
|
||||
"""Check if inhibition is active."""
|
||||
return self._id is not None
|
||||
|
||||
def _inhibit(self, command, data):
|
||||
"""Send a command to the DBus service to inhibit or un-inhibit."""
|
||||
dbus_command = (
|
||||
f"dbus-send --print-reply --dest=org.freedesktop.ScreenSaver "
|
||||
f"/org/freedesktop/ScreenSaver org.freedesktop.ScreenSaver.{command} {data}"
|
||||
)
|
||||
output = subprocess.run(
|
||||
dbus_command, shell=True, capture_output=True, text=True
|
||||
)
|
||||
|
||||
if command == "Inhibit":
|
||||
match = re.search(r"uint32\s+(\d+)", output.stdout)
|
||||
return int(match.group(1)) if match else None
|
||||
return None
|
||||
|
||||
def toggle(self):
|
||||
"""Toggle the inhibition state."""
|
||||
if self._id is None:
|
||||
self._id = self._inhibit("Inhibit", "string:'ags' string:'Manual pause'")
|
||||
else:
|
||||
self._id = self._inhibit("UnInhibit", f"uint32:{self._id}")
|
||||
|
||||
# Notify that the state has changed
|
||||
self.changed("is-inhibit")
|
||||
|
||||
def changed(self, property_name):
|
||||
"""Notify listeners that a property has changed."""
|
||||
print(
|
||||
f"Property '{property_name}' changed. Inhibition is now {'active' if self.is_inhibit else 'inactive'}."
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
import datetime
|
||||
import subprocess
|
||||
|
||||
from fabric.core.service import Service
|
||||
from fabric.utils import exec_shell_command
|
||||
from gi.repository import GLib, Gio
|
||||
from loguru import logger
|
||||
|
||||
|
||||
def exec_shell_command_async(cmd: str) -> bool:
|
||||
if isinstance(cmd, str):
|
||||
try:
|
||||
GLib.spawn_command_line_async(cmd)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
class ScreenRecorder(Service):
|
||||
# __gsignals__ = SignalContainer(
|
||||
|
||||
# )
|
||||
def __init__(self, **kwargs):
|
||||
self.screenshot_path = GLib.get_home_dir() + "/Pictures/Screenshots/"
|
||||
self.screenrecord_path = GLib.get_home_dir() + "/Videos/Screencasting/"
|
||||
self.recording = False
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def screenshot(self, fullscreen=False, save_copy=True):
|
||||
time = datetime.datetime.today().strftime("%Y-%m-%d_%H-%M-%S")
|
||||
file_path = self.screenshot_path + str(time) + ".png"
|
||||
command = ["wayshot", "-f", file_path] if save_copy else ["wayshot", "--stdout"]
|
||||
|
||||
if not fullscreen:
|
||||
region = exec_shell_command("slurp").split("\n")
|
||||
if region[0] == "selection cancelled":
|
||||
return
|
||||
command = command + ["-s", region[0]]
|
||||
|
||||
wayshot = subprocess.run(command, check=True, capture_output=True)
|
||||
if save_copy:
|
||||
exec_shell_command_async(f"bash -c 'wl-copy < {file_path}' ")
|
||||
self.send_screenshot_notification_file("file", file_path)
|
||||
return
|
||||
subprocess.run(["wl-copy"], input=wayshot.stdout, check=False)
|
||||
self.send_screenshot_notification_file("stdout")
|
||||
|
||||
def screencast_start(self, fullscreen=False):
|
||||
time = datetime.datetime.today().strftime("%Y-%m-%d_%H-%M-%S")
|
||||
file_path = self.screenrecord_path + str(time) + ".mp4"
|
||||
area = ""
|
||||
if fullscreen:
|
||||
area = exec_shell_command("slurp")
|
||||
command = f"wf-recorder -g {area} -f {file_path} --pixel-format yuv420p"
|
||||
|
||||
exec_shell_command_async(command)
|
||||
|
||||
def screencast_stop(self):
|
||||
exec_shell_command_async("killall -INT wf-recorder")
|
||||
self.recording = False
|
||||
|
||||
def send_screenshot_notification_file(self, notify_type, file_path=None):
|
||||
cmd = ["notify-send"]
|
||||
cmd.extend(
|
||||
[
|
||||
"-A",
|
||||
"files=Show in Files",
|
||||
"-A",
|
||||
"view=View",
|
||||
"-A",
|
||||
"edit=Edit",
|
||||
"-h",
|
||||
f"STRING:image-path:{file_path}",
|
||||
f"Screenshot {file_path}",
|
||||
]
|
||||
) if notify_type == "file" else ["Screenshot Sent to Clipboard"]
|
||||
|
||||
proc = Gio.Subprocess.new(cmd, Gio.SubprocessFlags.STDOUT_PIPE)
|
||||
|
||||
def do_callback(process: Gio.Subprocess, task: Gio.Task):
|
||||
try:
|
||||
_, stdout, stderr = process.communicate_utf8_finish(task)
|
||||
except Exception:
|
||||
logger.error("Failed read notification action")
|
||||
return
|
||||
|
||||
out = stdout.strip("\n")
|
||||
|
||||
match out:
|
||||
case "files":
|
||||
exec_shell_command_async(f"xdg-open {self.screenshot_path}")
|
||||
case "view":
|
||||
exec_shell_command_async(f"xdg-open {file_path}")
|
||||
case "edit":
|
||||
exec_shell_command_async(f"swappy -f {file_path}")
|
||||
|
||||
proc.communicate_utf8_async(None, None, do_callback)
|
||||
@@ -0,0 +1,55 @@
|
||||
from __init__ import *
|
||||
|
||||
CACHE_DIR = os.getenv("XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache"))
|
||||
BINS = os.path.join(CACHE_DIR, "binaries")
|
||||
|
||||
|
||||
class Sh:
|
||||
def __init__(self):
|
||||
self.reload() # Load binaries on initialization
|
||||
|
||||
def ls(self, path):
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
try:
|
||||
return (
|
||||
subprocess.check_output(f"ls {path}", shell=True, text=True)
|
||||
.strip()
|
||||
.splitlines()
|
||||
)
|
||||
except subprocess.CalledProcessError:
|
||||
return []
|
||||
|
||||
def reload(self):
|
||||
"""Reload the binaries from the PATH environment variable."""
|
||||
paths = os.getenv("PATH", "").split(":")
|
||||
bins = []
|
||||
|
||||
for path in paths:
|
||||
bins.extend(self.ls(path))
|
||||
|
||||
# Remove duplicates and save to file
|
||||
unique_bins = set(bins)
|
||||
with open(BINS, "w") as f:
|
||||
f.write("\n".join(unique_bins))
|
||||
|
||||
@staticmethod
|
||||
def query(filter_str):
|
||||
"""Filter binaries using fzf and return the results."""
|
||||
try:
|
||||
result = subprocess.check_output(
|
||||
f"cat {BINS} | fzf -f {filter_str} | head -n 16", shell=True, text=True
|
||||
)
|
||||
return list(dict.fromkeys(result.splitlines())) # Deduplicate results
|
||||
except subprocess.CalledProcessError:
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def run(args: str):
|
||||
"""Execute a command and print its output."""
|
||||
try:
|
||||
output = subprocess.check_output(args, shell=True, text=True)
|
||||
print(f":sh {args.strip()}:")
|
||||
print(output)
|
||||
except subprocess.CalledProcessError as err:
|
||||
print(f"Error running command: {err}")
|
||||
@@ -0,0 +1,249 @@
|
||||
from typing import List, Literal
|
||||
import gi
|
||||
from fabric.core.service import Property, Service, Signal
|
||||
from fabric.utils import bulk_connect
|
||||
from gi.repository import Gio
|
||||
from loguru import logger
|
||||
|
||||
from fabric.utils import exec_shell_command_async
|
||||
|
||||
try:
|
||||
gi.require_version("NM", "1.0")
|
||||
from gi.repository import NM
|
||||
except ValueError:
|
||||
logger.error("Failed to start network manager")
|
||||
|
||||
|
||||
class Wifi(Service):
|
||||
@Signal
|
||||
def changed(self) -> None:
|
||||
...
|
||||
|
||||
@Signal
|
||||
def enabled(self) -> bool:
|
||||
...
|
||||
|
||||
def __init__(self, client: NM.Client, device: NM.DeviceWifi, **kwargs):
|
||||
self._client: NM.Client = client
|
||||
self._device: NM.DeviceWifi = device
|
||||
self._ap: NM.AccessPoint | None = None
|
||||
self._ap_signal: int | None = None
|
||||
super().__init__(**kwargs)
|
||||
|
||||
self._client.connect(
|
||||
"notify::wireless-enabled",
|
||||
lambda *args: self.notifier("enabled", args),
|
||||
)
|
||||
if self._device:
|
||||
bulk_connect(
|
||||
self._device,
|
||||
{
|
||||
"notify::active-access-point": lambda *args: self._activate_ap(),
|
||||
"access-point-added": lambda *args: self.emit("changed"),
|
||||
"access-point-removed": lambda *args: self.emit("changed"),
|
||||
"state-changed": lambda *args: self.ap_update(),
|
||||
},
|
||||
)
|
||||
self._activate_ap()
|
||||
|
||||
def ap_update(self):
|
||||
self.emit("changed")
|
||||
for sn in [
|
||||
"enabled",
|
||||
"internet",
|
||||
"strength",
|
||||
"frequency",
|
||||
"access-points",
|
||||
"ssid",
|
||||
"state",
|
||||
"icon-name",
|
||||
]:
|
||||
self.notify(sn)
|
||||
|
||||
def _activate_ap(self):
|
||||
if self._ap:
|
||||
self._ap.disconnect(self._ap_signal)
|
||||
self._ap = self._device.get_active_access_point()
|
||||
if not self._ap:
|
||||
return
|
||||
|
||||
self._ap_signal = self._ap.connect(
|
||||
"notify::strength", lambda *args: self.ap_update()
|
||||
) # type: ignore
|
||||
|
||||
def toggle_wifi(self):
|
||||
self._client.wireless_set_enabled(not self._client.wireless_get_enabled())
|
||||
|
||||
# def set_active_ap(self, ap):
|
||||
# self._device.access
|
||||
|
||||
def scan(self):
|
||||
self._device.request_scan_async(
|
||||
None,
|
||||
lambda device, result: [
|
||||
device.request_scan_finish(result),
|
||||
self.emit("changed"),
|
||||
],
|
||||
)
|
||||
|
||||
def notifier(self, name: str, *args):
|
||||
self.notify(name)
|
||||
self.emit("changed")
|
||||
return
|
||||
|
||||
@Property(bool, "read-write", default_value=False)
|
||||
def enabled(self) -> bool: # type: ignore
|
||||
return bool(self._client.wireless_get_enabled())
|
||||
|
||||
@enabled.setter
|
||||
def enabled(self, value: bool):
|
||||
self._client.wireless_set_enabled(value)
|
||||
|
||||
@Property(int, "readable")
|
||||
def strength(self):
|
||||
return self._ap.get_strength() if self._ap else -1
|
||||
|
||||
@Property(str, "readable")
|
||||
def icon_name(self):
|
||||
if not self._ap:
|
||||
return "network-wireless-disabled-symbolic"
|
||||
|
||||
if self.internet == "activated":
|
||||
return {
|
||||
80: "network-wireless-signal-excellent-symbolic",
|
||||
60: "network-wireless-signal-good-symbolic",
|
||||
40: "network-wireless-signal-ok-symbolic",
|
||||
20: "network-wireless-signal-weak-symbolic",
|
||||
00: "network-wireless-signal-none-symbolic",
|
||||
}.get(
|
||||
min(80, 20 * round(self._ap.get_strength() / 20)),
|
||||
"network-wireless-no-route-symbolic",
|
||||
)
|
||||
if self.internet == "activating":
|
||||
return "network-wireless-acquiring-symbolic"
|
||||
|
||||
return "network-wireless-offline-symbolic"
|
||||
|
||||
@Property(int, "readable")
|
||||
def frequency(self):
|
||||
return self._ap.get_frequency() if self._ap else -1
|
||||
|
||||
@Property(int, "readable")
|
||||
def internet(self):
|
||||
return {
|
||||
NM.ActiveConnectionState.ACTIVATED: "activated",
|
||||
NM.ActiveConnectionState.ACTIVATING: "activating",
|
||||
NM.ActiveConnectionState.DEACTIVATING: "deactivating",
|
||||
NM.ActiveConnectionState.DEACTIVATED: "deactivated",
|
||||
}.get(
|
||||
self._device.get_active_connection().get_state(),
|
||||
"unknown",
|
||||
)
|
||||
|
||||
@Property(object, "readable")
|
||||
def access_points(self) -> List[object]:
|
||||
points: list[NM.AccessPoint] = self._device.get_access_points()
|
||||
|
||||
def make_ap_dict(ap: NM.AccessPoint):
|
||||
return {
|
||||
"bssid": ap.get_bssid(),
|
||||
# "address": ap.get_
|
||||
"last_seen": ap.get_last_seen(),
|
||||
"ssid": NM.utils_ssid_to_utf8(ap.get_ssid().get_data())
|
||||
if ap.get_ssid()
|
||||
else "Unknown",
|
||||
"active-ap": self._ap,
|
||||
"strength": ap.get_strength(),
|
||||
"frequency": ap.get_frequency(),
|
||||
"icon-name": {
|
||||
80: "network-wireless-signal-excellent-symbolic",
|
||||
60: "network-wireless-signal-good-symbolic",
|
||||
40: "network-wireless-signal-ok-symbolic",
|
||||
20: "network-wireless-signal-weak-symbolic",
|
||||
00: "network-wireless-signal-none-symbolic",
|
||||
}.get(
|
||||
min(80, 20 * round(ap.get_strength() / 20)),
|
||||
"network-wireless-no-route-symbolic",
|
||||
),
|
||||
}
|
||||
|
||||
return list(map(make_ap_dict, points))
|
||||
|
||||
@Property(str, "readable")
|
||||
def ssid(self):
|
||||
if not self._ap:
|
||||
return "Disconnected"
|
||||
ssid = self._ap.get_ssid().get_data()
|
||||
return NM.utils_ssid_to_utf8(ssid) if ssid else "Unknown"
|
||||
|
||||
@Property(int, "readable")
|
||||
def state(self):
|
||||
return {
|
||||
NM.DeviceState.UNMANAGED: "unmanaged",
|
||||
NM.DeviceState.UNAVAILABLE: "unavailable",
|
||||
NM.DeviceState.DISCONNECTED: "disconnected",
|
||||
NM.DeviceState.PREPARE: "prepare",
|
||||
NM.DeviceState.CONFIG: "config",
|
||||
NM.DeviceState.NEED_AUTH: "need_auth",
|
||||
NM.DeviceState.IP_CONFIG: "ip_config",
|
||||
NM.DeviceState.IP_CHECK: "ip_check",
|
||||
NM.DeviceState.SECONDARIES: "secondaries",
|
||||
NM.DeviceState.ACTIVATED: "activated",
|
||||
NM.DeviceState.DEACTIVATING: "deactivating",
|
||||
NM.DeviceState.FAILED: "failed",
|
||||
}.get(self._device.get_state(), "unknown")
|
||||
|
||||
|
||||
class NetworkClient(Service):
|
||||
@Signal
|
||||
def device_ready(self) -> None:
|
||||
...
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self._client: NM.Client | None = None
|
||||
self.wifi_device: Wifi | None = None
|
||||
super().__init__(**kwargs)
|
||||
NM.Client.new_async(
|
||||
cancellable=None,
|
||||
callback=self._init_network_client,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def _init_network_client(self, client: NM.Client, task: Gio.Task, **kwargs):
|
||||
self._client = client
|
||||
wifi_device: NM.DeviceWifi = self._get_device(NM.DeviceType.WIFI) # type: ignore
|
||||
# eth_device: NM.DeviceEthernet = self._get_device(NM.DeviceType.ETHERNET) # type: ignore
|
||||
|
||||
if wifi_device:
|
||||
self.wifi_device = Wifi(self._client, wifi_device)
|
||||
self.emit("device-ready")
|
||||
|
||||
# if eth_device:
|
||||
# self.eth_device = Ethernet(self._client, eth_device)
|
||||
|
||||
def _get_device(self, device_type) -> NM.Device | None:
|
||||
devices: List[NM.Device] = self._client.get_devices() # type: ignore
|
||||
return next((x for x in devices if x.get_device_type() == device_type), None)
|
||||
|
||||
def get_primary_device(self) -> Literal["wifi", "wired"] | None:
|
||||
if not self._client:
|
||||
return None
|
||||
return (
|
||||
"wifi"
|
||||
if "wireless"
|
||||
in str(self._client.get_primary_connection().get_connection_type())
|
||||
else "wired"
|
||||
if "ethernet"
|
||||
in str(self._client.get_primary_connection().get_connection_type())
|
||||
else None
|
||||
)
|
||||
|
||||
def connect_wifi_bssid(self, bssid):
|
||||
# We are using nmcli here, idk im lazy
|
||||
exec_shell_command_async(
|
||||
f"nmcli device wifi connect {bssid}", lambda *args: print(args)
|
||||
)
|
||||
|
||||
@Property(str, "readable")
|
||||
def primary_device(self) -> Literal["wifi", "wired"] | None:
|
||||
return self.get_primary_device()
|
||||
Reference in new issue
Block a user