def clean_config(): # Remove test config file if it already exists shutil.rmtree(config_dir, ignore_errors=True) # Rerun get_config dir to create config directory dirs.get_config_dir(appname) yield # Remove test config file if it already exists shutil.rmtree(config_dir)
def test_create(): appname = "aw-core-test" section = "section" config_dir = dirs.get_config_dir(appname) # Remove test config file if it already exists shutil.rmtree(config_dir) # Create default config default_config = ConfigParser() default_config[section] = { "somestring": "Hello World!", "somevalue": 12.3 } # Load non-existing config (will create a default config file) config = load_config(appname, default_config) # Check that current config file is same as default config file assert config[section]["somestring"] == default_config[section]["somestring"] assert config[section].getfloat("somevalue") == default_config[section].getfloat("somevalue") # Modify and save config file config[section]["somevalue"] = "1000.1" save_config(appname, config) # Open non-default config file and verify that values are correct new_config = load_config(appname, default_config) assert new_config[section]["somestring"] == config[section]["somestring"] assert new_config[section].getfloat("somevalue") == config[section].getfloat("somevalue") # Remove test config file shutil.rmtree(config_dir)
def save_config(appname, config): config_dir = dirs.get_config_dir(appname) config_file_path = os.path.join(config_dir, f"{appname}.ini") with open(config_file_path, "w") as f: config.write(f) # Flush and fsync to lower risk of corrupted files f.flush() os.fsync(f.fileno())
def save_config_toml(appname: str, config: str) -> None: # Check that passed config string is valid toml assert tomlkit.parse(config) config_dir = dirs.get_config_dir(appname) config_file_path = os.path.join(config_dir, f"{appname}.toml") with open(config_file_path, "w") as f: f.write(config)
def load_config(appname, default_config): """ Take the defaults, and if a config file exists, use the settings specified there as overrides for their respective defaults. """ config = default_config config_dir = dirs.get_config_dir(appname) config_file_path = os.path.join(config_dir, "{}.ini".format(appname)) # Override defaults from existing config file if os.path.isfile(config_file_path): with open(config_file_path, 'r') as f: config.read_file(f) # Overwrite current config file (necessary in case new default would be added) save_config(appname, config) return config
def load_config_toml( appname: str, default_config: str) -> Union[dict, tomlkit.container.Container]: config_dir = dirs.get_config_dir(appname) config_file_path = os.path.join(config_dir, f"{appname}.toml") # Run early to ensure input is valid toml before writing default_config_toml = tomlkit.parse(default_config) # Override defaults from existing config file if os.path.isfile(config_file_path): with open(config_file_path) as f: config = f.read() config_toml = tomlkit.parse(config) else: # If file doesn't exist, write with commented-out default config with open(config_file_path, "w") as f: f.write(_comment_out_toml(default_config)) config_toml = dict() config = _merge(default_config_toml, config_toml) return config
def main(): logging.basicConfig(level=logging.INFO) config_dir = dirs.get_config_dir(name) config = load_config() min_delay = config[name].getfloat("min_delay") pulsetime = config[name].getfloat("pulsetime") aw = ActivityWatchClient(name, testing=False) bucketname = "{}_{}".format(aw.client_name, aw.client_hostname) aw.setup_bucket(bucketname, 'currently-editing') aw.connect() i = 1 for chunk in sys.stdin: i, data = json.loads(chunk) if data == "stop": break elif data == "config": send("config", {"min_delay": min_delay}) elif data: timestamp = datetime.utcfromtimestamp(data.pop("timestamp")) event = Event(timestamp=timestamp, data=data) aw.heartbeat(bucketname, event, pulsetime=pulsetime, queued=True)
def save_config(appname, config): config_dir = dirs.get_config_dir(appname) config_file_path = os.path.join(config_dir, "{}.ini".format(appname)) with open(config_file_path, 'w') as f: config.write(f)
def main(): logging.basicConfig(level=logging.INFO) config_dir = dirs.get_config_dir("aw-watcher-spotify") config = load_config() poll_time = float(config["aw-watcher-spotify"].get("poll_time")) username = config["aw-watcher-spotify"].get("username", None) client_id = config["aw-watcher-spotify"].get("client_id", None) client_secret = config["aw-watcher-spotify"].get("client_secret", None) if not username or not client_id or not client_secret: logger.warning( "username, client_id or client_secret not specified in config file (in folder {}). Get your client_id and client_secret here: https://developer.spotify.com/my-applications/" .format(config_dir)) sys.exit(1) # TODO: Fix --testing flag and set testing as appropriate aw = ActivityWatchClient("aw-watcher-spotify", testing=False) bucketname = "{}_{}".format(aw.client_name, aw.client_hostname) aw.create_bucket(bucketname, "currently-playing", queued=True) aw.connect() sp = auth(username, client_id=client_id, client_secret=client_secret) last_track = None track = None while True: try: track = get_current_track(sp) # from pprint import pprint # pprint(track) except spotipy.client.SpotifyException as e: print_statusline("\nToken expired, trying to refresh\n") sp = auth(username, client_id=client_id, client_secret=client_secret) continue except ConnectionError as e: logger.error( "Connection error while trying to get track, check your internet connection." ) sleep(poll_time) continue except json.JSONDecodeError as e: logger.error("Error trying to decode") sleep(0.1) continue except Exception as e: logger.error("Unknown Error") logger.error(traceback.format_exc()) sleep(0.1) continue try: # Outputs a new line when a song ends, giving a short history directly in the log if last_track: last_track_data = data_from_track(last_track, sp) if not track or (track and last_track_data["uri"] != data_from_track(track, sp)["uri"]): song_td = timedelta(seconds=last_track["progress_ms"] / 1000) song_time = int(song_td.seconds / 60), int( song_td.seconds % 60) print_statusline( "Track ended ({}:{:02d}): {title} - {artist} ({album})\n" .format(*song_time, **last_track_data)) if track: track_data = data_from_track(track, sp) song_td = timedelta(seconds=track["progress_ms"] / 1000) song_time = int(song_td.seconds / 60), int(song_td.seconds % 60) print_statusline( "Current track ({}:{:02d}): {title} - {artist} ({album})". format(*song_time, **track_data)) event = Event(timestamp=datetime.now(timezone.utc), data=track_data) aw.heartbeat(bucketname, event, pulsetime=poll_time + 1, queued=True) else: print_statusline("Waiting for track to start playing...") last_track = track except Exception as e: print("An exception occurred: {}".format(e)) traceback.print_exc() sleep(poll_time)
def test_create(): appname = "aw-core-test" section = "section" config_dir = dirs.get_config_dir(appname)
import shutil from configparser import ConfigParser import pytest import deprecation from aw_core import dirs from aw_core.config import load_config, save_config, load_config_toml, save_config_toml appname = "aw-core-test" section = "section" config_dir = dirs.get_config_dir(appname) default_config_str = f"""# A default config file, with comments! [{section}] somestring = "Hello World!" # A comment somevalue = 12.3 # Another comment somearray = ["asd", 123]""" @pytest.fixture(autouse=True) def clean_config(): # Remove test config file if it already exists shutil.rmtree(config_dir, ignore_errors=True) # Rerun get_config dir to create config directory dirs.get_config_dir(appname) yield # Remove test config file if it already exists