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

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

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
72
73
74
75
76
77
78
79
80
        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 

81
82
        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)
83
84

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

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

    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")
111
        data["track_title"] = meta.get("title")              
112
113
114
        data["track_type"] = ResourceClass.FILE.numeric
        #lqs_source = meta["source"]  

115
116
117
118
119
120
        if "duration" in meta:
            duration = float(meta.get("duration"))
            data["track_duration"] = int(duration)
        else:
            data["track_duration"] = 0          

121
        entry = self.playlog.resolve_entry(meta["filename"])
122
        
123
124
125
126
127
128
129
130
131
132
133
134
135
        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}       
        
136
137
        data["log_source"] = self.config.get("api_engine_number")
        data = SU.clean_dictionary(data)
138
139
140
141
142
143
144
145
146
147
148
        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)
149

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


160
    def store_clock_info(self, data):
161
        """
162
        Posts the current and next show information to the Engine API.
163
        """
164
165
166
167
        current_playlist = self.engine.scheduler.get_active_playlist()
        (past_timeslot, current_timeslot, next_timeslot) = self.playlog.get_timeslots()            
        next_timeslot = self.engine.scheduler.get_next_schedules(1)
        if next_timeslot: next_timeslot = next_timeslot[0]
168
169
170
171
172
173
174
175
176
177
178

        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
179
180
181
182
                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                
183
184
                entry["track_num"] = e.entry_num
                entry["track_duration"] = e.duration
185
186
                content_class = ResourceUtil.get_content_class(e.get_content_type)
                entry["track_type"] = content_class.numeric
187
188
189
                entry = SU.clean_dictionary(entry)
                data["current_playlist"]["entries"].append(entry)          

190
191
192
193
194
        if current_timeslot:            
            data["current_schedule"] = current_timeslot

        if next_timeslot:
            data["next_schedule"] = next_timeslot
195
196
197
198
199
200
201
202
203


        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)
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
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
        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
    active entries to a local cache `entry_history` being able to manage concurrently playing entries.
    
    It also is in charge of resolving relevant meta information of the currently playing entry for
    the TrackService handler.
    """
    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 = {}
        self.set_timeslot(None)


    def set_timeslot(self, timeslot):
        """
        """
        if timeslot and self.previous_timeslot:
            if self.previous_timeslot.get("schedule_start") == timeslot.get("schedule_start"):
                return # Avoid overwrite by multiple calls in a row

        data = {}
        next_timeslot = self.engine.scheduler.get_next_schedules(1)
        if next_timeslot: next_timeslot = next_timeslot[0]
        
        if timeslot:         
            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       

        else:
            # Defaults are not existing timeslot
            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:
                data["schedule_end"] = next_timeslot.schedule_end
            else:
                # Fake the end, because the timeslot is actually not existing
                data["schedule_end"] = datetime.now() + timedelta(hours=1) 


        if self.next_timeslot:
            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
        
        self.current_timeslot = data




    def assign_fallback_playlist(self, data, timeslot):
        """
        """
        fallback_type = None
        playlist = None

        if timeslot:
            fallback_type, playlist = self.engine.scheduler.fallback_manager.resolve_playlist(timeslot)  

        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):
        """
        """
        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)