trackservice.py 15.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#
# Aura Engine (https://gitlab.servus.at/aura/engine)
#
# Copyright (C) 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/>.


20
import json
21
import logging
22
23
import requests

24
25
from collections                import deque
from datetime                   import datetime, timedelta
26

27
28
29
30
31
from src.base.config            import AuraConfig
from src.base.utils             import SimpleUtil as SU
from src.core.resources         import ResourceClass
from src.core.resources         import ResourceUtil
from src.scheduling.fallback    import FallbackType
32

33

34

David Trattnig's avatar
David Trattnig committed
35
class TrackServiceHandler():
36
    """
37
    Sends the trackservice entry and studio clock information to the `engine-api` REST endpoint.
38
39
40
    """
    logger = None
    config = None
41
42
    engine = None
    playlog = None
43
44


45
    def __init__(self, engine):
46
47
48
49
        """
        Initialize.
        """
        self.logger = logging.getLogger("AuraEngine")
50
51
52
        self.config = AuraConfig.config()
        self.engine = engine
        self.playlog = Playlog(engine)
53
54


55

56
    def on_timeslot_start(self, timeslot=None):
57
        """
58
        Some new timeslot has just started.
59
        """
60
61
62
        if timeslot:
            self.logger.info(f"Active timeslot used for trackservice '{timeslot}'")
        self.playlog.set_timeslot(timeslot)
63
64


65
66
67
68
69
70
71
72
73
74
75

    def on_timeslot_end(self, timeslot):
        """
        Called when a timeslot ends.
        """
        if timeslot:
            self.logger.info(f"Timeslot '{timeslot}' just ended")
        self.playlog.set_timeslot(None)



76
    def on_queue(self, entries):
77
        """
78
79
80
81
82
        Items have been queued. They are stored to the local playlog, allowing later
        matching and retrieval to augment meta-information.

        Args:
            entries ([PlaylistEntry]):  The entries which got queued
83
        """
84
85
86
87
88
89
90
91
92
93
94
95
96
        for entry in entries:
            self.playlog.add(entry)


    def on_play(self, entry):
        """
        Some `PlaylistEntry` started playing. This is likely only a LIVE or STREAM entry.
        """     
        content_class = ResourceUtil.get_content_class(entry.get_content_type())
        if content_class == ResourceClass.FILE:
            # Files are handled by "on_metadata" called via Liquidsoap
            return 

97
98
        diff = (entry.entry_start_actual - entry.entry_start).total_seconds()
        self.logger.info("There's a difference of %s seconds between planned and actual start of the entry" % diff)
99
100

        data = {}
101
        data["track_start"] = entry.entry_start_actual
102
103
104
105
        if entry.meta_data:
            data["track_artist"] = entry.meta_data.artist
            data["track_album"] = entry.meta_data.album
            data["track_title"] = entry.meta_data.title
106
        data["track_duration"] = entry.duration
107
        data["track_num"] = entry.entry_num
108
        data["track_type"] = content_class.numeric   
109
        data["playlist_id"] = entry.playlist.playlist_id
110
111
112
        data["timeslot_id"] = entry.playlist.timeslot.timeslot_id
        data["show_id"] = entry.playlist.timeslot.show_id
        data["show_name"] = entry.playlist.timeslot.show_name
113
114
115
116
117
118
        data["log_source"] = self.config.get("api_engine_number")    

        self.store_trackservice(data)
        self.store_clock_info(data)
        

119

120
121
122
123
124
125
126
127
    def on_metadata(self, meta):
        """
        Some metadata update was sent from Liquidsoap.
        """
        data = {}
        data["track_start"] = meta.get("on_air")
        data["track_artist"] = meta.get("artist")
        data["track_album"] = meta.get("album")
128
        data["track_title"] = meta.get("title")              
129
130
131
        data["track_type"] = ResourceClass.FILE.numeric
        #lqs_source = meta["source"]  

132
133
134
135
136
137
        if "duration" in meta:
            duration = float(meta.get("duration"))
            data["track_duration"] = int(duration)
        else:
            data["track_duration"] = 0          

138
        entry = self.playlog.resolve_entry(meta["filename"])
David Trattnig's avatar
David Trattnig committed
139

140
141
142
143
        if entry:
            # This is a playlog according to the scheduled playlist (normal or fallback)
            data["track_num"] = entry.entry_num
            data["playlist_id"] = entry.playlist.playlist_id
144
145
146
            data["timeslot_id"] = entry.playlist.timeslot.timeslot_id
            data["show_id"] = entry.playlist.timeslot.show_id
            data["show_name"] = entry.playlist.timeslot.show_name
147
148
149
150
151
152
        else:
            # This is a fallback playlog which wasn't scheduled actually (e.g. station fallback)
            (past, timeslot, next) = self.playlog.get_timeslots()            
            if timeslot:
                data = {**data, **timeslot}       
        
153
154
        data["log_source"] = self.config.get("api_engine_number")
        data = SU.clean_dictionary(data)
