summaryrefslogtreecommitdiff
path: root/tidal_dl_ng/helper/path.py
blob: fc8602c4bab0aa64f578d4910813eea76e0475de (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import glob
import os
import re
from collections.abc import Callable
from pathlib import Path

from pathvalidate import sanitize_filename, sanitize_filepath
from pathvalidate.error import ValidationError
from tidalapi import Album, Mix, Playlist, Track, UserPlaylist, Video

from tidal_dl_ng import __name_display__
from tidal_dl_ng.constants import MediaType


def path_home() -> str:
    if "XDG_CONFIG_HOME" in os.environ:
        return os.environ["XDG_CONFIG_HOME"]
    elif "HOME" in os.environ:
        return os.environ["HOME"]
    elif "HOMEDRIVE" in os.environ and "HOMEPATH" in os.environ:
        return os.path.join(os.environ["HOMEDRIVE"], os.environ["HOMEPATH"])
    else:
        return os.path.abspath("./")


def path_base() -> str:
    path_config: str = ".config"
    path_base: str = os.path.join(path_home(), path_config, __name_display__)

    return path_base


def path_file_log() -> str:
    # TODO: Remove this soon. Only for migration to new dir.
    old = os.path.join(path_home(), ".tidal-dl-ng.log")
    if os.path.isfile(old):
        os.makedirs(path_base(), exist_ok=True)
        os.rename(old, os.path.join(path_base(), "app.log"))

    return os.path.join(path_base(), "app.log")


def path_file_token() -> str:
    # TODO: Remove this soon. Only for migration to new dir.
    old = os.path.join(path_home(), ".tidal-dl-ng_token.json")
    if os.path.isfile(old):
        os.makedirs(path_base(), exist_ok=True)
        os.rename(old, os.path.join(path_base(), "token.json"))

    return os.path.join(path_base(), "token.json")


def path_file_settings() -> str:
    # TODO: Remove this soon. Only for migration to new dir.
    old = os.path.join(path_home(), ".tidal-dl-ng_settings.json")
    if os.path.isfile(old):
        os.makedirs(path_base(), exist_ok=True)
        os.rename(old, os.path.join(path_base(), "settings.json"))

    return os.path.join(path_base(), "settings.json")


def format_path_media(fmt_template: str, media: Track | Album | Playlist | UserPlaylist | Video | Mix) -> str:
    result = fmt_template

    # Search track format template for placeholder.
    regex = r"\{(.+?)\}"
    matches = re.finditer(regex, fmt_template, re.MULTILINE)
    fn_format = get_format_fn(media)

    for _matchNum, match in enumerate(matches, start=1):
        template_str = match.group()
        result_fmt = fn_format(match.group(1), media)

        if result_fmt:
            value = sanitize_filename(result_fmt)
            result = result.replace(template_str, value)

    return result


def format_str_track(name: str, media: Track) -> str | bool:
    result: str | bool = False

    if name == "track_num":
        result = str(media.track_num).rjust(2, "0")
    elif name == "artist_name":
        result = ", ".join(artist.name for artist in media.artists)
    elif name == "track_title":
        result = media.name

    return result


def format_str_album(name: str, media: Album) -> str | bool:
    result: str | bool = False

    if name == "album_title":
        result = media.name
    elif name == "artist_name":
        result = media.artist.name

    return result


def format_str_playlist(name: str, media: Playlist) -> str | bool:
    result: str | bool = False

    if name == "playlist_name":
        result = media.name

    return result


def format_str_mix(name: str, media: Mix) -> str | bool:
    result: str | bool = False

    if name == "mix_name":
        result = media.title

    return result


def format_str_video(name: str, media: Video) -> str | bool:
    result: str | bool = False

    if name == "artist_name":
        result = ", ".join(artist.name for artist in media.artists)
    elif name == "track_title":
        result = media.name

    return result


def get_format_fn(media: Track | Album | Playlist | UserPlaylist | Video | Mix) -> Callable:
    result = None

    if isinstance(media, Track):
        result = format_str_track
    elif isinstance(media, Album):
        result = format_str_album
    elif isinstance(media, Playlist | UserPlaylist):
        result = format_str_playlist
    elif isinstance(media, Mix):
        result = format_str_mix
    elif isinstance(media, Video):
        result = format_str_video

    return result


def get_format_template(
    media: Track | Album | Playlist | UserPlaylist | Video | Mix | MediaType, settings
) -> str | bool:
    result = False

    if isinstance(media, Track) or media == MediaType.TRACK:
        result = settings.data.format_track
    elif isinstance(media, Album) or media == MediaType.ALBUM:
        result = settings.data.format_album
    elif isinstance(media, Playlist | UserPlaylist) or media == MediaType.PLAYLIST:
        result = settings.data.format_playlist
    elif isinstance(media, Mix) or media == MediaType.MIX:
        result = settings.data.format_mix
    elif isinstance(media, Video) or media == MediaType.VIDEO:
        result = settings.data.format_video

    return result


def path_file_sanitize(path_file: str, adapt: bool = False) -> (bool, str):
    # Split into path and filename
    pathname, filename = os.path.split(path_file)

    # Sanitize path
    try:
        pathname_sanitized = sanitize_filepath(
            pathname, replacement_text=" ", validate_after_sanitize=True, platform="auto"
        )
    except ValidationError:
        # If adaption of path is allowed in case of an error set path to HOME.
        if adapt:
            pathname_sanitized = Path.home()
        else:
            raise

    # Sanitize filename
    try:
        filename_sanitized = sanitize_filename(
            filename, replacement_text=" ", validate_after_sanitize=True, platform="auto"
        )
        filename_sanitized_extension = Path(filename_sanitized).suffix

        # Check if the file extension was removed by shortening the filename length
        if filename_sanitized_extension == "":
            # Add the original file extension
            file_extension = "_" + Path(path_file).suffix
            filename_sanitized = filename_sanitized[: -len(file_extension)] + file_extension
    except ValidationError as e:
        # TODO: Implement proper exception handling and logging.
        print(e)

        raise

    # Join path and filename
    result = os.path.join(pathname_sanitized, filename_sanitized)

    return result


def check_file_exists(path_file: str, extension_ignore: bool = False):
    if extension_ignore:
        path_file = Path(path_file).stem + ".*"

    # TODO: Check what happens is (no) files .
    result = bool(glob.glob(path_file))

    return result