Example #1
0
def main(args):
    if not hlm_notifierbackend.isAvailable():
        sys.exit(1)
    # First connection yields an error if the daemon is not available.
    clientSocket = hlm_clientsocket.ClientSocket()

    while True:
        if __INFO__: logInfo('HLM notifier daemon is up and running.')
        try:
            clientSocket.write('notify')
            #
            # Regexes for parsing the notifications:
            # If a notification starts with [...] then the "..." is supposed
            # to be an icon that we will pass to notify-send.
            # Icons are taken from the hotspot_login_manager/icons directory.
            #
            regex = re.compile('^\\[([^]/]+)\\] ')
            #
            while True:
                message = clientSocket.readMessage()
                if message == '':
                    break
                # Keep-alive message, ignore it
                if message == '.':
                    continue
                # Default icon
                icon = None
                match = regex.search(message)
                if match != None:
                    # We found [icon], check it and adjust the message
                    iconName = match.group(1)
                    iconPath = hlm_application.getPath(
                    ) + '/icons/' + iconName + '.png'
                    if os.path.isfile(iconPath):
                        icon = iconPath
                        message = message[len(iconName) + 3:]
                # Send the notification to the end-user
                hlm_notifierbackend.notify(message, icon)

        finally:
            clientSocket.close()

        # Reconnect silently if the daemon went down
        if __DEBUG__: logDebug('Daemon went down, trying to reconnect...')
        while True:
            try:
                time.sleep(1)
                clientSocket = hlm_clientsocket.ClientSocket()
                if __DEBUG__: logDebug('Daemon went up again.')
                break
            except SystemExit:
                raise
            except KeyboardInterrupt:
                raise
            except BaseException:
                pass
def main(args):
    if not hlm_notifierbackend.isAvailable():
        sys.exit(1)
    # First connection yields an error if the daemon is not available.
    clientSocket = hlm_clientsocket.ClientSocket()

    while True:
        if __INFO__: logInfo('HLM notifier daemon is up and running.')
        try:
            clientSocket.write('notify')
            #
            # Regexes for parsing the notifications:
            # If a notification starts with [...] then the "..." is supposed
            # to be an icon that we will pass to notify-send.
            # Icons are taken from the hotspot_login_manager/icons directory.
            #
            regex = re.compile('^\\[([^]/]+)\\] ')
            #
            while True:
                message = clientSocket.readMessage()
                if message == '':
                    break
                # Keep-alive message, ignore it
                if message == '.':
                    continue
                # Default icon
                icon = None
                match = regex.search(message)
                if match != None:
                    # We found [icon], check it and adjust the message
                    iconName = match.group(1)
                    iconPath = hlm_application.getPath() + '/icons/' + iconName + '.png'
                    if os.path.isfile(iconPath):
                        icon = iconPath
                        message = message[len(iconName)+3:]
                # Send the notification to the end-user
                hlm_notifierbackend.notify(message, icon)

        finally:
            clientSocket.close()

        # Reconnect silently if the daemon went down
        if __DEBUG__: logDebug('Daemon went down, trying to reconnect...')
        while True:
            try:
                time.sleep(1)
                clientSocket = hlm_clientsocket.ClientSocket()
                if __DEBUG__: logDebug('Daemon went up again.')
                break
            except SystemExit:
                raise
            except KeyboardInterrupt:
                raise
            except BaseException:
                pass
