def main(testing=False):
    client_logger = logging.getLogger("aw_client")
    if not testing:
        client_logger.setLevel(logging.WARNING)
    setup_logging(name, testing=testing, log_stderr=True, log_file=testing)

    # change back log level changed in setup_logging(), see issue #8
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO if testing else logging.WARNING)

    config = load_config()
    pulsetime = config[name].getfloat("pulsetime")

    aw = ActivityWatchClient(name, testing=testing)
    bucketname = "{}_{}".format(aw.client_name, aw.client_hostname)
    aw.create_bucket(bucketname, 'app.editor.activity', queued=True)
    aw.connect()

    for chunk in sys.stdin:
        msg = json.loads(chunk)
        if "action" not in msg:
            logger.error("No action in msg: {}".format(msg))
        elif msg["action"] == "update":
            timestamp = datetime.now(timezone.utc)
            event = Event(timestamp=timestamp, data=msg["data"])
            aw.heartbeat(bucketname, event, pulsetime=pulsetime, queued=True, commit_interval=3)
        else:
            logger.error("Invalid action: {}".format(msg["action"]))
Пример #2
0
def main():
    # Verify python version is >=3.5
    #   req_version is 3.5 due to usage of subprocess.run
    assert_version((3, 5))

    if sys.platform.startswith("linux") and ("DISPLAY" not in os.environ or not os.environ["DISPLAY"]):
        raise Exception("DISPLAY environment variable not set")

    # Read settings from config
    config = load_config()
    args = parse_args(default_poll_time=config.getfloat("poll_time"))

    setup_logging(name="aw-watcher-window", testing=args.testing, verbose=args.verbose,
                  log_stderr=True, log_file=True)

    client = ActivityWatchClient("aw-watcher-window", testing=args.testing)

    bucket_id = "{}_{}".format(client.client_name, client.client_hostname)
    event_type = "currentwindow"

    client.create_bucket(bucket_id, event_type, queued=True)

    logger.info("aw-watcher-window started")
    sleep(1)  # wait for server to start
    with client:
        heartbeat_loop(client, bucket_id, poll_time=args.poll_time, exclude_title=args.exclude_title)
Пример #3
0
def main():
    # Verify python version is >=3.5
    #   req_version is 3.5 due to usage of subprocess.run
    assert_version((3, 5))

    if sys.platform.startswith("linux") and ("DISPLAY" not in os.environ
                                             or not os.environ["DISPLAY"]):
        raise Exception("DISPLAY environment variable not set")

    # Read settings from config
    config = load_config()
    args = parse_args(default_poll_time=config.getfloat("poll_time"),
                      default_exclude_title=config.getboolean("exclude_title"))

    setup_logging(name="aw-watcher-window",
                  testing=args.testing,
                  verbose=args.verbose,
                  log_stderr=True,
                  log_file=True)

    client = ActivityWatchClient("aw-watcher-window", testing=args.testing)

    bucket_id = "{}_{}".format(client.client_name, client.client_hostname)
    event_type = "currentwindow"

    client.create_bucket(bucket_id, event_type, queued=True)

    logger.info("aw-watcher-window started")
    sleep(1)  # wait for server to start
    with client:
        heartbeat_loop(client,
                       bucket_id,
                       poll_time=args.poll_time,
                       exclude_title=args.exclude_title)
Пример #4
0
def main():
    """Called from the executable and __main__.py"""

    settings, storage_method = parse_settings()

    # FIXME: The LogResource API endpoint relies on the log being in JSON format
    # at the path specified by aw_core.log.get_log_file_path(). We probably want
    # to write the LogResource API so that it does not depend on any physical file
    # but instead add a logging handler that it can use privately.
    # That is why log_file_json=True currently.
    # UPDATE: The LogResource API is no longer available so log_file_json is now False.
    setup_logging("aw-server",
                  testing=settings.testing,
                  verbose=settings.verbose,
                  log_stderr=True,
                  log_file=True,
                  log_file_json=False)

    logger.info("Using storage method: {}".format(settings.storage))

    if settings.testing:
        logger.info("Will run in testing mode")

    logger.info("Starting up...")
    _start(host=settings.host,
           port=settings.port,
           testing=settings.testing,
           storage_method=storage_method)
Пример #5
0
def main(testing=False):
    client_logger = logging.getLogger("aw_client")
    if not testing:
        client_logger.setLevel(logging.WARNING)
    setup_logging(name, testing=testing, log_stderr=True, log_file=testing)

    config = load_config()
    pulsetime = config[name].getfloat("pulsetime")

    aw = ActivityWatchClient(name, testing=testing)
    bucketname = "{}_{}".format(aw.client_name, aw.client_hostname)
    aw.create_bucket(bucketname, 'app.editor.activity', queued=True)
    aw.connect()

    for chunk in sys.stdin:
        msg = json.loads(chunk)
        if "action" not in msg:
            logger.error("No action in msg: {}".format(msg))
        elif msg["action"] == "update":
            timestamp = datetime.now(timezone.utc)
            event = Event(timestamp=timestamp, data=msg["data"])
            aw.heartbeat(bucketname,
                         event,
                         pulsetime=pulsetime,
                         queued=True,
                         commit_interval=3)
        else:
            logger.error("Invalid action: {}".format(msg["action"]))
