utils.py 8.69 KB
Newer Older
David Trattnig's avatar
David Trattnig committed
1
#
David Trattnig's avatar
David Trattnig committed
2
# Aura Engine (https://gitlab.servus.at/aura/engine)
David Trattnig's avatar
David Trattnig committed
3
#
David Trattnig's avatar
David Trattnig committed
4
# Copyright (C) 2017-2020 - The Aura Engine Team.
David Trattnig's avatar
David Trattnig committed
5
#
David Trattnig's avatar
David Trattnig committed
6
7
8
9
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
David Trattnig's avatar
David Trattnig committed
10
#
David Trattnig's avatar
David Trattnig committed
11
12
13
14
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
David Trattnig's avatar
David Trattnig committed
15
#
David Trattnig's avatar
David Trattnig committed
16
17
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
David Trattnig's avatar
David Trattnig committed
18
19
20
21
22


import datetime
import time

23
from enum import Enum
David Trattnig's avatar
David Trattnig committed
24
25
from modules.core.channels import ChannelType
from modules.scheduling.types import PlaylistType
26
27
28
29
30
31
32



class EngineUtil:
    """
    A class for Engine utilities.
    """
33
34
35



36
37
38
39
40
41
42
43
    @staticmethod
    def get_channel_type(uri):
        """
        Returns the channel type, depending on the passed URI and source.

        Args:
            uri (String):   The URI of the source
        """
David Trattnig's avatar
David Trattnig committed
44
45
        if uri.startswith("https"):
            return ChannelType.HTTPS
46
        if uri.startswith("http"):
David Trattnig's avatar
David Trattnig committed
47
            return ChannelType.HTTP
48
49
        if uri.startswith("pool") or uri.startswith("playlist") or uri.startswith("file"):
            return ChannelType.FILESYSTEM
50
        if uri.startswith("line://"):
51
52
            return ChannelType.LIVE

David Trattnig's avatar
David Trattnig committed
53

54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

    @staticmethod
    def uri_to_filepath(base_dir, uri):
        """
        Converts a file-system URI to an actual, absolute path to the file.

        Args:
            basi_dir (String):  The location of the audio store.
            uri (String):       The URI of the file

        Returns:
            path (String):  Absolute file path
        """
        return base_dir + "/" + uri[7:] + ".flac"



71
    @staticmethod
72
    def get_playlist_type(fallback_id):
73
74
75
76
77
78
79
80
81
        """
        Converts an playlist type ID to the playlist type object.

        Args:
            id (String):    playlist type ID

        Returns:
            type (PlaylistType):  The type
        """
82
        if fallback_id == 0:
83
            return PlaylistType.DEFAULT
84
        elif fallback_id == 1:
85
            return PlaylistType.SHOW
86
        elif fallback_id == 2:
87
88
89
90
91
92
            return PlaylistType.TIMESLOT
        else:
            return PlaylistType.STATION



93
94
95
96
97
98
    @staticmethod
    def get_entries_string(entries):
        """
        Returns a list of entries as String for logging purposes.
        """
        s = ""
99
100
101
102
103
104
        if isinstance(entries, list):
            for entry in entries:
                s += str(entry)
                if entry != entries[-1]: s += ", "
        else:
            s = str(entries)
105
106
107
        return s


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    @staticmethod
    def lqs_annotate_cuein(uri, cue_in):
        """
        Wraps the given URI with a Liquidsoap Cue In annotation.

        Args:
            uri (String):   The path to the audio source
            cue_in (Float): The value in seconds wher the cue in should start
        
        Returns:
            (String):       The annotated URI
        """
        if cue_in > 0.0:
            uri = "annotate:liq_cue_in=\"%s\":%s" % (str(cue_in), uri)
        return uri

David Trattnig's avatar
David Trattnig committed
124

David Trattnig's avatar
David Trattnig committed
125
126
127
128
129
130
131
132
133
134
135
136
    @staticmethod
    def engine_info(component, version):
        """
        Prints the engine logo and version info.
        """
        return """\n
             █████╗ ██╗   ██╗██████╗  █████╗     ███████╗███╗   ██╗ ██████╗ ██╗███╗   ██╗███████╗
            ██╔══██╗██║   ██║██╔══██╗██╔══██╗    ██╔════╝████╗  ██║██╔════╝ ██║████╗  ██║██╔════╝
            ███████║██║   ██║██████╔╝███████║    █████╗  ██╔██╗ ██║██║  ███╗██║██╔██╗ ██║█████╗  
            ██╔══██║██║   ██║██╔══██╗██╔══██║    ██╔══╝  ██║╚██╗██║██║   ██║██║██║╚██╗██║██╔══╝  
            ██║  ██║╚██████╔╝██║  ██║██║  ██║    ███████╗██║ ╚████║╚██████╔╝██║██║ ╚████║███████╗
            ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝    ╚══════╝╚═╝  ╚═══╝ ╚═════╝ ╚═╝╚═╝  ╚═══╝╚══════╝
137
138
            %s v%s - Ready to play!
        \n""" % (component, version)                                                                           