def _parse():
    ''' Perform the actual arguments parsing.
    '''
    (parser, options) = _parseArgs()

    # Handle --help and --version and exit immediately
    if options.displayHelp or options.displayVersion:
        print('Hotspot Login Manager {0}'.format(hlm_application.getVersion()))
        if options.displayHelp:
            print()
            parser.print_help()
        sys.exit(0)
    # We don't need the parser anymore
    parser.destroy()

    # Do not accept any additional options
    if options.strayArgs != []:
        exitWithError(_N('Unknown option:',
                         'Unknown options:',
                         len(options.strayArgs))
                      + ' ' + ' '.join(options.strayArgs))

    # Mutually exclusive options
    mainCommands = quote(['--reauth', '--status', '--providers', '--pid', '--notifier', '--daemon'])
    mainCommandsCount = sum([options.runReauth, options.runStatus, options.runProviders, options.runPID, options.runNotifier, options.runDaemon])
    if mainCommandsCount == 0:
        exitWithError(_('Missing option: one of {0} must be used.').format(mainCommands))
    if mainCommandsCount > 1:
        exitWithError(_('Incompatible options: the options {0} are mutually exclusive.').format(mainCommands))
    if (not options.runDaemon) and ((options.daemonConfig != None) or (options.daemonCredentials != None)):
        optionNames = []
        if options.daemonConfig != None:
            optionNames.append('--config')
        if options.daemonCredentials != None:
            optionNames.append('--credentials')
        exitWithError(_N('Incompatible options: {0} can only be used in combination with {1}.',
                         'Incompatible options: {0} can only be used in combination with {1}.',
                         len(optionNames))
                        .format(quote(optionNames), quote('--daemon')))
    if options.runNotifier and not hlm_notifierbackend.isAvailable():
        exitWithError(_('{0} is not available on your system, you cannot run a notifier daemon.').format(quote('notify-send')))

    # Apply default values
    if options.logLevel == None:
        options.logLevel = hlm_globals.defaultLogLevel
    if options.runDaemon:
        # We'll handle daemonCredentials later on because it could be defined in daemon.conf
        if options.daemonConfig == None:
            options.daemonConfig = hlm_paths.daemonConfig()

    return options
Example #4
0
def _parse():
    ''' Perform the actual arguments parsing.
    '''
    (parser, options) = _parseArgs()

    # Handle --help and --version and exit immediately
    if options.displayHelp or options.displayVersion:
        print('Hotspot Login Manager {0}'.format(hlm_application.getVersion()))
        if options.displayHelp:
            print()
            parser.print_help()
        sys.exit(0)
    # We don't need the parser anymore
    parser.destroy()

    # Do not accept any additional options
    if options.strayArgs != []:
        exitWithError(
            _N('Unknown option:', 'Unknown options:', len(options.strayArgs)) +
            ' ' + ' '.join(options.strayArgs))

    # Mutually exclusive options
    mainCommands = quote([
        '--reauth', '--status', '--providers', '--pid', '--notifier',
        '--daemon'
    ])
    mainCommandsCount = sum([
        options.runReauth, options.runStatus, options.runProviders,
        options.runPID, options.runNotifier, options.runDaemon
    ])
    if mainCommandsCount == 0:
        exitWithError(
            _('Missing option: one of {0} must be used.').format(mainCommands))
    if mainCommandsCount > 1:
        exitWithError(
            _('Incompatible options: the options {0} are mutually exclusive.').
            format(mainCommands))
    if (not options.runDaemon) and ((options.daemonConfig != None) or
                                    (options.daemonCredentials != None)):
        optionNames = []
        if options.daemonConfig != None:
            optionNames.append('--config')
        if options.daemonCredentials != None:
            optionNames.append('--credentials')
        exitWithError(
            _N(
                'Incompatible options: {0} can only be used in combination with {1}.',
                'Incompatible options: {0} can only be used in combination with {1}.',
                len(optionNames)).format(quote(optionNames),
                                         quote('--daemon')))
    if options.runNotifier and not hlm_notifierbackend.isAvailable():
        exitWithError(
            _('{0} is not available on your system, you cannot run a notifier daemon.'
              ).format(quote('notify-send')))

    # Apply default values
    if options.logLevel == None:
        options.logLevel = hlm_globals.defaultLogLevel
    if options.runDaemon:
        # We'll handle daemonCredentials later on because it could be defined in daemon.conf
        if options.daemonConfig == None:
            options.daemonConfig = hlm_paths.daemonConfig()

    return options
