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
        if "duration" in meta:
            duration = float(meta.get("duration"))
            data["track_duration"] = int(duration)
        else:
136
            data["track_duration"] = 0
137

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
        else:
            # This is a fallback playlog which wasn't scheduled actually (e.g. station fallback)
149
            (past, timeslot, next) = self.playlog.get_timeslots()
150
            if timeslot:
151
152
                data = {**data, **timeslot}
                data["playlist_id"] = -1
153
        
154
155
        data["log_source"] = self.config.get("api_engine_number")
        data = SU.clean_dictionary(data)
156
157
158
159
160
161
162
163
164
165
        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)
166

167
        self.logger.info("Posting playlog to Engine API...")        
168
        url = self.config.get("api_engine_store_playlog")
169
170
        headers = {'content-type': 'application/json'}
        body = json.dumps(data, indent=4, sort_keys=True, default=str)
171
        self.logger.debug("Playlog Data: " + body)
172
        response = requests.post(url, data=body, headers=headers)
173
174
175
        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"))
176
177


178
    def store_clock_info(self, data):
179
        """
180
        Posts the current and next show information to the Engine API.
181
        """
182
        planned_playlist = None
183
        if self.engine.scheduler:
184
            (fallback_type, planned_playlist) = self.engine.scheduler.get_active_playlist()
185
        (past_timeslot, current_timeslot, next_timeslot) = self.playlog.get_timeslots()            
186
187

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

        if current_timeslot:                        
191
            data["current_timeslot"] = current_timeslot
192

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
            if planned_playlist:
                data["planned_playlist"] = dict()
                data["planned_playlist"]["playlist_id"] = planned_playlist.playlist_id
                data["planned_playlist"]["entries"] = []
                for e in planned_playlist.entries:
                    entry = dict()
                    entry["track_start"] = e.entry_start
                    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                
                    entry["track_num"] = e.entry_num
                    entry["track_duration"] = e.duration
                    content_class = ResourceUtil.get_content_class(e.get_content_type())
                    entry["track_type"] = content_class.numeric
                    entry = SU.clean_dictionary(entry)
                    data["planned_playlist"]["entries"].append(entry) 

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


        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)
221
        self.logger.debug("Clock Data: " + body)
222
        response = requests.put(url, data=body, headers=headers)
223
224
225
226
227
228
229
230
231
        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:
    """
232
    Playlog keeps a history of currently queued (and playing) entries. It stores the recent
David Trattnig's avatar
David Trattnig committed
233
    active entries to a local cache `history` being able to manage concurrently playing entries.
234
235
    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
236
237
238

    The records are stored in pre-formatted dictionary structure, allowing easy serialization when
    posting them to the Engine API.
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
    """
    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
256
        self.history = deque(maxlen=100)
257
        self.current_timeslot = {}
258
259
260
261
262
263
264
265
266
267
        self.init_timeslot(None)



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

        if self.previous_timeslot:
273
            data["timeslot_start"] = self.previous_timeslot.get("timeslot_end")
274
        else:
275
            data["timeslot_start"] = None
276
277

        if next_timeslot:
278
            data["timeslot_end"] = next_timeslot.timeslot_start
279
280
        else:        
            data["timeslot_end"] = None
281

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


285

286
287
    def set_timeslot(self, timeslot):
        """
288
289
290
291
292
293
294
295
        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
296
297
        """
        if timeslot and self.previous_timeslot:
298
            if self.previous_timeslot.get("timeslot_start") == timeslot.timeslot_start:
299
300
301
                return # Avoid overwrite by multiple calls in a row

        data = {}
David Trattnig's avatar
David Trattnig committed
302
        next_timeslot = self.engine.scheduler.get_programme().get_next_timeslots(1)
David Trattnig's avatar
David Trattnig committed
303
304
305
306
        if next_timeslot: 
            next_timeslot = next_timeslot[0]
        else:
            next_timeslot = None
307
        
David Trattnig's avatar
David Trattnig committed
308
309
        # A valid timeslot from the scheduler is available
        if timeslot:              
310
            self.assign_fallback_playlist(data, timeslot)
311
312
313
            data["timeslot_id"] = timeslot.timeslot_id
            data["timeslot_start"] = timeslot.timeslot_start
            data["timeslot_end"] = timeslot.timeslot_end            
314
315
316
317
318
319
            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:  
320
                self.current_timeslot["timeslot_end"] = timeslot.timeslot_start
321
            self.previous_timeslot = self.current_timeslot       
David Trattnig's avatar
David Trattnig committed
322
            self.current_timeslot = data
323

David Trattnig's avatar
David Trattnig committed
324
325
        # Defaults for a not existing timeslot
        else:            
326
            self.init_timeslot(next_timeslot)
David Trattnig's avatar
David Trattnig committed
327
            
David Trattnig's avatar
David Trattnig committed
328
        # A valid following timeslot is available
329
        if next_timeslot:
330
331
            ns = {}
            self.assign_fallback_playlist(ns, next_timeslot)
332
333
334
            ns["timeslot_id"] = next_timeslot.timeslot_id
            ns["timeslot_start"] = next_timeslot.timeslot_start
            ns["timeslot_end"] = next_timeslot.timeslot_end
335
336
337
338
339
            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
340

341
342
343
344


    def assign_fallback_playlist(self, data, timeslot):
        """
345
346
347
348
349
        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
350
351
352
353
354
        """
        fallback_type = None
        playlist = None

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

        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):
        """
370
371
372
373
        Retrieves all available timeslots for the past, future and the current one.

        Returns:
            ({}, {}, {})
374
375
376
377
378
379
380
381
        """
        return (self.previous_timeslot, self.current_timeslot, self.next_timeslot)


    def add(self, entry):
        """
        Saves the currently preloaded [`Entry`] to the local cache.
        """
382
        self.history.append(entry) 
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


    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
419
            self.logger.info(msg)
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436

        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)