utils.py 12.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#
# Aura Engine (https://gitlab.servus.at/aura/engine)
#
# Copyright (C) 2017-2020 - The Aura Engine Team.

# 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.

# 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.

# 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/>.


import logging

from enum import Enum
24
from datetime import datetime
25
26

from src.base.utils import SimpleUtil as SU
27
from src.base.config import AuraConfig
28
29
30
31
32
33
34
35
36
37
38
39
40



class EntryQueueState(Enum):
    """
    Types of playlist entry behaviours.
    """
    OKAY = "ok"
    CUT = "cut"
    OUT_OF_SCHEDULE = "oos"



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


class TimeslotFilter():
    """
    Filters timeslot dictionaries with various criteria.
    """

    @staticmethod
    def filter_24h(timeslots):
        """ 
        Removes entries 24h in the future and 12 hours in the past.
        Note: This might influence resuming (in case of a crash)  
        single timeslots which are longer than 12 hours long.
        Think e.g. live broadcasts.
        """
        items = []
        now = SU.timestamp()
        now_plus_24hours = now + (12*60*60)
        now_minus_12hours = now - (12*60*60)

        for s in timeslots:
            start_time = datetime.strptime(s["start"], "%Y-%m-%dT%H:%M:%S")
            start_time = SU.timestamp(start_time)

            if start_time <= now_plus_24hours and start_time >= now_minus_12hours:
                items.append(s)

        return items


    @staticmethod
    def filter_past(timeslots):
        """
        Removes all timeslot dictionaries from the past, except the one which is 
        currently playing.
        """
        items = []
        now = SU.timestamp()
        for s in timeslots:
            start_time = datetime.strptime(s["start"], "%Y-%m-%dT%H:%M:%S")
            start_time = SU.timestamp(start_time)
            end_time = datetime.strptime(s["end"], "%Y-%m-%dT%H:%M:%S")
            end_time = SU.timestamp(end_time)

            # Append all elements in the future
            if start_time >= now:
                items.append(s)
             # Append the one which is playing now
            elif start_time < now < end_time:
                items.append(s)

        return items



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
class M3UPlaylistProcessor():
    """
    Renders a M3U Playlist as a engine compatible playlist dictionary.
    """
    config = None
    logging = None
    playlist_folder = None


    def __init__(self):
        """
        Constructor
        """
        self.config = AuraConfig.config()
        self.logger = logging.getLogger("AuraEngine")
        self.playlist_folder = self.config.get("audio_playlist_folder")
        if not self.playlist_folder.endswith("/"):
            self.playlist_folder += "/"



    def spread(self, entries):
        """
        Converts a playlist with M3U entries and renders them as individual playlist entries.
        """
        if not self.playlist_folder:
            return entries

        result = []
        m3u_entries = None

        for entry in entries:
            # It's a M3U Playlist which needs to be spread
            if "uri" in entry and entry["uri"].startswith("playlist://"):
                
                playlist_name = entry["uri"].split("playlist://")[1]
                self.logger.info(f"Spreading entries of M3U playlist '{playlist_name}'")
                m3u_entries = self.read_m3u_file(self.playlist_folder + playlist_name)
                result += m3u_entries
            # It's an ordinary entry to be taken as it is
            else:
                result.append(entry)

        return result



    def read_m3u_file(self, source_file):
        """
        Read entries from an M3U file.
        """
        file = open(source_file, "r")
        lines = file.readlines()
        entries = []

        for i in range(0, len(lines)):
            if lines[i].startswith("#EXTINF:"):
                metadata = lines[i].split("#EXTINF:")[1].split(",")
                entry = {
                    "file": {
                        "metadata": {
                            "artist": metadata[1].split(" - ")[0],
                            "album": "",
                            "title": metadata[1].split(" - ")[1]
                        }
                    },
                    "duration": SU.seconds_to_nano(int(metadata[0])),
                    "uri": "file://" + lines[i+1]
                }
                entries.append(entry)

        file.close()
        return entries



172
173
174
175
176
177
class TimeslotRenderer:
    """
    Displays current and next timeslots in ASCII for maintainence and debugging.
    """
    logger = None
    scheduler = None
David Trattnig's avatar
David Trattnig committed
178
    programme = None
179
180
181
182
183
184
185
186


    def __init__(self, scheduler):
        """
        Constructor
        """
        self.logger = logging.getLogger("AuraEngine")
        self.scheduler = scheduler
David Trattnig's avatar
David Trattnig committed
187
        self.programme = scheduler.get_programme()
188
189
190
191
192
193
194
195
196


    def get_ascii_timeslots(self):
        """
        Creates a printable version of the current programme (playlists and entries as per timeslot) 

        Returns:
            (String):   An ASCII representation of the current and next timeslots
        """