155
156
157
158
159
160
161
162
163
164
        self.store_trackservice(data)
        self.store_clock_info(data)

        

    def store_trackservice(self, data):
        """
        Posts the given `PlaylistEntry` to the Engine API Playlog.
        """        
        data = SU.clean_dictionary(data)
165

166
        self.logger.info("Posting playlog to Engine API...")        
167
        url = self.config.get("api_engine_store_playlog")
168
169
170
        headers = {'content-type': 'application/json'}
        body = json.dumps(data, indent=4, sort_keys=True, default=str)
        response = requests.post(url, data=body, headers=headers)
171
172
173
        if response.status_code != 204 or response.status_code != 204:            
            msg = f"Error while posting playlog to Engine API: {response.reason} (Error {response.status_code})\n"                
            self.logger.info(SU.red(msg) + response.content.decode("utf-8"))
174
175


176
    def store_clock_info(self, data):
177
        """
178
        Posts the current and next show information to the Engine API.
179
        """
180
181
        current_playlist = None
        if self.engine.scheduler:
182
            (fallback_type, current_playlist) = self.engine.scheduler.get_active_playlist()
183
        (past_timeslot, current_timeslot, next_timeslot) = self.playlog.get_timeslots()            
184
185
186
187
188
189
190
191
192
193
194

        data = dict()
        data["engine_source"] = self.config.get("api_engine_number")

        if current_playlist:
            data["current_playlist"] = dict()
            data["current_playlist"]["playlist_id"] = current_playlist.playlist_id
            data["current_playlist"]["entries"] = []
            for e in current_playlist.entries:
                entry = dict()
                entry["track_start"] = e.entry_start
195
196
197
198
                if e.meta_data:                
                    entry["track_artist"] = e.meta_data.artist
                    entry["track_album"] = e.meta_data.album                
                    entry["track_title"] = e.meta_data.title                
199
200
                entry["track_num"] = e.entry_num
                entry["track_duration"] = e.duration
201
                content_class = ResourceUtil.get_content_class(e.get_content_type())
202
                entry["track_type"] = content_class.numeric
203
204
205
                entry = SU.clean_dictionary(entry)
                data["current_playlist"]["entries"].append(entry)          

206
        if current_timeslot:            
207
            data["current_timeslot"] = current_timeslot
208
209

        if next_timeslot:
210
            data["next_timeslot"] = next_timeslot
211
212
213
214
215
216
217
218
219


        data = SU.clean_dictionary(data)

        self.logger.info("Posting clock info update to Engine API...")        
        url = self.config.get("api_engine_store_clock")
        headers = {'content-type': 'application/json'}
        body = json.dumps(data, indent=4, sort_keys=True, default=str)
        response = requests.put(url, data=body, headers=headers)
220
221
222
223
224
225
226
227
228
229
        if response.status_code != 204 or response.status_code != 204:            
            msg = f"Error while posting clock-info to Engine API: {response.reason} (Error {response.status_code})\n"                
            self.logger.info(SU.red(msg) + response.content.decode("utf-8"))   




class Playlog:
    """
    Playlog keeps a short history of currently playing entries. It stores the recent
David Trattnig's avatar
David Trattnig committed
230
    active entries to a local cache `history` being able to manage concurrently playing entries.
231
232
    It also is in charge of resolving relevant meta information of the currently playing entry for
    the TrackService handler.
David Trattnig's avatar
David Trattnig committed
233
234
235

    The records are stored in pre-formatted dictionary structure, allowing easy serialization when
    posting them to the Engine API.
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    """
    config = None
    logger = None
    engine = None
    history = None
    previous_timeslot = None
    current_timeslot = None
    next_timeslot = None


    def __init__(self, engine):
        """
        Constructor
        """
        self.config = AuraConfig.config()
        self.logger = logging.getLogger("AuraEngine")
        self.engine = engine
        self.history = deque([None, None, None])
        self.current_timeslot = {}
255
256
257
258
259
260
261
262
263
264
        self.init_timeslot(None)



    def init_timeslot(self, next_timeslot=None):
        """
        Initializes the timeslot.
        """
        data = {}
        self.assign_fallback_playlist(data, None)
265
        data["timeslot_id"] = -1
266
267
268
269
        data["show_id"] = -1
        data["show_name"] = ""

        if self.previous_timeslot:
270
            data["timeslot_start"] = self.previous_timeslot.get("timeslot_end")
271
        else:
272
            data["timeslot_start"] = datetime.now()
273
274

        if next_timeslot:
275
            data["timeslot_end"] = next_timeslot.timeslot_start
276
277
        else:
            # Fake the end, because the timeslot is actually not existing
278
            data["timeslot_end"] = datetime.now() + timedelta(hours=1) 
279

David Trattnig's avatar
David Trattnig committed
280
        self.current_timeslot = data
281
282
283
284


    def set_timeslot(self, timeslot):
        """
285
286
287
288
289
290
291
292
        Sets the current timeslot and proper default values if no timeslot is available.
        Any previous timeslot is stored to `self.previous_timeslot` and the following one
        to `self.next_timeslot`.

        This method is protect by overwritting by multiple calls with the same timeslot.

        Args:
            timeslot (Timeslot):    The current timeslot
293
294
        """
        if timeslot and self.previous_timeslot:
