utils.py 12.1 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


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

    @staticmethod
    def filter_24h(timeslots):
50
        """
51
        Removes entries 24h in the future and 12 hours in the past.
52
        Note: This might influence resuming (in case of a crash)
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
        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):
        """
74
        Removes all timeslot dictionaries from the past, except the one which is
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
        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
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")
111
        self.playlist_folder = self.config.abs_playlist_path()
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127



    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://"):
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
                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



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


    def __init__(self, scheduler):
        """
        Constructor
        """
        self.logger = logging.getLogger("AuraEngine")
        self.scheduler = scheduler
David Trattnig's avatar
David Trattnig committed
185
        self.programme = scheduler.get_programme()
186
187
188
189


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

        Returns:
            (String):   An ASCII representation of the current and next timeslots
        """
David Trattnig's avatar
David Trattnig committed
195
        active_timeslot = self.programme.get_current_timeslot()
196
197
198
199
200
201
202
203

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

204
            (playlist_type, resolved_playlist) = self.scheduler.resolve_playlist(active_timeslot)
205
206

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

213
            if resolved_playlist:
214
                if not planned_playlist:
215
216
                    s += "\n│      "
                    s += SU.red(f"No playlist assigned to timeslot. Instead playing the '{playlist_type.get('name')}' playlist below ↓↓↓")
217
218
219

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

David Trattnig's avatar
David Trattnig committed
220
                active_entry = self.programme.get_current_entry()
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

                # 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)
238

239
240
241
242
243
244
245
246
247
            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
248
        next_timeslots = self.programme.get_next_timeslots()
249
250
251
        if not next_timeslots:
            s += "\n│   Nothing.         "
        else:
252
            for timeslot in next_timeslots:
253
                (playlist_type, resolved_playlist) = self.scheduler.resolve_playlist(timeslot)
254
255
256
                if resolved_playlist:

                    s += "\n│   Queued timeslot %s         " % timeslot
257
                    s += "\n│      └── Playlist %s         (Type: %s)" % (resolved_playlist, SU.cyan(str(playlist_type)))
258
259
260
                    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)))
261

262
263
264
265
266
267
268
                    entries = self.preprocess_entries(resolved_playlist.entries, False)
                    s += self.build_playlist_string(entries)

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


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
    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)
324
                self.logger.debug(msg)
325
326
327
328
329
                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
330

331
332
333
334
            if not entry.queue_state == EntryQueueState.OUT_OF_SCHEDULE or not cut_oos:
                clean_entries.append(entry)

        return clean_entries