config works

This commit is contained in:
Hellow 2023-09-10 19:00:51 +02:00
parent b6eb1cbec6
commit 0ce6be5d2f
5 changed files with 43 additions and 34 deletions

View File

@ -89,7 +89,7 @@ class YouTubeMusicCredentials:
# the context in requests # the context in requests
context: dict context: dict
class YoutubeMusic(SuperYouTube): class YoutubeMusic(SuperYouTube):
# CHANGE # CHANGE
@ -235,6 +235,5 @@ class YoutubeMusic(SuperYouTube):
return Album() return Album()
def fetch_artist(self, source: Source, stop_at_level: int = 1) -> Artist: def fetch_artist(self, source: Source, stop_at_level: int = 1) -> Artist:
print("fuck you")
print(source) print(source)
return Artist() return Artist()

View File

@ -3,7 +3,8 @@ from typing import Optional, List, Union, Iterable, Callable
from dataclasses import dataclass from dataclasses import dataclass
import logging import logging
import toml import toml
from copy import deepcopy from copy import deepcopy, copy
from urllib.parse import urlparse, urlunparse, ParseResult
from ...exception.config import SettingValueError from ...exception.config import SettingValueError
from ..utils import comment from ..utils import comment
@ -20,7 +21,6 @@ def comment_string(uncommented: str) -> str:
processed_lines: List[str] = [] processed_lines: List[str] = []
for line in unprocessed_lines: for line in unprocessed_lines:
line: str = line.strip()
if line.startswith(COMMENT_PREFIX) or line == "": if line.startswith(COMMENT_PREFIX) or line == "":
processed_lines.append(line) processed_lines.append(line)
continue continue
@ -56,17 +56,14 @@ class Attribute:
self.name = name self.name = name
self.raw_data = {name: default_value} self.value = self._recursive_parse_object(default_value, self.parse_simple_value)
self.value = None
self.description: Optional[str] = description self.description: Optional[str] = description
self.loaded_settings: dict = None self.loaded_settings: dict = None
def initialize_from_config(self, loaded_settings: dict): def initialize_from_config(self, loaded_settings: dict):
self.loaded_settings = loaded_settings self.loaded_settings = loaded_settings
self.loaded_settings.__setitem__(self.name, self.value, True)
if not self.load_toml(self.raw_data):
logging.warning(f"Couldn't load the initial value of {self.name}: {self.raw_data[self.name]}")
def unparse_simple_value(self, value: any) -> any: def unparse_simple_value(self, value: any) -> any:
return value return value
@ -75,18 +72,27 @@ class Attribute:
return value return value
def _recursive_parse_object(self, __object, callback: Callable): def _recursive_parse_object(self, __object, callback: Callable):
__object = copy(__object)
if isinstance(__object, dict): if isinstance(__object, dict):
for key, value in __object.items(): for key, value in __object.items():
__object[key] = self._recursive_parse_object(value, callback) __object[key] = self._recursive_parse_object(value, callback)
return __object return __object
if isinstance(__object, Union[list, tuple]): if isinstance(__object, list) or (isinstance(__object, tuple) and not isinstance(__object, ParseResult)):
for i, item in enumerate(__object): for i, item in enumerate(__object):
__object[i] = self._recursive_parse_object(item, callback) __object[i] = self._recursive_parse_object(item, callback)
return __object return __object
return callback(__object) return callback(__object)
def parse(self, unparsed_value):
self.value = self._recursive_parse_object(unparsed_value, self.parse_simple_value)
return self.value
def unparse(self, parsed_value):
return self._recursive_parse_object(parsed_value, self.unparse_simple_value)
def load_toml(self, loaded_toml: dict) -> bool: def load_toml(self, loaded_toml: dict) -> bool:
""" """
@ -97,17 +103,13 @@ class Attribute:
LOGGER.warning(f"No setting by the name {self.name} found in the settings file.") LOGGER.warning(f"No setting by the name {self.name} found in the settings file.")
self.loaded_settings.__setitem__(self.name, self.value, True) self.loaded_settings.__setitem__(self.name, self.value, True)
return return
self.raw_data = loaded_toml[self.name]
_object = deepcopy(loaded_toml[self.name])
try: try:
parsed_object = self._recursive_parse_object(_object, self.parse_simple_value) self.parse(loaded_toml[self.name])
except SettingValueError as settings_error: except SettingValueError as settings_error:
logging.warning(settings_error) logging.warning(settings_error)
return False return False
self.value = parsed_object
self.loaded_settings.__setitem__(self.name, self.value, True) self.loaded_settings.__setitem__(self.name, self.value, True)
return True return True
@ -120,8 +122,9 @@ class Attribute:
if self.description is not None: if self.description is not None:
string += comment(self.description) + "\n" string += comment(self.description) + "\n"
string += toml.dumps(self.raw_data) string += toml.dumps({self.name: self.unparse(self.value)})
# print(string)
return string return string
def __str__(self): def __str__(self):

