Estoy desarrollando una aplicación que bloquee el apagado y muestre una notificación cuando el usuario intenta apagar con un pendrive conectado.
En otras distribuciones, lo he conseguido usando polkit, con un fichero .rules que invoque a un script; pero en Debian, la versión de polkit (0.105) no admite esos ficheros y solo permite el uso de fichero .pkla, los cuales no permiten invocar a scripts.
Mi fichero pkla es este:
[Shutdown]
Identity=unix-user:*
Action=org.freedesktop.consolekit.system.stop; org.freedesktop.login1.power-off;org.freedesktop.login1.power-off-multiple-sessions;org.xfce.session.xfsm-shutdown-helper
ResultAny=no
ResultInactive=no
ResultActive=no
Con esto he logrado bloquear el apagado, pero no puedo mostrar la notificación.
Se me ha ocurrido que podría usar un cliente dbus, lanzado por el usuario, que esté conectado a los eventos de apagado del sistema, pero no consigo que funcione.
He probado con este código:
#!/usr/bin/python3
from gi.repository import GLib
from gi.repository import Notify
import dbus
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop = DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus(mainloop=dbus_loop)
loop = GLib.MainLoop()
def msg_handler(*args,**keywords):
try:
#show notification to desktop
Notify.init('Pendrive Reminder')
notify = Notify.Notification.new('Pendrive Reminder', 'Shutdown lock enabled. Disconnect pendrive to enable shutdown')
notify.show()
except:
pass
bus.add_signal_receiver(handler_function=msg_handler,dbus_interface='org.freedesktop.login1.power-off-multiple-sessions', path_keyword='path')
Pero, cuando lo ejecuto, con:
python client.py
me salta este error:
ValueError: Invalid interface or error name 'org.freedesktop.login1.power-off-multiple-sessions': contains invalid character '-'
¿como podría detectar el evento desde dbus?
ACTUALIZACIÓN
Siguiendo las recomendaciones aportadas en las respuestas, he cambiado la captura del evento. El código resultante es el siguiente:
from gi.repository import GLib
from gi.repository import Notify
import dbus
from dbus.mainloop.glib import DBusGMainLoop
dbus_loop = DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus(mainloop=dbus_loop)
loop = GLib.MainLoop()
def msg_handler(*args,**keywords):
try:
#show notification to desktop
Notify.init('Pendrive Reminder')
notify = Notify.Notification.new('Pendrive Reminder', 'Shutdown lock enabled. Disconnect pendrive to enable shutdown')
notify.show()
except:
pass
bus.add_signal_receiver(
handler_function=msg_handler,
signal_name='PreparingForShutdown',
dbus_interface='org.freedesktop.login1.Manager',
bus_name='org.freedesktop.login1'
)
bus.add_signal_receiver(
handler_function=msg_handler,
signal_name='CanPowerOff',
dbus_interface='org.freedesktop.login1.Manager',
bus_name='org.freedesktop.login1'
)
bus.add_signal_receiver(
handler_function=msg_handler,
signal_name='PowerOff',
dbus_interface='org.freedesktop.login1.Manager',
bus_name='org.freedesktop.login1'
)
loop.run()
Con esto ya no me da error de sintaxis, pero tampoco logro capturar la señal: cuando pulso el botón de apagado, no se muestra la notificación.
¿donde podría estar el error?
De hecho, tampoco lo encuentro en la lista de procesos en ejecución
ACTUALIZACIÓN 2
Usando dbus-monitor --system
he descubierto que la acción realizada para bloquear el apagado es la siguiente:
signal time=1523017240.291438 sender=:1.16 -> destination=(null destination) serial=794 path=/org/freedesktop/login1; interface=org.freedesktop.DBus.Properties; member=PropertiesChanged
string "org.freedesktop.login1.Manager"
array [
dict entry(
string "DelayInhibited"
variant string "shutdown:sleep"
)
]
array [
]
He intentado capturarla con pydbus así:
from pydbus import SystemBus
from gi.repository import GLib
from gi.repository import Notify
from dbus.mainloop.glib import DBusGMainLoop
bus = SystemBus()
# Create an object that will proxy for a particular remote object.
power = bus.get('org.freedesktop.login1', '/org/freedesktop/login1')
loop = GLib.MainLoop()
if power.PropertiesChanged() == True:
#show notification to desktop
Notify.init('Pendrive Reminder')
notify = Notify.Notification.new('Pendrive Reminder', 'Shutdown lock enabled. Disconnect pendrive to enable shutdown')
notify.show()
loop.run()
Pero ahora me devuelve este error:
AttributeError: 'ProxySignal' object has no attribute 'emit'
Creo que el problema es que la señal devuelve una estructura, en vez de un booleano, pero no sé como podría recrear la estructura en Python
¿alguna idea?