Пример #6
0
def main(testing: bool, autostart_modules: Optional[str]) -> None:
    # Since the .app can crash when started from Finder for unknown reasons, we send a syslog message here to make debugging easier.
    if platform.system() == "Darwin":
        subprocess.call("syslog -s 'aw-qt started'", shell=True)

    setup_logging("aw-qt", testing=testing, verbose=testing, log_file=True)
    logger.info("Started aw-qt...")

    # Since the .app can crash when started from Finder for unknown reasons, we send a syslog message here to make debugging easier.
    if platform.system() == "Darwin":
        subprocess.call("syslog -s 'aw-qt successfully started logging'",
                        shell=True)

    config = AwQtSettings(testing=testing)
    _autostart_modules = ([
        m.strip() for m in autostart_modules.split(",")
        if m and m.lower() != "none"
    ] if autostart_modules else config.autostart_modules)

    _manager = Manager(testing=testing)
    _manager.autostart(_autostart_modules)

    error_code = trayicon.run(_manager, testing=testing)
    _manager.stop_all()

    sys.exit(error_code)
Пример #7
0
def main() -> None:
    # Set up argparse
    parser = argparse.ArgumentParser(
        "Monitors whether you have set your height-adjustable table to sitting or "
        "standing.")
    parser.add_argument("-v",
                        "--verbose",
                        dest='verbose',
                        action="store_true",
                        help='run with verbose logging')
    parser.add_argument("--testing",
                        action="store_true",
                        help='run in testing mode')
    args = parser.parse_args()

    # Set up logging
    setup_logging("aw-watcher-table",
                  testing=args.testing,
                  verbose=args.verbose,
                  log_stderr=True,
                  log_file=True)

    # Start watcher
    watcher = TableWatcher(testing=args.testing)
    watcher.run()
Пример #8
0
 def __init__(self, config: Config) -> None:
     self.config = config
     self.afk_runner = AfkRunner()
     setup_logging("aw-runner",
                   testing=False,
                   verbose=False,
                   log_stderr=False,
                   log_file=False)
Пример #9
0
def main():
    args = parse_args()
    setup_logging("aw-qt", testing=args.testing, verbose=args.testing, log_file=True)

    _manager = Manager(testing=args.testing)
    _manager.autostart(args.autostart_modules)

    error_code = trayicon.run(_manager, testing=args.testing)
    _manager.stop_all()

    sys.exit(error_code)
Пример #10
0
def main():
    args = parse_args()
    setup_logging("aw-qt",
                  testing=args.testing,
                  verbose=args.testing,
                  log_file=True)

    _manager = Manager(testing=args.testing)
    _manager.autostart(args.autostart_modules)

    error_code = trayicon.run(_manager, testing=args.testing)
    _manager.stop_all()

    sys.exit(error_code)
Пример #11
0
def main(testing: bool, autostart_modules: Optional[str]) -> None:
    config = AwQtSettings(testing=testing)
    _autostart_modules = ([
        m.strip() for m in autostart_modules.split(",")
        if m and m.lower() != "none"
    ] if autostart_modules else config.autostart_modules)
    setup_logging("aw-qt", testing=testing, verbose=testing, log_file=True)

    _manager = Manager(testing=testing)
    _manager.autostart(_autostart_modules)

    error_code = trayicon.run(_manager, testing=testing)
    _manager.stop_all()

    sys.exit(error_code)
Пример #12
0
def main() -> None:
    """
    Start aw-watcher-terminal
    See the docs for usage
    """

    args = parse_args()

    # Load configurations
    setup_logging(client_id,
                  testing=args.testing,
                  verbose=args.verbose,
                  log_stderr=True,
                  log_file=True)

    # Create MessageHandler to which the fifo messages will be passed
    with MessageHandler(testing=args.testing) as message_handler:

        # Setup and open named pipe
        fifo_path = "{}/aw-watcher-terminal-fifo".format(
            get_data_dir(client_id))
        setup_named_pipe(fifo_path)
        pipe_fd = os.open(fifo_path, os.O_RDONLY | os.O_NONBLOCK)

        with os.fdopen(pipe_fd) as pipe:
            logger.info("Listening to pipe: {}".format(fifo_path))
            """
            Periodically read pipe for new messages
            and update the event queue
            """
            while True:
                # Read new messages from the named pipe
                try:
                    message = pipe.read()
                    if message:
                        message_handler.handle_fifo_message(message)
                except Exception as e:
                    logger.error(e)
                    traceback.print_exc()

                # Update event queue of the message handler
                try:
                    message_handler.update_event_queue()
                except Exception as e:
                    logger.error(e)
                    traceback.print_exc()

                sleep(1)
