events.py 9.22 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# 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/>.


import logging
21
import datetime
22

23
from threading                  import Thread
David Trattnig's avatar
David Trattnig committed
24

25
26
27
28
29
from src.base.config            import AuraConfig
from src.base.utils             import SimpleUtil as SU
from src.base.mail              import AuraMailer
from src.plugins.monitor        import AuraMonitor
from src.plugins.trackservice   import TrackServiceHandler
30
31
32
33
34
35


class EventBinding():
    """
    A binding between the event dispatcher and some event handler.

36
    It allows you to subscribe to events in a chained way:
37
38
39
40
41
42
43
44
45

        ```
        binding = dispatcher.attach(AuraMonitor)
        binding.subscribe("on_boot").subscribe("on_play")
        ```
    """
    dispatcher = None
    instance = None

46

47
    def __init__(self, dispatcher, instance):
48
49
50
        """
        Constructor
        """
51
52
53
54
55
56
57
58
59
60
61
62
        self.dispatcher = dispatcher
        self.instance = instance


    def subscribe(self, event_type):
        """
        Subscribes the instance to some event identified by the `event_type` string.
        """
        self.dispatcher.subscribe(self.instance, event_type)
        return self


David Trattnig's avatar
David Trattnig committed
63
    def get_instance(self):
64
65
66
67
68
69
70
71
72
        """
        Returns the object within that binding.
        """
        return self.instance



class EngineEventDispatcher():
    """
73
    Executes handlers for engine events.
74
75
76
77
78
79
    """
    logger = None
    config = None

    subscriber_registry = None
    mailer = None
80
    engine = None
81
    scheduler = None
David Trattnig's avatar
David Trattnig committed
82
    monitor = None
83
84


85
    def __init__(self, engine):
86
        """
87
        Constructor
88
89
90
        """
        self.subscriber_registry = dict()
        self.logger = logging.getLogger("AuraEngine")
91
        self.config = AuraConfig.config()
92
        self.mailer = AuraMailer(self.config)
93
        self.engine = engine
94
95
96
        
        binding = self.attach(AuraMonitor)
        binding.subscribe("on_boot")
David Trattnig's avatar
David Trattnig committed
97
98
99
100
        binding.subscribe("on_sick")
        binding.subscribe("on_resurrect")

        binding = self.attach(TrackServiceHandler)
101
        binding.subscribe("on_timeslot")
102
        binding.subscribe("on_play")
103
104
        binding.subscribe("on_metadata")
        binding.subscribe("on_queue")
105
106
107
108


    def attach(self, clazz):
        """
109
        Creates an instance of the given Class.
110
        """
111
        instance = clazz(self.engine)
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
        return EventBinding(self, instance)


    def subscribe(self, instance, event_type):
        """
        Subscribes to some event type. Preferably use it via `EventBinding.subscribe(..)`.
        """
        if not event_type in self.subscriber_registry:
            self.subscriber_registry[event_type] = []
        self.subscriber_registry[event_type].append(instance)


    def call_event(self, event_type, args):
        """
        Calls all subscribers for the given event type.
        """
        if not event_type in self.subscriber_registry:
            return
        listeners = self.subscriber_registry[event_type]
        if not listeners:
            return
        for listener in listeners:
            method = getattr(listener, event_type)
            if method:
                if args:
                    method(args)
                else:
                    method()


    #
    # Events
    #


    def on_initialized(self):
        """
149
        Called when the engine is initialized, just before
150
151
        """
        self.logger.debug("on_initialized(..)")
152
        from src.scheduling.scheduler import AuraScheduler
153
        self.scheduler = AuraScheduler(self.engine)
154
155
156
157
158
159
        self.call_event("on_initialized", None)


    def on_boot(self):
        """
        Called when the engine is starting up. This happens after the initialization step.
160
        Connection to Liquidsoap should be available here.
161
162
163
164
165
166
167
168
169
        """
        self.logger.debug("on_boot(..)")
        self.call_event("on_boot", None)


    def on_ready(self):
        """
        Called when the engine is booted and ready to play.
        """
170
        self.logger.debug("on_ready(..)")
171
172
173
        self.scheduler.on_ready()


174
    def on_timeslot(self, timeslot):
175
        """
176
        Event Handler which is called by the scheduler when the current timeslot is refreshed.
177
178

        Args:
179
            source (String):    The `PlaylistEntry` object
180
        """
181
182
183
184
185
186
187
        def func(self, timeslot):        
            self.logger.debug("on_timeslot(..)")
            self.call_event("on_timeslot", timeslot)

        thread = Thread(target = func, args = (self, timeslot))
        thread.start()    

David Trattnig's avatar
David Trattnig committed
188

