diff --git a/simple_backup/simple_backup.py b/simple_backup/simple_backup.py index 246b4c8..1691e49 100755 --- a/simple_backup/simple_backup.py +++ b/simple_backup/simple_backup.py @@ -15,7 +15,6 @@ Classes: from __future__ import annotations # Import libraries -import traceback import sys import os import pwd @@ -51,7 +50,7 @@ except ImportError: try: import dbus except ImportError: - pass + dbus = None load_dotenv() @@ -316,10 +315,7 @@ class Backup: logger.critical( 'Cannot access the backup directory. Permission denied') - try: - _notify('Backup failed (check log for details)') - except NameError: - pass + _notify('Backup failed (check log for details)') sys.exit(3) @@ -500,10 +496,7 @@ class Backup: logger.info('Starting backup...') - try: - _notify('Starting backup...') - except NameError: - pass + _notify('Starting backup...') self.define_backup_dir() self.find_last_backup() @@ -525,10 +518,7 @@ class Backup: logger.info( 'No existing files or directories specified for backup. Nothing to do') - try: - _notify('Backup finished. No files copied') - except NameError: - pass + _notify('Backup finished. No files copied') return 1 @@ -615,17 +605,11 @@ class Backup: if output == 'ok': logger.info('Backup completed') - try: - _notify('Backup completed') - except NameError: - pass + _notify('Backup completed') else: logger.error('Backup failed') - try: - _notify('Backup failed (check log for details)') - except NameError: - pass + _notify('Backup failed (check log for details)') if self._ssh: self._ssh.close() @@ -634,20 +618,14 @@ class Backup: logger.error( 'Some errors occurred while performing the backup') - try: - _notify( - 'Some errors occurred while performing the backup. Check log for details') - except NameError: - pass + _notify( + 'Some errors occurred while performing the backup. Check log for details') return 4 logger.info('Backup completed') - try: - _notify('Backup completed') - except NameError: - pass + _notify('Backup completed') return 0 @@ -844,12 +822,20 @@ def _target_uid() -> int | None: return None +_notify_failed = False + + def _notify(text: str) -> None: + global _notify_failed + + if dbus is None or _notify_failed: + return + euid = os.geteuid() uid = _target_uid() if uid is None: - print('notify: no target uid (neither SUDO_UID nor DOAS_USER set)', file=sys.stderr) + logger.debug('Cannot send desktop notification: user not found') return @@ -862,8 +848,10 @@ def _notify(text: str) -> None: '/org/freedesktop/Notifications') obj = dbus.Interface(obj, 'org.freedesktop.Notifications') obj.Notify('simple_backup', 0, '', 'simple_backup', text, [], {'urgency': dbus.Byte(1)}, 10000) - except Exception: - traceback.print_exc() + except Exception as e: + # Report the failure only once (e.g. no session bus available), then stop trying + _notify_failed = True + logger.warning('Cannot send desktop notification: %s', e) finally: os.seteuid(euid)