programme.py 20.5 KB
Newer Older
David Trattnig's avatar
David Trattnig committed
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
24
25
import threading
import queue
David Trattnig's avatar
David Trattnig committed
26
27
28

from datetime import datetime

29

David Trattnig's avatar
David Trattnig committed
30
31
32
33
from src.base.config import AuraConfig
from src.base.utils import SimpleUtil as SU
from src.core.engine import Engine

34
35
from src.scheduling.models import Timeslot, Playlist, PlaylistEntry, PlaylistEntryMetaData
from src.scheduling.api import ApiFetcher
David Trattnig's avatar
David Trattnig committed
36
37
38



39
class ProgrammeService():
David Trattnig's avatar
David Trattnig committed
40
    """
41
    The current programme of the calendar. The programme is a set of timeslots for the current day.
David Trattnig's avatar
David Trattnig committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    """
    config = None
    logger = None
    programme = None
    last_successful_fetch = None


    def __init__(self):
        """
        Constructor
        """
        self.config = AuraConfig.config()
        self.logger = logging.getLogger("AuraEngine")



    def refresh(self):
        """
        Fetch the latest programme from `AuraCalendarService` which stores it to the database.
        After that, the programme is in turn loaded from the database and stored in `self.programme`.
        """

        # Fetch programme from API endpoints
        self.logger.debug("Trying to fetch new programe from API endpoints...")
66
67
68
69
        pp = ProgrammePersistence()
        pp_queue = pp.get_queue()
        pp.start() # start fetching thread
        response = pp_queue.get() # wait for the end
David Trattnig's avatar
David Trattnig committed
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
        self.logger.debug("... Programme fetch via API done!")

        # Reset last successful fetch state
        lsf = self.last_successful_fetch
        self.last_successful_fetch = None

        if response is None:
            msg = SU.red("Trying to load programme from Engine Database, because AuraCalendarService returned an empty response.")
            self.logger.warning(msg)
        elif type(response) is list:
            self.programme = response
            if self.programme is not None and len(self.programme) > 0:
                self.last_successful_fetch = datetime.now()
                self.logger.info(SU.green("Finished fetching current programme from API"))
            if len(self.programme) == 0:
                self.logger.critical("Programme fetched from Steering/Tank has no entries!")
        elif response.startswith("fetching_aborted"):
            msg = SU.red("Trying to load programme from database only, because fetching was being aborted from AuraCalendarService! Reason: ")
            self.logger.warning(msg + response[16:])
        else:
            msg = SU.red("Trying to load programme from database only, because of an unknown response from AuraCalendarService: " + response)
            self.logger.warning(msg)

        # Always load latest programme from the database
        self.last_successful_fetch = lsf
        self.load_programme_from_db()
        self.logger.info(SU.green("Finished loading current programme from database (%s timeslots)" % str(len(self.programme))))
        for timeslot in self.programme:
            self.logger.debug("\tTimeslot %s with Playlist %s" % (str(timeslot), str(timeslot.playlist)))




    def load_programme_from_db(self):
        """
105
        Loads the programme from Engine's database and enables them via `self.enable_entries(..)`. After that, the
David Trattnig's avatar
David Trattnig committed
106
107
        current message queue is printed to the console.
        """
108
        self.programme = Timeslot.get_timeslots()