Пример #13
0
def main() -> None:
    # Set up argparse
    parser = argparse.ArgumentParser("A watcher for keyboard and mouse input to detect AFK state")
    parser.add_argument("-v", "--verbose", dest='verbose', action="store_true",
                        help='run with verbose logging')
    parser.add_argument("--testing", action="store_true",
                        help='run in testing mode')
    args = parser.parse_args()

    # Set up logging
    setup_logging("aw-watcher-afk",
                  testing=args.testing, verbose=args.verbose,
                  log_stderr=True, log_file=True)

    # Start watcher
    watcher = AFKWatcher(testing=args.testing)
    watcher.run()
Пример #14
0
def main():
    # Set up argparse
    parser = argparse.ArgumentParser(
        ("A watcher that can be invoked manually to write events to AW."))
    parser.add_argument("-v",
                        "--verbose",
                        dest='verbose',
                        action="store_true",
                        help="run with verbose logging")
    parser.add_argument("--testing",
                        action="store_true",
                        help='run in testing mode')
    parser.add_argument("-b",
                        "--bucket",
                        help="The name of the bucket to store events in.",
                        default="aw-watcher-cli")
    parser.add_argument("-d",
                        "--data",
                        help="The JSON-Formatted Event data to store.",
                        required=True)
    parser.add_argument("-D",
                        "--duration",
                        help=" The duration of the event, in seconds.",
                        default=0)
    parser.add_argument("-t",
                        "--eventtype",
                        help="The 'type' of the event to store.",
                        default="awclistatus")

    args = parser.parse_args()

    setup_logging("aw-aw_watcher_cli",
                  testing=args.testing,
                  verbose=args.verbose,
                  log_stderr=True,
                  log_file=True)

    watcher = CLIWatcher(testing=args.testing,
                         bucket=args.bucket,
                         etype=args.eventtype)
    watcher.run()
    watcher.updateLastEvent()
    watcher.addStringEvent(args.data, args.duration)
Пример #15
0
def main():
    """Called from the executable and __main__.py"""

    settings, storage_method = parse_settings()

    # FIXME: The LogResource API endpoint relies on the log being in JSON format
    # at the path specified by aw_core.log.get_log_file_path(). We probably want
    # to write the LogResource API so that it does not depend on any physical file
    # but instead add a logging handler that it can use privately.
    # That is why log_file_json=True currently.
    # UPDATE: The LogResource API is no longer available so log_file_json is now False.
    setup_logging("aw-server", testing=settings.testing, verbose=settings.verbose,
                  log_stderr=True, log_file=True, log_file_json=False)

    logger.info("Using storage method: {}".format(settings.storage))

    if settings.testing:
        logger.info("Will run in testing mode")

    logger.info("Starting up...")
    _start(host=settings.host, port=settings.port,
           testing=settings.testing, storage_method=storage_method, cors_origins=settings.cors_origins)
Пример #16
0
def main() -> None:
    parser = argparse.ArgumentParser(
        "A watcher for mpd to detect currently played song")
    parser.add_argument("-v",
                        "--verbose",
                        dest="verbose",
                        action="store_true",
                        help="run with verbose logging")
    parser.add_argument("--testing",
                        dest="testing",
                        action="store_true",
                        help="run in testing mode")
    args = parser.parse_args()

    setup_logging("aw-watcher-mpd",
                  testing=args.testing,
                  verbose=args.verbose,
                  log_stderr=True,
                  log_file=True)

    watcher = MPDWatcher(testing=args.testing)
    watcher.run()
Пример #17
0
def main():
    # Read settings from config
    config = load_config()
    args = parse_args(
        default_poll_time=config.getfloat("poll_time"),
        default_exclude_title=config.getboolean("exclude_title"),
    )

    if sys.platform.startswith("linux") and ("DISPLAY" not in os.environ
                                             or not os.environ["DISPLAY"]):
        raise Exception("DISPLAY environment variable not set")

    setup_logging(name="aw-watcher-window",
                  testing=args.testing,
                  verbose=args.verbose,
                  log_stderr=True,
                  log_file=True)

    if sys.platform == "darwin":
        from . import macos
        macos.background_ensure_permissions()

    client = ActivityWatchClient("aw-watcher-window", testing=args.testing)

    bucket_id = "{}_{}".format(client.client_name, client.client_hostname)
    event_type = "currentwindow"

    client.create_bucket(bucket_id, event_type, queued=True)

    logger.info("aw-watcher-window started")

    sleep(1)  # wait for server to start
    with client:
        heartbeat_loop(client,
                       bucket_id,
                       poll_time=args.poll_time,
                       exclude_title=args.exclude_title)