189
190
191
    def on_play(self, entry):
        """
        Event Handler which is called by the engine when some entry is actually playing. 
192

193
194
195
196
197
        Args:
            source (String):    The `PlaylistEntry` object
        """
        def func(self, entry):        
            self.logger.debug("on_play(..)")
David Trattnig's avatar
David Trattnig committed
198
199
200
            # Assign timestamp for play time
            entry.entry_start_actual = datetime.datetime.now()
            self.call_event("on_play", entry)
201

202
        thread = Thread(target = func, args = (self, entry))
David Trattnig's avatar
David Trattnig committed
203
        thread.start()    
204
205


206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    def on_metadata(self, data):
        """
        Event Handler which is called by the soundsystem implementation (i.e. Liquidsoap)
        when some entry is actually playing.

        Args:
            data (dict):    A collection of metadata related to the current track
        """
        def func(self, data):        
            self.logger.debug("on_metadata(..)")
            self.call_event("on_metadata", data)

        thread = Thread(target = func, args = (self, data))
        thread.start() 


222
223
224
225
    def on_stop(self, entry):
        """
        The entry on the assigned channel has been stopped playing.
        """
David Trattnig's avatar
David Trattnig committed
226
227
228
229
230
231
        def func(self, entry):        
            self.logger.debug("on_stop(..)")
            self.call_event("on_stop", entry)
        
        thread = Thread(target = func, args = (self, entry))
        thread.start() 
232
233


234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    def on_fallback_updated(self, playlist_uri):
        """
        Called when the scheduled fallback playlist has been updated.
        """
        self.logger.debug("on_fallback_updated(..)")
        self.call_event("on_fallback_updated", playlist_uri)


    def on_fallback_cleaned(self, cleaned_channel):
        """
        Called when the scheduled fallback queue has been cleaned up.
        """
        self.logger.debug("on_fallback_cleaned(..)")
        self.call_event("on_fallback_cleaned", cleaned_channel)


250
251
252
253
    def on_idle(self):
        """
        Callend when no entry is playing
        """
David Trattnig's avatar
David Trattnig committed
254
255
256
257
258
259
260
        def func(self):
            self.logger.debug("on_idle(..)")
            self.logger.error(SU.red("Currently there's nothing playing!"))
            self.call_event("on_idle", None)

        thread = Thread(target = func, args = (self, ))
        thread.start() 
261
262


263
    def on_timeslot_change(self, timeslot):
264
        """
265
        Called when the playlist or entries of the current timeslot have changed.
266
        """
267
268
269
        def func(self, timeslot):        
            self.logger.debug("on_timeslot_change(..)")
            self.call_event("on_timeslot_change", timeslot)
David Trattnig's avatar
David Trattnig committed
270

271
        thread = Thread(target = func, args = (self, timeslot))
David Trattnig's avatar
David Trattnig committed
272
        thread.start() 
273
274
275
276
277
278


    def on_queue(self, entries):
        """
        One or more entries have been queued and are currently pre-loaded.
        """
David Trattnig's avatar
David Trattnig committed
279
280
281
282
283
284
        def func(self, entries):        
            self.logger.debug("on_queue(..)")
            self.call_event("on_queue", entries)

        thread = Thread(target = func, args = (self, entries))
        thread.start() 
285
286


David Trattnig's avatar
David Trattnig committed
287
    def on_sick(self, data):
288
289
290
        """
        Called when the engine is in some unhealthy state.
        """
David Trattnig's avatar
David Trattnig committed
291
292
293
294
295
296
        def func(self, data):        
            self.logger.debug("on_sick(..)")
            self.call_event("on_sick", data)

        thread = Thread(target = func, args = (self, data))
        thread.start() 
297
298


David Trattnig's avatar
David Trattnig committed
299
    def on_resurrect(self, data):
300
301
302
        """
        Called when the engine turned healthy again after being sick.
        """
David Trattnig's avatar
David Trattnig committed
303
304
305
306
307
308
        def func(self, data):        
            self.logger.debug("on_resurrect(..)")
            self.call_event("on_resurrect", data)

        thread = Thread(target = func, args = (self, data))
        thread.start() 
309
310
311
312
313
314


    def on_critical(self, subject, message, data=None):
        """
        Callend when some critical event occurs
        """
David Trattnig's avatar
David Trattnig committed
315
316
317
318
319
320
321
322
        def func(self, subject, message, data):        
            self.logger.debug("on_critical(..)")
            if not data: data = ""
            self.mailer.send_admin_mail(subject, message + "\n\n" + str(data))
            self.call_event("on_critical", (subject, message, data))

        thread = Thread(target = func, args = (self, subject, message, data))
        thread.start()