David Trattnig's avatar
David Trattnig committed
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

        if not self.programme:
            self.logger.critical(SU.red("Could not load programme from database. We are in big trouble my friend!"))
            return



    def get_current_entry(self):
        """
        Retrieves the current `PlaylistEntry` which should be played as per programme. 

        Returns:
            (PlaylistEntry): The track which is (or should) currently being played
        """
        now_unix = Engine.engine_time()

        # Load programme if necessary
        if not self.programme:
            self.load_programme_from_db()

        # Check for current timeslot
        current_timeslot = self.get_current_timeslot()
        if not current_timeslot:
            self.logger.warning(SU.red("There's no active timeslot"))
            return None

        # Check for scheduled playlist
        current_playlist = current_timeslot.playlist
        if not current_playlist:
            msg = "There's no playlist assigned to the current timeslot. Most likely a fallback will make things okay again."
            self.logger.warning(SU.red(msg))
            return None

        # Iterate over playlist entries and store the current one
        current_entry = None
        for entry in current_playlist.entries:
            if entry.start_unix <= now_unix and now_unix <= entry.end_unix:
                current_entry = entry
                break
      
        if not current_entry:
            # Nothing playing ... fallback will kick-in
            msg = "There's no entry scheduled for playlist '%s' at %s" % (str(current_playlist), SU.fmt_time(now_unix))
            self.logger.warning(SU.red(msg))
            return None

        return current_entry
 


    def get_current_timeslot(self):
        """
        Retrieves the timeslot currently to be played. 
        
        Returns:
            (Timeslot): The current timeslot
        """
        current_timeslot = None
        now_unix = Engine.engine_time()

        # Iterate over all timeslots and find the one to be played right now
        if self.programme:
            for timeslot in self.programme:
                if timeslot.start_unix <= now_unix and now_unix < timeslot.end_unix:
                    current_timeslot = timeslot
                    break
        
        return current_timeslot



    def get_next_timeslots(self, max_count=0):
        """
        Retrieves the timeslots to be played after the current one.

        Args:
            max_count (Integer): Maximum of timeslots to return, if `0` all exitsing ones are returned

        Returns:
            ([Timeslot]): The next timeslots
        """
        now_unix = Engine.engine_time()
        next_timeslots = []

        for timeslot in self.programme:
            if timeslot.start_unix > now_unix:
                if (len(next_timeslots) < max_count) or max_count == 0:
                    next_timeslots.append(timeslot)
                else:
                    break
                
        return self.filter_scheduling_window(next_timeslots)



    def filter_scheduling_window(self, timeslots):
        """
        Ignore timeslots which are beyond the scheduling window. The end of the scheduling window
        is defined by the config option `scheduling_window_end`. This value defines the seconds
        minus the actual start time of the timeslot.
        """
        now_unix = Engine.engine_time()
        len_before = len(timeslots)
        window_start = self.config.get("scheduling_window_start")
        window_end = self.config.get("scheduling_window_end")
        timeslots = list(filter(lambda s: (s.start_unix - window_end) > now_unix and (s.start_unix - window_start) < now_unix, timeslots))
        len_after = len(timeslots)
        self.logger.info("For now, skipped %s future timeslot(s) which are out of the scheduling window (-%ss <-> -%ss)" % ((len_before - len_after), window_start, window_end))

        return timeslots



    def is_timeslot_in_window(self, timeslot):
        """
        Checks if the timeslot is within the scheduling window.
        """
        now_unix = Engine.engine_time()
        window_start = self.config.get("scheduling_window_start")
        window_end = self.config.get("scheduling_window_end")

        if timeslot.start_unix - window_start < now_unix and \
            timeslot.start_unix - window_end > now_unix:

            return True
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
        return False