David Trattnig's avatar
David Trattnig committed
197
        active_timeslot = self.programme.get_current_timeslot()
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

        s = "\n\n   SCHEDULED NOW:"
        s += "\n┌──────────────────────────────────────────────────────────────────────────────────────────────────────"
        if active_timeslot:
            planned_playlist = None
            if active_timeslot.playlist:
                planned_playlist = active_timeslot.playlist

            (fallback_type, resolved_playlist) = self.scheduler.fallback.resolve_playlist(active_timeslot)

            s += "\n│   Playing timeslot %s         " % active_timeslot
            if planned_playlist: 
                if resolved_playlist and resolved_playlist.playlist_id != planned_playlist.playlist_id:
                    s += "\n│       └── Playlist %s         " % planned_playlist
                    s += "\n│       "
                    s += SU.red("↑↑↑ That's the originally planned playlist.") + ("Instead playing the fallback playlist below ↓↓↓")

            if resolved_playlist:                                  
                if not planned_playlist:
                    s += "\n│                         "
                    s += SU.red("No playlist assigned to timeslot. Instead playing the `%s` playlist below ↓↓↓" % SU.cyan(str(fallback_type)))

                s += "\n│       └── Playlist %s         " % resolved_playlist

David Trattnig's avatar
David Trattnig committed
222
                active_entry = self.programme.get_current_entry()
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

                # Finished entries
                for entry in resolved_playlist.entries:
                    if active_entry == entry:
                        break
                    else:
                        s += self.build_entry_string("\n│         └── ", entry, True)

                # Entry currently being played
                if active_entry:
                    s += "\n│         └── Entry %s | %s         " % \
                        (str(active_entry.entry_num+1), SU.green("PLAYING > "+str(active_entry)))

                    # Open entries for current playlist
                    rest_of_playlist = active_entry.get_next_entries(False)
                    entries = self.preprocess_entries(rest_of_playlist, False)
                    s += self.build_playlist_string(entries)
                    
            else:
                s += "\n│       └── %s" % (SU.red("No active playlist. There should be at least some fallback playlist running..."))
        else:
            s += "\n│   Nothing.           "
        s += "\n└──────────────────────────────────────────────────────────────────────────────────────────────────────"

        s += "\n   SCHEDULED NEXT:"
        s += "\n┌──────────────────────────────────────────────────────────────────────────────────────────────────────"

David Trattnig's avatar
David Trattnig committed
250
        next_timeslots = self.programme.get_next_timeslots()
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
        if not next_timeslots:
            s += "\n│   Nothing.         "
        else:
            for timeslot in next_timeslots:        
                (fallback_type, resolved_playlist) = self.scheduler.fallback.resolve_playlist(timeslot)
                if resolved_playlist:

                    s += "\n│   Queued timeslot %s         " % timeslot
                    s += "\n│      └── Playlist %s         (Type: %s)" % (resolved_playlist, SU.cyan(str(fallback_type)))
                    if resolved_playlist.end_unix > timeslot.end_unix:
                        s += "\n│          %s!              " % \
                        (SU.red("↑↑↑ Playlist #%s ends after timeslot #%s!" % (resolved_playlist.playlist_id, timeslot.timeslot_id)))
                    
                    entries = self.preprocess_entries(resolved_playlist.entries, False)
                    s += self.build_playlist_string(entries)

        s += "\n└──────────────────────────────────────────────────────────────────────────────────────────────────────\n\n"
        return s


    
    def build_playlist_string(self, entries):
        """
        Returns a stringified list of entries
        """
        s = ""
        is_out_of_timeslot = False

        for entry in entries:
            if entry.queue_state == EntryQueueState.OUT_OF_SCHEDULE and not is_out_of_timeslot:
                s += "\n│             %s" % \
                    SU.red("↓↓↓ These entries won't be played because they are out of timeslot.")
                is_out_of_timeslot = True

            s += self.build_entry_string("\n│         └── ", entry, is_out_of_timeslot)

        return s



    def build_entry_string(self, prefix, entry, strike):
        """
        Returns an stringified entry.
        """
        s = ""
        if entry.queue_state == EntryQueueState.CUT:
            s = "\n│             %s" % SU.red("↓↓↓ This entry is going to be cut.")

        if strike:
            entry_str = SU.strike(entry)
        else:
            entry_str = str(entry)

        entry_line = "%sEntry %s | %s" % (prefix, str(entry.entry_num+1), entry_str)
        return s + entry_line



    def preprocess_entries(self, entries, cut_oos):
        """
        Analyses and marks entries which are going to be cut or excluded.

        Args:
            entries ([PlaylistEntry]):  The playlist entries to be scheduled for playout
            cut_oos (Boolean):  If `True` entries which are 'out of timeslot' are not returned

        Returns:
            ([PlaylistEntry]):  The list of processed playlist entries
        """
        clean_entries = []

        for entry in entries:

            if entry.entry_start >= entry.playlist.timeslot.timeslot_end:
                msg = "Filtered entry (%s) after end-of timeslot (%s) ... SKIPPED" % (entry, entry.playlist.timeslot)
326
                self.logger.debug(msg)
327
328
329
330
331
332
333
334
335
336
                entry.queue_state = EntryQueueState.OUT_OF_SCHEDULE
            elif entry.end_unix > entry.playlist.timeslot.end_unix:
                entry.queue_state = EntryQueueState.CUT
            else:
                entry.queue_state = EntryQueueState.OKAY
            
            if not entry.queue_state == EntryQueueState.OUT_OF_SCHEDULE or not cut_oos:
                clean_entries.append(entry)

        return clean_entries