Reintroduce sudo feature to lock users out. Remove AW watcher because the dependency is annoying.

This commit is contained in:
2022-07-23 12:37:05 -04:00
parent 34691309db
commit c82c52910c
6 changed files with 51 additions and 47 deletions

View File

@@ -19,3 +19,20 @@ ExecStart=/home/felixm/dot/bin/antidrift
WantedBy=default.target WantedBy=default.target
``` ```
## Autostart via desktop file
Create a file `antidrift.desktop` in `/etc/xdg/autostart`.
Add the following content to the file.
```
[Desktop Entry]
Name=AntiDrift
Exec=/home/felixm/dot/bin/antidrift
Terminal=false
Type=Application
StartupNotify=false
```
Your window manager will now start antidrift automatically.

View File

@@ -3,6 +3,7 @@ import shutil
import sys import sys
import os import os
import signal import signal
import subprocess
from pathlib import Path from pathlib import Path
import antidrift.client as client import antidrift.client as client
from antidrift.config import Config from antidrift.config import Config
@@ -40,17 +41,30 @@ def check_for_xdotool():
sys.exit(1) sys.exit(1)
def main_daemon(config):
init_logging(config.daemon_log_file)
add = AntiDriftDaemon(config)
add.run()
def main() -> None: def main() -> None:
""" Main routine that dispatches to client or daemon """ """ Main routine that dispatches to client or daemon """
config = Config.load(os.path.expanduser("~/.config/antidrift.yaml")) config = Config.load(os.path.expanduser("~/.config/antidrift.yaml"))
check_for_xdotool() check_for_xdotool()
if client.antidrift_daemon_is_running(): if client.antidrift_daemon_is_running():
init_logging(config.client_log_file) init_logging(config.client_log_file)
client.client_mode(config) client.client_mode(config)
elif len(sys.argv) == 1: elif len(sys.argv) == 1:
init_logging(config.daemon_log_file) if os.geteuid() == 0:
add = AntiDriftDaemon(config) newpid = os.fork()
add.run() if newpid == 0:
main_daemon(config)
else:
cmd = ["sudo", "/home/felixm/dot/bin/antidrift"]
subprocess.Popen(cmd)
elif len(sys.argv) == 2 and sys.argv[1] == '--daemon_user':
main_daemon(config)
else: else:
print("ad not running") print("ad not running")

View File

@@ -1,30 +0,0 @@
import logging
from datetime import datetime, timedelta, timezone
from dataclasses import dataclass
from aw_core.models import Event
from aw_client import ActivityWatchClient
@dataclass
class Settings:
timeout: int
poll_time: int
class AntidriftWatcher:
def __init__(self):
self.settings = Settings(timeout=180, poll_time=5)
self.client = ActivityWatchClient("aw-watcher-antidrift")
self.bucketname = "{}_{}".format(
self.client.client_name, self.client.client_hostname
)
logging.info("aw-watcher-antidrift started")
eventtype = "antidrift_status"
self.client.create_bucket(self.bucketname, eventtype, queued=False)
def ping(self, status: str):
data = {"status": status}
now = datetime.now(timezone.utc)
event = Event(timestamp=now, data=data)
inserted_event = self.client.heartbeat(self.bucketname, event, 2.0)

View File

@@ -8,8 +8,8 @@ import dbus.service
def get_dbus_interface() -> Optional[dbus.Interface]: def get_dbus_interface() -> Optional[dbus.Interface]:
bus = dbus.SessionBus()
try: try:
bus = dbus.SessionBus()
bus_object = bus.get_object("com.antidrift", "/com/antidrift") bus_object = bus.get_object("com.antidrift", "/com/antidrift")
interface = dbus.Interface(bus_object, "com.antidrift") interface = dbus.Interface(bus_object, "com.antidrift")
return interface return interface

View File