class ProgrammePersistence(threading.Thread):
    """ 
    The `ProgrammePersistence` service retrieves all current schedules and related
    playlists including audio files from the configured API endpoints and stores 
    it in the local database.

    To perform the API queries it utilizes the ApiFetcher class.
    """
    queue = None
    config = None
    logger = None
    fetched_timeslot_data = None
    api_fetcher = None
    stop_event = None


    def __init__(self):
        """
        Initializes the class.
        """
        threading.Thread.__init__(self)

        self.config = AuraConfig.config()
        self.logger = logging.getLogger("AuraEngine")
        self.queue = queue.Queue()
        self.stop_event = threading.Event()
        self.api_fetcher = ApiFetcher()



    def get_queue(self):
        """ 
        Retrieves the queue of fetched data.
        """
        return self.queue



    def run(self):
        """
        Fetch calendar data and store it in the database. Also handles local deletion of remotely
        deleted schedules.

        Returns
            Timeslot ([]):  An arrar of retrieved timeslots passed via `self.queue`
        """
        result = []
        now_unix = SU.timestamp()
        scheduling_window_start = self.config.get("scheduling_window_start")

        try:
            fetched_timeslot_data = self.api_fetcher.fetch()
            self.logger.debug("Timeslot data fetched from API: " + str(fetched_timeslot_data))

            # If nothing is fetched, return
            if not fetched_timeslot_data:
                self.queue.put("fetching_aborted Nothing fetched")
                return
            
            # Check if existing timeslots have been deleted
            local_timeslots = Timeslot.get_timeslots(datetime.now())
            for local_timeslot in local_timeslots:

                # Only allow deletion of timeslots which are deleted before the start of the scheduling window
                if local_timeslot.start_unix > now_unix:
                    if (local_timeslot.start_unix - scheduling_window_start) > now_unix:

                        # Filter the local timeslot from the fetched ones
                        existing_timeslot = list(filter(lambda new_timeslot: \
                            new_timeslot["timeslot_id"] == local_timeslot.timeslot_id, fetched_timeslot_data))
                        
                        if existing_timeslot:
                            # self.logger.debug("Timeslot #%s is still existing remotely!" % (local_timeslot.timeslot_id))
                            pass
                        else:
                            self.logger.info("Timeslot #%s has been deleted remotely, hence also delete it locally [%s]" % \
                                (local_timeslot.timeslot_id, str(local_timeslot)))
                            local_timeslot.delete(commit=True)
                            self.logger.info("Deleted local timeslot #%s from database" % local_timeslot.timeslot_id)

                    else:
                        msg = "Timeslot #%s has been deleted remotely. Since the scheduling window has already started, it won't be deleted locally." % \
                            local_timeslot.timeslot_id
                        self.logger.error(SU.red(msg))

            # Process fetched timeslots    
            for timeslot in fetched_timeslot_data:

                # Check timeslot for validity
                if "start" not in timeslot:
                    self.logger.warning("No 'start' of timeslot given. Skipping the timeslot: %s " % str(timeslot))
                    continue
                if "end" not in timeslot:
                    self.logger.warning("No 'end' of timeslot given. Skipping the timeslot: %s " % str(timeslot))
                    continue

                # Store the timeslot
                timeslot_db = self.store_timeslot(timeslot)

                # Store playlists to play
                self.store_playlist(timeslot_db, timeslot_db.playlist_id, timeslot["playlist"])
                if timeslot_db.schedule_fallback_id:
                    self.store_playlist(timeslot_db, timeslot_db.schedule_fallback_id, timeslot["schedule_fallback"])
                if timeslot_db.show_fallback_id:
                    self.store_playlist(timeslot_db, timeslot_db.show_fallback_id, timeslot["show_fallback"])
                if timeslot_db.station_fallback_id:
                    self.store_playlist(timeslot_db, timeslot_db.station_fallback_id, timeslot["station_fallback"])

                result.append(timeslot_db)

            # Release the mutex
            self.queue.put(result)
        except Exception as e:
            # Release the mutex
            self.logger.warning("Fetching aborted due to: %s" % str(e), e)
            self.queue.put("fetching_aborted " + str(e))

        # terminate the thread
        return



    def store_timeslot(self, timeslot):
        """
        Stores the given timeslot to the database.

        Args:
            timeslot (Timeslot):    The timeslot
        """
        timeslot_db = Timeslot.for_datetime(timeslot["start"])
        havetoadd = False

        if not timeslot_db:
            self.logger.debug("no timeslot with given timeslot id in database => create new")
            timeslot_db = Timeslot()
            havetoadd = True


        timeslot_db.show_id = timeslot["show_id"]
        timeslot_db.timeslot_id = timeslot["timeslot_id"]
        timeslot_db.timeslot_start = timeslot["start"]
        timeslot_db.timeslot_end = timeslot["end"]
        timeslot_db.show_name = timeslot["show_name"]
        timeslot_db.show_hosts = timeslot["show_hosts"]
        timeslot_db.is_repetition = timeslot["is_repetition"]
        timeslot_db.funding_category = timeslot["show_fundingcategory"]
        timeslot_db.languages = timeslot["show_languages"]
        timeslot_db.type = timeslot["show_type"]
        timeslot_db.category = timeslot["show_categories"]
        timeslot_db.topic = timeslot["show_topics"]
        timeslot_db.musicfocus = timeslot["show_musicfocus"]

        timeslot_db.playlist_id = timeslot["playlist_id"]
        timeslot_db.schedule_fallback_id = timeslot["schedule_fallback_id"]
        timeslot_db.show_fallback_id = timeslot["show_fallback_id"]
        timeslot_db.station_fallback_id = timeslot["station_fallback_id"]

        timeslot_db.store(add=havetoadd, commit=True)

        return timeslot_db



    # def store_playlist(self, timeslot_db, playlist_id, fetched_playlist, fallbackplaylist_type=0):
    def store_playlist(self, timeslot_db, playlist_id, fetched_playlist):
        """
        Stores the Playlist to the database.
        """
        if not playlist_id or not fetched_playlist:
            self.logger.debug(f"Playlist ID#{playlist_id} is not available!")
            return
            
        playlist_db = Playlist.select_playlist_for_timeslot(timeslot_db.timeslot_start, playlist_id)
        havetoadd = False

        if not playlist_db:
            playlist_db = Playlist()
            havetoadd = True

        self.logger.debug("Storing playlist %d for timeslot (%s)" % (playlist_id, str(timeslot_db)))
        playlist_db.playlist_id = playlist_id
        playlist_db.timeslot_start = timeslot_db.timeslot_start
        playlist_db.show_name = timeslot_db.show_name
        if "entries" in fetched_playlist:
            playlist_db.entry_count = len(fetched_playlist["entries"])
        else:
            playlist_db.entry_count = 0

        playlist_db.store(havetoadd, commit=True)
      
        if playlist_db.entry_count > 0:
            self.store_playlist_entries(timeslot_db, playlist_db, fetched_playlist)

        return playlist_db



    def store_playlist_entries(self, timeslot_db, playlist_db, fetched_playlist):
        """
        Stores the playlist entries to the database.
        """
        entry_num = 0
        time_marker = playlist_db.start_unix

        self.expand_entry_duration(timeslot_db, fetched_playlist)
        self.delete_orphaned_entries(playlist_db, fetched_playlist)  

        for entry in fetched_playlist["entries"]:
            entry_db = PlaylistEntry.select_playlistentry_for_playlist(playlist_db.artificial_id, entry_num)
            havetoadd = False
            if not entry_db:
                entry_db = PlaylistEntry()
                havetoadd = True

            entry_db.entry_start = datetime.fromtimestamp(time_marker)
            entry_db.artificial_playlist_id = playlist_db.artificial_id
            entry_db.entry_num = entry_num
            entry_db.duration = SU.nano_to_seconds(entry["duration"])

            if "uri" in entry:
                # FIXME Refactor mix of uri/filename/file/source
                entry_db.uri = entry["uri"]
                entry_db.source = entry["uri"]
            if "filename" in entry:
                entry_db.source = entry["filename"]

            entry_db.store(havetoadd, commit=True)

            if "file" in entry:
                self.store_playlist_entry_metadata(entry_db, entry["file"]["metadata"])

            entry_num = entry_num + 1
            time_marker += entry_db.duration



    def delete_orphaned_entries(self, playlist_db, fetched_playlist):
        """
        Deletes all playlist entries which are beyond the current playlist's `entry_count`.
        Such entries might be existing due to a remotely changed playlist, which now has
        less entries than before.
        """
        new_last_idx = len(fetched_playlist["entries"])
        existing_last_idx = PlaylistEntry.count_entries(playlist_db.artificial_id)-1

        if existing_last_idx < new_last_idx:
            return 

        for entry_num in range(new_last_idx, existing_last_idx+1, 1):
            PlaylistEntry.delete_entry(playlist_db.artificial_id, entry_num)            
            self.logger.info(SU.yellow("Deleted playlist entry %s:%s" % (playlist_db.artificial_id, entry_num)))
            entry_num += 1


    def expand_entry_duration(self, timeslot_db, fetched_playlist):
        """
        If some playlist entry doesn't have a duration assigned, its duration is expanded to the
        remaining duration of the playlist (= timeslot duration minus playlist entries with duration).
        If there's more than one entry without duration, such entries are removed from the playlist.
        """
        total_seconds = (timeslot_db.timeslot_end - timeslot_db.timeslot_start).total_seconds()
        total_duration = SU.seconds_to_nano(total_seconds)
        actual_duration = 0        
        missing_duration = []
        idx = 0

        for entry in fetched_playlist["entries"]:
            if not "duration" in entry:
                missing_duration.append(idx)
            else:
                actual_duration += entry["duration"]
            idx += 1
                
        if len(missing_duration) == 1:
            fetched_playlist["entries"][missing_duration[0]]["duration"] = total_duration - actual_duration
            self.logger.info("Expanded duration of playlist entry #%s:%s" % (fetched_playlist["id"], missing_duration[0]))

        elif len(missing_duration) > 1:
            # This case should actually never happen, as TANK doesn't allow more than one entry w/o duration anymore
            for i in reversed(missing_duration[1:-1]):
                self.logger.error(SU.red("Deleted Playlist Entry without duration: %s" % \
                    str(fetched_playlist["entries"][i])))
                del fetched_playlist["entries"][i]



    def store_playlist_entry_metadata(self, entry_db, metadata):
        """
        Stores the meta-data for a PlaylistEntry.
        """
        metadata_db = PlaylistEntryMetaData.select_metadata_for_entry(entry_db.artificial_id)
        havetoadd = False
        if not metadata_db:
            metadata_db = PlaylistEntryMetaData()
            havetoadd = True

        metadata_db.artificial_entry_id = entry_db.artificial_id

        if "artist" in metadata:
            metadata_db.artist = metadata["artist"]
        else:
            metadata_db.artist = ""
        
        if "album" in metadata:
            metadata_db.album = metadata["album"]
        else:
            metadata_db.album = ""

        if "title" in metadata:
            metadata_db.title = metadata["title"]
        else:
            metadata_db.title = ""

        metadata_db.store(havetoadd, commit=True)



    def stop(self):
        self.stop_event.set()