trackservice.py 14.8 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
26
from collections import deque
from datetime import datetime, timedelta

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(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
    def on_queue(self, entries):
66
        """
67
68
69
70
71
        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
72
        """
73
74
75
76
77
78
79
80
81
82
83
84
85
        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 

86
87
        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)
88
89

        data = {}
90
        data["track_start"] = entry.entry_start_actual
91
92
93
94
        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
95
        data["track_duration"] = entry.duration
96
        data["track_num"] = entry.entry_num
97
        data["track_type"] = content_class.numeric   
98
        data["playlist_id"] = entry.playlist.playlist_id
99
        data["schedule_id"] = entry.playlist.schedule.schedule_id
100
        data["show_id"] = entry.playlist.schedule.show_id
101
        data["show_name"] = entry.playlist.schedule.show_name
102
103
104
105
106
107
        data["log_source"] = self.config.get("api_engine_number")    

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

108

109
110
111
112
113
114
115
116
    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")
117
        data["track_title"] = meta.get("title")              
118
119
120
        data["track_type"] = ResourceClass.FILE.numeric
        #lqs_source = meta["source"]  

121
122
123
124
125
126
        if "duration" in meta:
            duration = float(meta.get("duration"))
            data["track_duration"] = int(duration)
        else:
            data["track_duration"] = 0          

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

129
130
131
132
133
134
135
136
137
138
139
140
141
        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
            data["schedule_id"] = entry.playlist.schedule.schedule_id
            data["show_id"] = entry.playlist.schedule.show_id
            data["show_name"] = entry.playlist.schedule.show_name
        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}       
        
142
143
        data["log_source"] = self.config.get("api_engine_number")
        data = SU.clean_dictionary(data)
144
145
146
147
148
149
150
151
152
153
        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)
154

155
        self.logger.info("Posting playlog to Engine API...")        
156
        url = self.config.get("api_engine_store_playlog")
157
158
159
        headers = {'content-type': 'application/json'}
        body = json.dumps(data, indent=4, sort_keys=True, default=str)
        response = requests.post(url, data=body, headers=headers)
160
161
162
        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"))
163
164


165
    def store_clock_info(self, data):
166
        """
167
        Posts the current and next show information to the Engine API.
168
        """
169
170
171
        current_playlist = None
        if self.engine.scheduler:
            current_playlist = self.engine.scheduler.get_active_playlist()
172
        (past_timeslot, current_timeslot, next_timeslot) = self.playlog.get_timeslots()            
173
174
175
176
177
178
179
180
181
182
183

        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
184
185
186
187
                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                
188
189
                entry["track_num"] = e.entry_num
                entry["track_duration"] = e.duration
190
191
                content_class = ResourceUtil.get_content_class(e.get_content_type)
                entry["track_type"] = content_class.numeric
192
193
194
                entry = SU.clean_dictionary(entry)
                data["current_playlist"]["entries"].append(entry)          

195
196
197
198
199
        if current_timeslot:            
            data["current_schedule"] = current_timeslot

        if next_timeslot:
            data["next_schedule"] = next_timeslot
200
201
202
203
204
205
206
207
208


        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)
209
210
211
212
213
214
215
216
217
218
        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
219
    active entries to a local cache `history` being able to manage concurrently playing entries.
220
221
    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
222
223
224

    The records are stored in pre-formatted dictionary structure, allowing easy serialization when
    posting them to the Engine API.
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    """
    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 = {}
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
        self.init_timeslot(None)



    def init_timeslot(self, next_timeslot=None):
        """
        Initializes the timeslot.
        """
        data = {}
        self.assign_fallback_playlist(data, None)
        data["schedule_id"] = -1
        data["show_id"] = -1
        data["show_name"] = ""

        if self.previous_timeslot:
            data["schedule_start"] = self.previous_timeslot.get("schedule_end")
        else:
            data["schedule_start"] = datetime.now()

        if next_timeslot:
David Trattnig's avatar
David Trattnig committed
264
            data["schedule_end"] = next_timeslot.schedule_start
265
266
267
268
        else:
            # Fake the end, because the timeslot is actually not existing
            data["schedule_end"] = datetime.now() + timedelta(hours=1) 

David Trattnig's avatar
David Trattnig committed
269
        self.current_timeslot = data
270
271
272
273


    def set_timeslot(self, timeslot):
        """
274
275
276
277
278
279
280
281
        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
282
283
        """
        if timeslot and self.previous_timeslot:
David Trattnig's avatar
David Trattnig committed
284
            if self.previous_timeslot.get("schedule_start") == timeslot.schedule_start:
285
286
287
                return # Avoid overwrite by multiple calls in a row

        data = {}
288
        next_timeslot = self.engine.scheduler.get_next_timeslots(1)
David Trattnig's avatar
David Trattnig committed
289
290
291
292
        if next_timeslot: 
            next_timeslot = next_timeslot[0]
        else:
            next_timeslot = None
293
        
David Trattnig's avatar
David Trattnig committed
294
295
        # A valid timeslot from the scheduler is available
        if timeslot:              
296
297
298
299
300
301
302
303
304
305
306
307
            self.assign_fallback_playlist(data, timeslot)
            data["schedule_id"] = timeslot.schedule_id
            data["schedule_start"] = timeslot.schedule_start
            data["schedule_end"] = timeslot.schedule_end            
            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:  
                self.current_timeslot["schedule_end"] = timeslot.schedule_start
            self.previous_timeslot = self.current_timeslot       
David Trattnig's avatar
David Trattnig committed
308
            self.current_timeslot = data
309

David Trattnig's avatar
David Trattnig committed
310
311
        # Defaults for a not existing timeslot
        else:            
312
            self.init_timeslot(next_timeslot)
David Trattnig's avatar
David Trattnig committed
313
            
David Trattnig's avatar
David Trattnig committed
314
        # A valid following timeslot is available
315
        if next_timeslot:
316
317
318
319
320
321
322
323
324
325
            ns = {}
            self.assign_fallback_playlist(ns, next_timeslot)
            ns["schedule_id"] = next_timeslot.schedule_id
            ns["schedule_start"] = next_timeslot.schedule_start
            ns["schedule_end"] = next_timeslot.schedule_end
            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
326

327
328
329
330


    def assign_fallback_playlist(self, data, timeslot):
        """
331
332
333
334
335
        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
336
337
338
339
340
        """
        fallback_type = None
        playlist = None

        if timeslot:
David Trattnig's avatar
David Trattnig committed
341
            fallback_type, playlist = self.engine.scheduler.fallback.resolve_playlist(timeslot)  
342
343
344
345
346
347
348
349
350
351
352
353
354
355

        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):
        """
356
357
358
359
        Retrieves all available timeslots for the past, future and the current one.

        Returns:
            ({}, {}, {})
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
        """
        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)
            self.logger.critical(SU.red(msg))

        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)