utils.py 10.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40

from src.base.utils import SimpleUtil as SU




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
class TimeslotRenderer:
    """
    Displays current and next timeslots in ASCII for maintainence and debugging.
    """
    logger = None
    scheduler = None
David Trattnig's avatar
David Trattnig committed
102
    programme = None
103
104
105
106
107
108
109
110


    def __init__(self, scheduler):
        """
        Constructor
        """
        self.logger = logging.getLogger("AuraEngine")
        self.scheduler = scheduler
David Trattnig's avatar
David Trattnig committed
111
        self.programme = scheduler.get_programme()
112
113
114
115
116
117
118
119
120


    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
121
        active_timeslot = self.programme.get_current_timeslot()
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145

        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
146
                active_entry = self.programme.get_current_entry()
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

                # 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
174
        next_timeslots = self.programme.get_next_timeslots()
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
219
220
221
222
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
        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)
250
                self.logger.debug(msg)
251
252
253
254
255
256
257
258
259
260
                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