David Trattnig's avatar
David Trattnig committed
139
140
141



David Trattnig's avatar
David Trattnig committed
142
143
class SimpleUtil:
    """
144
    A container class for simple utility methods.
David Trattnig's avatar
David Trattnig committed
145
146
147
    """


148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    @staticmethod
    def clean_dictionary(data):
        """
        Delete keys with the value `None` in a dictionary, recursively.
        This alters the input so you may wish to `copy` the dict first.

        Args:
            data (dict):    The dicationary

        Returns:
            (dict): 
        """
        for key, value in list(data.items()):
            if value is None:
                del data[key]
            elif isinstance(value, dict):
                SimpleUtil.clean_dictionary(value)
        return data


David Trattnig's avatar
David Trattnig committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    @staticmethod
    def fmt_time(timestamp):
        """
        Formats a UNIX timestamp to a String displaying time in the format '%H:%M:%S'.

        Args:
            (Integer) timestamp:    Unix epoch

        Returns:
            (String): Displaying the time
        """
        return datetime.datetime.fromtimestamp(timestamp).strftime('%H:%M:%S')


    @staticmethod
183
    def timestamp(date_and_time=None):
David Trattnig's avatar
David Trattnig committed
184
185
186
187
188
189
190
191
192
193
        """
        Transforms the given `datetime` into a UNIX epoch timestamp.
        If no parameter is passed, the current timestamp is returned.
        
        Args:
            (Datetime) date_and_time:    the date and time to transform.

        Returns: 
            (Integer): timestamp in seconds.
        """
194
195
        if not date_and_time:
            date_and_time = datetime.datetime.now()
David Trattnig's avatar
David Trattnig committed
196
        return time.mktime(date_and_time.timetuple())
197
198
199
200
201
202
203
204
205
206
207
208
209
210


    @staticmethod
    def strike(text):
        """
        Creates a strikethrough version of the given text.

        Args:
            (String) text:  the text to strike.

        Returns:
            (String):       the striked text.
        """
        result = ""
David Trattnig's avatar
David Trattnig committed
211
        for c in str(text):
David Trattnig's avatar
David Trattnig committed
212
            result += c + TerminalColors.STRIKE.value
213
214
        return result

David Trattnig's avatar
David Trattnig committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
    @staticmethod
    def bold(text):
        """
        Creates a bold version of the given text.
        """
        return TerminalColors.BOLD.value + text + TerminalColors.ENDC.value

    @staticmethod
    def underline(text):
        """
        Creates a underlined version of the given text.
        """
        return TerminalColors.UNDERLINE.value + text + TerminalColors.ENDC.value

    @staticmethod
    def blue(text):
        """
        Creates a blue version of the given text.
        """
        return TerminalColors.BLUE.value + text + TerminalColors.ENDC.value
235

236
237
238
239
240
    @staticmethod
    def red(text):
        """
        Creates a red version of the given text.
        """
241
        return TerminalColors.RED.value + text + TerminalColors.ENDC.value
242
243
244
245
246
247
248
249

    @staticmethod
    def pink(text):
        """
        Creates a red version of the given text.
        """
        return TerminalColors.PINK.value + text + TerminalColors.ENDC.value

David Trattnig's avatar
David Trattnig committed
250
251
252
253
254
255
    @staticmethod
    def yellow(text):
        """
        Creates a yellow version of the given text.
        """
        return TerminalColors.YELLOW.value + text + TerminalColors.ENDC.value
256

257
258
259
260
261
262
263
    @staticmethod
    def green(text):
        """
        Creates a red version of the given text.
        """
        return TerminalColors.GREEN.value + text + TerminalColors.ENDC.value

David Trattnig's avatar
David Trattnig committed
264
265
266
267
268
269
    @staticmethod
    def cyan(text):
        """
        Creates a cyan version of the given text.
        """
        return TerminalColors.CYAN.value + text + TerminalColors.ENDC.value
270
271
        

272

273
274
275
276
277
278
279
280
281
class TerminalColors(Enum):
    """
    Colors for formatting terminal output.
    """

    HEADER = "\033[95m"

    RED = "\033[31m"
    GREEN = "\033[32m"
David Trattnig's avatar
David Trattnig committed
282
    YELLOW = "\033[33m"
283
284
285
286
287
288
289
290
291
    BLUE = "\033[34m"
    PINK = "\033[35m"
    CYAN = "\033[36m"

    WARNING = "\033[31m"
    FAIL = "\033[41m"

    BOLD = "\033[1m"
    UNDERLINE = "\033[4m"
David Trattnig's avatar
David Trattnig committed
292
    STRIKE = "\u0336"
293
294

    ENDC = "\033[0m"