Example #5
0
def _parseArgs():
    ''' Parse the command-line arguments, optionally ignoring the notification backend choices.
    '''
    parser = OptionParser(usage=_('Usage: %prog OPTIONS'),
                          add_help_option=False)
    # Map Python english error messages to custom i18n messages
    parser.error = _i18nErrorMapper
    # Set default options
    parser.set_defaults(
        displayHelp=False,
        displayVersion=False,
        # User commands
        runReauth=False,
        runStatus=False,
        runProviders=False,
        runPID=False,
        # Notification daemon
        runNotifier=False,
        # System daemon
        runDaemon=False,
        daemonConfig=None,
        daemonCredentials=None,
        # Verbosity
        logLevel=None,
    )

    group = OptionGroup(parser, _('General information'))
    group.add_option('-h',
                     '--help',
                     help=_('Display this help message and exit.'),
                     dest='displayHelp',
                     action='store_true')
    group.add_option('-v',
                     '--version',
                     help=_('Display the program version and exit.'),
                     dest='displayVersion',
                     action='store_true')
    parser.add_option_group(group)

    group = OptionGroup(parser, _('User commands'))
    group.add_option(
        '-r',
        '--reauth',
        help=
        _('Ask the system daemon to reauthenticate you immediately (bypassing the connection watchdog\'s timer) in case the hotspot decided to disconnect you.'
          ),
        dest='runReauth',
        action='store_true')
    group.add_option(
        '-s',
        '--status',
        help=_('Display the current status of the system daemon and exit.'),
        dest='runStatus',
        action='store_true')
    group.add_option(
        '--providers',
        help=_(
            'Display the list of the supported service providers and exit.'),
        dest='runProviders',
        action='store_true')
    group.add_option(
        '--pid',
        help=_('Display the current PID of the system daemon and exit.'),
        dest='runPID',
        action='store_true')
    parser.add_option_group(group)

    group = OptionGroup(
        parser, _('Notification daemon options'),
        _('This daemon can be run under an unprivileged account.'))

    if hlm_notifierbackend.isAvailable():
        notifierBackendMessage = ''
    else:
        notifierBackendMessage = ' ' + _(
            'Unfortunately {0} is not available on your system. You cannot run a notifier daemon.'
        ).format(quote('notify-send'))

    group.add_option(
        '-n',
        '--notifier',
        help=
        _('Run in the background and display end-user desktop notifications using {0}.'
          ).format(quote('notify-send')) + notifierBackendMessage,
        dest='runNotifier',
        action="store_true")
    parser.add_option_group(group)

    group = OptionGroup(
        parser, _('System daemon options'),
        _('This daemon must be run under a privileged account.'))
    group.add_option('--daemon',
                     help=_('Run as a system daemon (unique instance).'),
                     dest='runDaemon',
                     action='store_true')
    group.add_option('--config',
                     metavar=_('FILE'),
                     help=_('Use the daemon configuration file FILE.'),
                     dest='daemonConfig')
    group.add_option(
        '--credentials',
        metavar=_('FILE'),
        help=
        _('Use the credentials configuration file FILE. This option overrides the equivalent option from the daemon configuration file.'
          ),
        dest='daemonCredentials')
    parser.add_option_group(group)

    group = OptionGroup(parser, _('Verbosity'))

    group.add_option(
        '--log',
        metavar=_('LEVEL'),
        help=
        _('Determine the maximum verbosity LEVEL of the informational messages. In increasing verbosity order, the possible levels are: {0}. If this option is omitted, a default level of {1} will be used. In both daemon modes, messages are emitted to syslog\'s {2} facility.'
          ).format(quote(hlm_globals.availableLogLevels),
                   quote(hlm_globals.defaultLogLevel), quote('daemon')),
        dest='logLevel',
        choices=hlm_globals.availableLogLevels)
    parser.add_option_group(group)

    (options, strayArgs) = parser.parse_args()

    # Store stray args in the options
    options.strayArgs = strayArgs

    return (parser, options)