295
            if self.previous_timeslot.get("timeslot_start") == timeslot.timeslot_start:
296
297
298
                return # Avoid overwrite by multiple calls in a row

        data = {}
David Trattnig's avatar
David Trattnig committed
299
        next_timeslot = self.engine.scheduler.get_programme().get_next_timeslots(1)
David Trattnig's avatar
David Trattnig committed
300
301
302
303
        if next_timeslot: 
            next_timeslot = next_timeslot[0]
        else:
            next_timeslot = None
304
        
David Trattnig's avatar
David Trattnig committed
305
306
        # A valid timeslot from the scheduler is available
        if timeslot:              
307
            self.assign_fallback_playlist(data, timeslot)
308
309
310
            data["timeslot_id"] = timeslot.timeslot_id
            data["timeslot_start"] = timeslot.timeslot_start
            data["timeslot_end"] = timeslot.timeslot_end            
311
312
313
314
315
316
            data["show_id"] = timeslot.show_id
            data["show_name"] = timeslot.show_name            
            data = SU.clean_dictionary(data)

            # Any previous (fake) timeslots should get the proper end now
            if not self.previous_timeslot:  
317
                self.current_timeslot["timeslot_end"] = timeslot.timeslot_start
318
            self.previous_timeslot = self.current_timeslot       
David Trattnig's avatar
David Trattnig committed
319
            self.current_timeslot = data
320

David Trattnig's avatar
David Trattnig committed
321
322
        # Defaults for a not existing timeslot
        else:            
323
            self.init_timeslot(next_timeslot)
David Trattnig's avatar
David Trattnig committed
324
            
David Trattnig's avatar
David Trattnig committed
325
        # A valid following timeslot is available
326
        if next_timeslot:
327
328
            ns = {}
            self.assign_fallback_playlist(ns, next_timeslot)
329
330
331
            ns["timeslot_id"] = next_timeslot.timeslot_id
            ns["timeslot_start"] = next_timeslot.timeslot_start
            ns["timeslot_end"] = next_timeslot.timeslot_end
332
333
334
335
336
            ns["show_id"] = next_timeslot.show_id
            ns["show_name"] = next_timeslot.show_name
            ns["playlist_id"] = next_timeslot.playlist_id
            ns = SU.clean_dictionary(ns)
            self.next_timeslot = ns
David Trattnig's avatar
David Trattnig committed
337

338
339
340
341


    def assign_fallback_playlist(self, data, timeslot):
        """
342
343
344
345
346
        Assigns fallback info to the given timeslot.

        Args:
            data ({}):              The dictionary holding the (virtual) timeslot
            timeslot (Timeslot):    The actual timeslot object to retrieve fallback info from
347
348
349
350
351
        """
        fallback_type = None
        playlist = None

        if timeslot:
David Trattnig's avatar
David Trattnig committed
352
            fallback_type, playlist = self.engine.scheduler.fallback.resolve_playlist(timeslot)  
353
354
355
356
357
358
359
360
361
362
363
364
365
366

        if playlist:
            data["playlist_id"] = playlist.playlist_id
        else:
            data["playlist_id"] = -1

        if fallback_type:
            data["fallback_type"] = fallback_type.id
        else:
            data["fallback_type"] = FallbackType.STATION.id


    def get_timeslots(self):
        """
367
368
369
370
        Retrieves all available timeslots for the past, future and the current one.

        Returns:
            ({}, {}, {})
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
        """
        return (self.previous_timeslot, self.current_timeslot, self.next_timeslot)


    def add(self, entry):
        """
        Saves the currently preloaded [`Entry`] to the local cache.
        """
        self.history.pop() 
        self.history.appendleft(entry) 


    def get_recent_entries(self):
        """
        Retrieves the currently playing [`Entry`] from the local cache.
        """
        return self.history


    def resolve_entry(self, uri):
        """
        Retrieves the playlog matching the provied file URI.

        Args:
            path (String):    The URI of the resource
        """
        result = None
        entries = self.get_recent_entries()
        if not entries:
            return None

        for entry in entries:
            if entry:
                entry_source = entry.source

                if entry.get_content_type() in ResourceClass.FILE.types:
                    base_dir = self.config.get("audio_source_folder")
                    extension = self.config.get("audio_source_extension")
                    entry_source = ResourceUtil.uri_to_filepath(base_dir, entry.source, extension)
                if entry_source == uri:
                    self.logger.info("Resolved '%s' entry '%s' for URI '%s'" % (entry.get_content_type(), entry, uri))
                    result = entry
                    break

        if not result:
            msg = "Found no entry in the recent history which matches the given source '%s'" % (uri)
David Trattnig's avatar
David Trattnig committed
417
            self.logger.info(msg)
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434

        return result


    def print_entry_history(self):
        """
        Prints all recents entries of the history.
        """
        msg = "Active entry history:\n"
        for entries in self.history:
            msg += "["
            for e in entries:
                msg += "\n" + str(e)
            msg += "]"
        self.logger.info(msg)