View File

@ -1,4 +1,4 @@
from pathlib import Path from pathlib import Path, PosixPath
from typing import Optional, Dict, Set from typing import Optional, Dict, Set
from urllib.parse import urlparse, urlunparse from urllib.parse import urlparse, urlunparse
import logging import logging
@ -16,11 +16,13 @@ class UrlAttribute(Attribute):
class PathAttribute(Attribute): class PathAttribute(Attribute):
def parse_simple_value(self, value: any) -> any: def parse_simple_value(self, value: any) -> Path:
if isinstance(value, Path) or isinstance(value, PosixPath):
return value
return Path(value) return Path(value)
def unparse_simple_value(self, value: any) -> any: def unparse_simple_value(self, value: Path) -> any:
return value.resolve() return str(value.resolve())

View File

@ -16,10 +16,13 @@ class ConfigDict(dict):
def __getattribute__(self, __name: str) -> Any: def __getattribute__(self, __name: str) -> Any:
return super().__getattribute__(__name) return super().__getattribute__(__name)
def __setitem__(self, __key: Any, __value: Any, from_attribute: bool = False) -> None: def __setitem__(self, __key: Any, __value: Any, from_attribute: bool = False, is_parsed: bool = False) -> None:
if not from_attribute: if not from_attribute:
attribute: Attribute = self.config_reference.attribute_map[__key] attribute: Attribute = self.config_reference.attribute_map[__key]
attribute.load_toml({attribute.name: __value}) if is_parsed:
attribute.value = __value
else:
attribute.parse(__value)
self.config_reference.write() self.config_reference.write()
__value = attribute.value __value = attribute.value
@ -44,7 +47,7 @@ class Config:
@property @property
def toml_string(self): def toml_string(self):
return "\n\n".join(component.toml_string for component in self.component_list) return "\n".join(component.toml_string for component in self.component_list)
def write(self): def write(self):
with self.config_file.open("w") as conf_file: with self.config_file.open("w") as conf_file:

View File

@ -19,12 +19,14 @@ The changes you make to the comments, will be discarded, next time you run music
Latest reset: {datetime.now()} Latest reset: {datetime.now()}
_________ __ _____
\\_ ___ \\ __ __ _/ |_ ____ / ____|
/ \\ \\/ | | \\\\ __\\_/ __ \\ | | __ __ _ _ _
\\ \\____| | / | | \\ ___/ | | |_ | / _` || | | |
\\______ /|____/ |__| \\___ > | |__| || (_| || |_| |
\\/ \\/ \_____| \__,_| \__, |
__/ |
|___/
"""), """),
Attribute(name="hasnt_yet_started", default_value=False, description="This will be set automatically, to look if it needs to run the scripts that run on start."), Attribute(name="hasnt_yet_started", default_value=False, description="This will be set automatically, to look if it needs to run the scripts that run on start."),
@ -74,10 +76,10 @@ all the error messages are shown."""),
EmptyLine(), EmptyLine(),
PathAttribute(name="music_directory", default_value=LOCATIONS.MUSIC_DIRECTORY, description="The directory, all the music will be downloaded to."), PathAttribute(name="music_directory", default_value=LOCATIONS.MUSIC_DIRECTORY.resolve(), description="The directory, all the music will be downloaded to."),
PathAttribute(name="temp_directory", default_value=LOCATIONS.TEMP_DIRECTORY, description="All temporary stuff is gonna be dumped in this directory."), PathAttribute(name="temp_directory", default_value=LOCATIONS.TEMP_DIRECTORY.resolve(), description="All temporary stuff is gonna be dumped in this directory."),
PathAttribute(name="log_file", default_value=LOCATIONS.get_log_file("download_logs.log")), PathAttribute(name="log_file", default_value=LOCATIONS.get_log_file("download_logs.log").resolve()),
PathAttribute(name="ffmpeg_binary", default_value=LOCATIONS.FFMPEG_BIN, description="Set the path to the ffmpeg binary."), PathAttribute(name="ffmpeg_binary", default_value=LOCATIONS.FFMPEG_BIN.resolve(), description="Set the path to the ffmpeg binary."),
Attribute( Attribute(
name="not_a_genre_regex", name="not_a_genre_regex",
description="These regular expressions tell music-kraken, which sub-folders of the music-directory\n" description="These regular expressions tell music-kraken, which sub-folders of the music-directory\n"