def _parseArgs():
    ''' Parse the command-line arguments, optionally ignoring the notification backend choices.
    '''
    parser = OptionParser(usage = _('Usage: %prog OPTIONS'), add_help_option = False)
    # Map Python english error messages to custom i18n messages
    parser.error = _i18nErrorMapper
    # Set default options
    parser.set_defaults(displayHelp = False,
                        displayVersion = False,
                        # User commands
                        runReauth = False,
                        runStatus = False,
                        runProviders = False,
                        runPID = False,
                        # Notification daemon
                        runNotifier = False,
                        # System daemon
                        runDaemon = False,
                        daemonConfig = None,
                        daemonCredentials = None,
                        # Verbosity
                        logLevel = None,
                       )

    group = OptionGroup(parser, _('General information'))
    group.add_option('-h', '--help',
                     help = _('Display this help message and exit.'),
                     dest = 'displayHelp', action = 'store_true')
    group.add_option('-v', '--version',
                     help = _('Display the program version and exit.'),
                     dest = 'displayVersion', action = 'store_true')
    parser.add_option_group(group)

    group = OptionGroup(parser, _('User commands'))
    group.add_option('-r', '--reauth',
                     help = _('Ask the system daemon to reauthenticate you immediately (bypassing the connection watchdog\'s timer) in case the hotspot decided to disconnect you.'),
                     dest = 'runReauth', action = 'store_true')
    group.add_option('-s', '--status',
                     help = _('Display the current status of the system daemon and exit.'),
                     dest = 'runStatus', action = 'store_true')
    group.add_option('--providers',
                     help = _('Display the list of the supported service providers and exit.'),
                     dest = 'runProviders', action = 'store_true')
    group.add_option('--pid',
                     help = _('Display the current PID of the system daemon and exit.'),
                     dest = 'runPID', action = 'store_true')
    parser.add_option_group(group)

    group = OptionGroup(parser, _('Notification daemon options'),
                                _('This daemon can be run under an unprivileged account.'))

    if hlm_notifierbackend.isAvailable():
        notifierBackendMessage = ''
    else:
        notifierBackendMessage = ' ' + _('Unfortunately {0} is not available on your system. You cannot run a notifier daemon.').format(quote('notify-send'))

    group.add_option('-n', '--notifier',
                     help = _('Run in the background and display end-user desktop notifications using {0}.').format(quote('notify-send')) + notifierBackendMessage,
                     dest = 'runNotifier', action = "store_true")
    parser.add_option_group(group)

    group = OptionGroup(parser, _('System daemon options'),
                                _('This daemon must be run under a privileged account.'))
    group.add_option('--daemon',
                     help = _('Run as a system daemon (unique instance).'),
                     dest = 'runDaemon', action = 'store_true')
    group.add_option('--config', metavar = _('FILE'),
                     help = _('Use the daemon configuration file FILE.'),
                     dest = 'daemonConfig')
    group.add_option('--credentials', metavar = _('FILE'),
                     help = _('Use the credentials configuration file FILE. This option overrides the equivalent option from the daemon configuration file.'),
                     dest = 'daemonCredentials')
    parser.add_option_group(group)

    group = OptionGroup(parser, _('Verbosity'))

    group.add_option('--log', metavar = _('LEVEL'),
                     help = _('Determine the maximum verbosity LEVEL of the informational messages. In increasing verbosity order, the possible levels are: {0}. If this option is omitted, a default level of {1} will be used. In both daemon modes, messages are emitted to syslog\'s {2} facility.')
                            .format(quote(hlm_globals.availableLogLevels), quote(hlm_globals.defaultLogLevel), quote('daemon')),
                     dest = 'logLevel', choices = hlm_globals.availableLogLevels)
    parser.add_option_group(group)

    (options, strayArgs) = parser.parse_args()

    # Store stray args in the options
    options.strayArgs = strayArgs

    return (parser, options)