@@ -1,11 +1,11 @@
import logging import logging
import os import os
import sys import sys
import pwd
import antidrift.xwindow as xwindow import antidrift.xwindow as xwindow
from antidrift.config import Config from antidrift.config import Config
from gi.repository import GLib, Gio from gi.repository import GLib, Gio
from typing import List from typing import List
from antidrift.antidrift_watcher import AntidriftWatcher
import dbus import dbus
import dbus.service import dbus.service
@@ -23,7 +23,14 @@ def reload_callback(m, f, o, event):
class AntiDriftDaemon(dbus.service.Object): class AntiDriftDaemon(dbus.service.Object):
def __init__(self, config: Config): def __init__(self, config: Config):
bus = dbus.SessionBus()
user_name = os.environ["SUDO_USER"]
user_uid = pwd.getpwnam(user_name)[2]
euid = os.geteuid()
os.seteuid(user_uid)
bus = dbus.bus.BusConnection(f"unix:path=/run/user/{user_uid}/bus")
os.seteuid(euid)
bus.request_name(BUS_NAME) bus.request_name(BUS_NAME)
bus_name = dbus.service.BusName(BUS_NAME, bus=bus) bus_name = dbus.service.BusName(BUS_NAME, bus=bus)
dbus.service.Object.__init__(self, bus_name, OPATH) dbus.service.Object.__init__(self, bus_name, OPATH)
@@ -32,7 +39,6 @@ class AntiDriftDaemon(dbus.service.Object):
self.config.active_blackblocks = self.config.blackblocks self.config.active_blackblocks = self.config.blackblocks
self.enforce_count = 0 self.enforce_count = 0
self.enforce_value = int(config.enforce_delay_ms / config.polling_cycle_ms) self.enforce_value = int(config.enforce_delay_ms / config.polling_cycle_ms)
self.antidrift_watcher = AntidriftWatcher()
@dbus.service.method(dbus_interface=IFACE, @dbus.service.method(dbus_interface=IFACE,
in_signature="as", out_signature="s") in_signature="as", out_signature="s")
@@ -112,21 +118,15 @@ class AntiDriftDaemon(dbus.service.Object):
xwindow.notify(f"Minimize {window.name[:30]}.") xwindow.notify(f"Minimize {window.name[:30]}.")
window.minimize() window.minimize()
self.enforce_count = 0 self.enforce_count = 0
self.antidrift_watcher.ping("blocked")
elif self.enforce_count > 0 and window_is_blocked(config, True): elif self.enforce_count > 0 and window_is_blocked(config, True):
self.enforce_count += 1 self.enforce_count += 1
self.antidrift_watcher.ping("blocked")
elif self.enforce_count == 0 and window_is_blocked(config): elif self.enforce_count == 0 and window_is_blocked(config):
self.enforce_count += 1 self.enforce_count += 1
delay = int(config.enforce_delay_ms / 1000) delay = int(config.enforce_delay_ms / 1000)
xwindow.notify(f"AntiDrift will minimize in {delay}s.") xwindow.notify(f"AntiDrift will minimize in {delay}s.")
self.antidrift_watcher.ping("blocked")
elif self.enforce_count > 0: elif self.enforce_count > 0:
xwindow.notify("We are gucci again.") xwindow.notify("We are gucci again.")
self.enforce_count = 0 self.enforce_count = 0
self.antidrift_watcher.ping("okay")
else:
self.antidrift_watcher.ping("okay")
def window_is_blocked(config: Config, silent: bool = False) -> bool: def window_is_blocked(config: Config, silent: bool = False) -> bool:

View File

@@ -1,5 +1,6 @@
import os import os
import re import re
import pwd
import subprocess import subprocess
import logging import logging
@@ -30,17 +31,19 @@ class XWindow:
def quit(self): def quit(self):
self._run(["windowquit", self.window]) self._run(["windowquit", self.window])
def kill(self):
self._run(["windowkill", self.window])
def notify(message: str) -> None: def notify(message: str) -> None:
""" Notify user via the Xorg notify-send command. """ """ Notify user via the Xorg notify-send command. """
logging.debug(f"{message} - [grey]notify[/grey]") logging.debug(f"{message} - [grey]notify[/grey]")
env = { env = dict(os.environ)
**os.environ,
"DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1000/bus"
}
user = env.get("SUDO_USER", None) user = env.get("SUDO_USER", None)
if user is None: if user is None:
cmd = ["notify-send", message] cmd = ["notify-send", message]
else: else:
uid = pwd.getpwnam(user)[2]
env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path=/run/user/{uid}/bus"
cmd = ["runuser", "-m", "-u", user, "notify-send", message] cmd = ["runuser", "-m", "-u", user, "notify-send", message]
subprocess.run(cmd, env=env) subprocess.run(cmd, env=env)