engine.py 37.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#
#  engine
#
#  Playout Daemon for autoradio project
#
#
#  Copyright (C) 2017-2018 Gottfried Gaisbauer <gottfried.gaisbauer@servus.at>
#
#  This file is part of engine.
#
#  engine is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  any later version.
#
#  engine 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with engine. If not, see <http://www.gnu.org/licenses/>.
#

25
26
import time
import logging
27
import json
28

David Trattnig's avatar
David Trattnig committed
29
30
31
32
33
from urllib.parse import urlparse, ParseResult

from modules.base.enum          import ChannelType, Channel, TransitionType, LiquidsoapResponse, EntryPlayState
from modules.base.utils         import TerminalColors, SimpleUtil, EngineUtil
from modules.base.exceptions    import LQConnectionError, InvalidChannelException, NoActiveEntryException, EngineMalfunctionException, LQStreamException, LoadSourceException
34
from modules.communication.liquidsoap.playerclient import LiquidSoapPlayerClient
35
# from modules.communication.liquidsoap.recorderclient import LiquidSoapRecorderClient
David Trattnig's avatar
David Trattnig committed
36
37
38
from modules.core.startup       import StartupThread
from modules.core.state         import PlayerStateService
from modules.core.monitor       import Monitoring
39
from modules.communication.mail import AuraMailer
40

41

David Trattnig's avatar
David Trattnig committed
42
class SoundSystem():
43
    """ 
David Trattnig's avatar
David Trattnig committed
44
    SoundSystem Class
45
46

    Uses LiquidSoapClient, but introduces more complex commands, transactions and error handling.
47
    """
48
    client = None
49
    logger = None
50
    transaction = 0
51
    channels = None
52
    scheduler = None
David Trattnig's avatar
David Trattnig committed
53
    monitoring = None
54
    auramailer = None
55
    is_liquidsoap_running = False
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
56
    connection_attempts = 0
57
    disable_logging = False
58
59
    fade_in_active = False
    fade_out_active = False
60

61
62
63
64
65
66
    # Active Channel & Entry Handling
    active_channel_type = None
    active_channel = None
    player_state = None


67
    def __init__(self, config):
68
        """
69
70
71
72
73
        Initializes the communicator by establishing a Socket connection
        to Liquidsoap.

        Args:
            config (AuraConfig):    The configuration
74
        """
75
        self.config = config
76
77
        self.logger = logging.getLogger("AuraEngine")

78
79
        self.client = LiquidSoapPlayerClient(config, "engine.sock")
        # self.lqcr = LiquidSoapRecorderClient(config, "record.sock")
80
        self.auramailer = AuraMailer(self.config)
81
82
        self.monitoring = Monitoring(config, self, self.auramailer)
        
David Trattnig's avatar
David Trattnig committed
83
        self.is_active()
84

85
86
87
        # Initialize Default Channels
        self.active_channel = {
            ChannelType.FILESYSTEM: Channel.FILESYSTEM_A,
David Trattnig's avatar
David Trattnig committed
88
            ChannelType.HTTP: Channel.HTTP_A,
David Trattnig's avatar
David Trattnig committed
89
            ChannelType.HTTPS: Channel.HTTPS_A,
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
            ChannelType.LIVE: Channel.LIVE_0
        }
        # self.active_entries = {}
        self.player_state = PlayerStateService(config)



    def start(self):
        """
        Starts the soundsystem.
        """
        # Sleep needed, because the socket is created too slowly by Liquidsoap
        time.sleep(1)
        self.enable_transaction()
        time.sleep(1)

        self.mixer_start()

        # Setting init params like a blank file
        install_dir = self.config.get("install_dir")
        channel = self.active_channel[ChannelType.FILESYSTEM]
        self.playlist_push(channel, install_dir + "/configuration/blank.flac")

        self.disable_transaction()
        self.is_liquidsoap_running = True
        self.logger.info(SimpleUtil.green("Engine Core ------[ connected ]-------- Liquidsoap"))

David Trattnig's avatar
David Trattnig committed
117
118
119
120
121
122
123
124
125
126
127
        # Start Monitoring
        is_valid = self.monitoring.has_valid_status(False)
        status = self.monitoring.get_status()
        self.logger.info("Status Monitor:\n%s" % json.dumps(status, indent=4))
        if not is_valid:
            self.logger.info("Engine Status: " + SimpleUtil.red(status["engine"]["status"]))
            raise EngineMalfunctionException
        else:
            self.logger.info("Engine Status: " + SimpleUtil.green("OK"))


128
129
130

    def is_ready(self):
        """
131
        Returns `True` if the soundsystem is connected to Liquidsoap and is ready to be used.
132
133
134
        """
        return self.is_liquidsoap_running

135

136
    #
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    #   MIXER : GENERAL
    # 


    def mixer_start(self):
        # Reset channels and reload them
        channels = self.reload_channels()

        # For all available channels
        for c in channels:
            # Set volume to zero
            self.channel_volume(c, "0")
            # And activate this channel
            self.channel_activate(c, True)
151
152


153
    # ------------------------------------------------------------------------------------------ #
154
155
156
    # def set_volume(self, mixernumber, volume):
    #     #return self.client.command("mixer", 'volume', mixernumber, str(volume))
    #     return self.__send_lqc_command__(self.client, "mixer", "volume", mixernumber, volume)
David Trattnig's avatar
David Trattnig committed
157

158
159
160
161
162
    # ------------------------------------------------------------------------------------------ #
    def get_active_mixer(self):
        """
        get active mixer in liquidsoap server
        :return:
163
        """
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        activeinputs = []

        # enable more control over the connection
        self.enable_transaction()

        inputs = self.get_all_channels()

        cnt = 0
        for input in inputs:
            status = self.__get_mixer_status__(cnt)

            if "selected=true" in status:
                activeinputs.append(input)

            cnt = cnt + 1

        self.disable_transaction()

        return activeinputs
183

184
    # ------------------------------------------------------------------------------------------ #
185
186
    def get_mixer_status(self):
        inputstate = {}
187

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
        self.enable_transaction()

        inputs = self.get_all_channels()

        cnt = 0
        for input in inputs:
            inputstate[input] = self.__get_mixer_status__(cnt)
            cnt = cnt + 1

        self.disable_transaction()

        return inputstate


    # ------------------------------------------------------------------------------------------ #
    def get_mixer_volume(self, channel):
        return False

    # ------------------------------------------------------------------------------------------ #
    def __get_mixer_status__(self, mixernumber):
        return self.__send_lqc_command__(self.client, "mixer", "status", mixernumber)


    #
    #   MIXER : CHANNELS
    #


David Trattnig's avatar
David Trattnig committed
216
217
218
    def load(self, entry):
        """
        Preloads the entry. This is required before the actual `play(..)` can happen.
219

David Trattnig's avatar
David Trattnig committed
220
221
222
223
224
        Note his method is blocking until loading has finished. If this method is called 
        asynchroniously, the progress on the preloading state can be looked up in `entry.state`.
        """
        entry.status = EntryPlayState.LOADING
        self.logger.info("Loading entry '%s'" % entry)
225
        is_ready = False
226

227
228
229
        # Choose and save the input channel
        if entry.type == ChannelType.LIVE:
            entry.channel = "linein_" + entry.source.split("line://")[1]
230
            is_ready = True
231
232
233
        else:
            self.player_state.set_active_entry(entry)
            entry.channel = self.channel_swap(entry.type)
234

David Trattnig's avatar
David Trattnig committed
235
236
        # PLAYLIST
        if entry.type == ChannelType.FILESYSTEM:
237
            is_ready = self.playlist_push(entry.channel, entry.source)
David Trattnig's avatar
David Trattnig committed
238
239
            
        # STREAM
David Trattnig's avatar
David Trattnig committed
240
        elif entry.type == ChannelType.HTTP or entry.type == ChannelType.HTTPS:
241
            is_ready = self.stream_load_entry(entry)
David Trattnig's avatar
David Trattnig committed
242

243
244
        if is_ready == True:
            entry.status = EntryPlayState.READY
245
246
247


    def play(self, entry, transition):
David Trattnig's avatar
David Trattnig committed
248
        """
249
250
        Plays a new `Entry`. In case of a new schedule (or some intented, immediate transition),
        a clean channel is selected and transitions between old and new channel is performed.
David Trattnig's avatar
David Trattnig committed
251

David Trattnig's avatar
David Trattnig committed
252
253
        This method expects that the entry is pre-loaded using `load(..)` before being played.

David Trattnig's avatar
David Trattnig committed
254
        Args:
David Trattnig's avatar
David Trattnig committed
255
            entry (PlaylistEntry):          The audio source to be played
256
            transition (TransitionType):    The type of transition to use e.g. fade-out.
David Trattnig's avatar
David Trattnig committed
257
            queue (Boolean):                If `True` the entry is queued if the `ChannelType` does allow so; 
258
                otherwise a new channel of the same type is activated
David Trattnig's avatar
David Trattnig committed
259
260
        
        """
261
        try:
262
263
            
            # Move channel volume all the way up
David Trattnig's avatar
David Trattnig committed
264
            self.enable_transaction()
265
266
267
268
            if transition == TransitionType.FADE:
                self.fade_in(entry)
            else:
                self.channel_volume(entry.channel, entry.volume)
David Trattnig's avatar
David Trattnig committed
269
            self.disable_transaction()
270
271
272
273
274

            # Update active channel and type
            self.active_channel[entry.type] = entry.channel     
            
            
275
        except LQConnectionError:
David Trattnig's avatar
David Trattnig committed
276
277
            # we already caught and handled this error in __send_lqc_command__, 
            # but we do not want to execute this function further and pass the exception
278
            pass
279

David Trattnig's avatar
David Trattnig committed
280

281
282
283
284
285

    def on_play(self, source):
        """
        Event Handler which is called by soundsystem implementation (i.e. Liquidsoap) 
        when some entry is actually playing.
David Trattnig's avatar
David Trattnig committed
286
287
288

        Args:
            source (String):    The URI of the media source currently being played
289
290
291
292
293
294
295
296
297
298
299
        """
        self.logger.info(SimpleUtil.pink("Source '%s' started playing" % source))

        try:
            self.player_state.store_trackservice_entry(source)
        except NoActiveEntryException:
            self.logger.warn(SimpleUtil.red("Currently there's nothing playing!"))



    def stop(self, entry, transition):
David Trattnig's avatar
David Trattnig committed
300
        """
301
        Stops the currently playing entry. 
David Trattnig's avatar
David Trattnig committed
302
303

        Args:
304
305
            entry (Entry):                  The entry to stop playing
            transition (TransitionType):    The type of transition to use e.g. fade-out.
David Trattnig's avatar
David Trattnig committed
306
        """
307

308
309
        try:
            self.enable_transaction()
310

311
312
313
314
315
316
317
318
            if not entry.channel:
                self.logger.warn("Trying to stop entry %s, but it has no channel assigned" % entry)
                return
            
            if transition == TransitionType.FADE:
                self.fade_out(entry)
            else:
                self.channel_volume(entry.channel, 0)
319

320
321
            # self.playlist_clear(entry.channel)
            self.logger.info(SimpleUtil.pink("Stopped channel '%s' for entry %s" % (entry.channel, entry)))
322

323
            self.disable_transaction()
324

325
326
327
328
        except LQConnectionError:
            # we already caught and handled this error in __send_lqc_command__, 
            # but we do not want to execute this function further and pass the exception
            pass
329

David Trattnig's avatar
David Trattnig committed
330

331

332
    def channel_swap(self, channel_type):
David Trattnig's avatar
David Trattnig committed
333
334
335
336
337
338
339
340
        """
        Returns the currently in-active channel for a given type. For example if the currently some
        file on channel FILESYSTEM_A is playing, the channel FILESYSTEM B is returned for being used
        to queue new entries.

        Args:
            channel_type (ChannelType): The channel type such es filesystem, stream or live channel
        """
341
342
343
344
345
346
347
348
349
350
351
352
        active_channel = self.active_channel[channel_type]
        channel = None
        msg = None

        if channel_type == ChannelType.FILESYSTEM:
            if active_channel == Channel.FILESYSTEM_A:
                channel = Channel.FILESYSTEM_B
                msg = "Swapped filesystem channel from A > B"
            else:
                channel = Channel.FILESYSTEM_A
                msg = "Swapped filesystem channel from B > A"
            
David Trattnig's avatar
David Trattnig committed
353
354
355
356
357
            # TODO Clear old channel
            
        elif channel_type == ChannelType.HTTP:
            if active_channel == Channel.HTTP_A:
                channel = Channel.HTTP_B
David Trattnig's avatar
David Trattnig committed
358
                msg = "Swapped HTTP Stream channel from A > B"
David Trattnig's avatar
David Trattnig committed
359

360
            else:
David Trattnig's avatar
David Trattnig committed
361
                channel = Channel.HTTP_A
David Trattnig's avatar
David Trattnig committed
362
363
364
365
366
367
368
369
370
371
372
                msg = "Swapped HTTP Stream channel from B > A"


        elif channel_type == ChannelType.HTTPS:
            if active_channel == Channel.HTTPS_A:
                channel = Channel.HTTPS_B
                msg = "Swapped HTTPS Stream channel from A > B"

            else:
                channel = Channel.HTTPS_A
                msg = "Swapped HTTPS Stream channel from B > A"
David Trattnig's avatar
David Trattnig committed
373
            
374

David Trattnig's avatar
David Trattnig committed
375

376
377
        if msg: self.logger.info(SimpleUtil.pink(msg))
        return channel
378
379
380



381
382
    # ------------------------------------------------------------------------------------------ #
    def all_inputs_but(self, input_type):
383
        try:
384
            activemixer_copy = self.get_all_channels().copy()
385
            activemixer_copy.remove(input_type)
386
387
        except ValueError as e:
            self.logger.error("Requested channel (" + input_type + ") not in channellist. Reason: " + str(e))
388
389
        except AttributeError:
            self.logger.critical("Channellist is None")
390

391
392
393
394
        return activemixer_copy

    # ------------------------------------------------------------------------------------------ #
    def get_all_channels(self):
395
        if self.channels is None or len(self.channels) == 0:
396
            self.channels = self.__send_lqc_command__(self.client, "mixer", "inputs")
397
398

        return self.channels
399

400
401
402
403
404
    # ------------------------------------------------------------------------------------------ #
    def reload_channels(self):
        self.channels = None
        return self.get_all_channels()

405

406

407
408
409
    # ------------------------------------------------------------------------------------------ #
    def channel_activate(self, channel, activate):
        channels = self.get_all_channels()
410
411
412
413

        try:
            index = channels.index(channel)
            if len(channel) < 1:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
414
415
416
417
418
419
                self.logger.critical("Cannot activate channel. There are no channels!")
            else:
                message = self.__send_lqc_command__(self.client, "mixer", "select", index, activate)
                return message
        except Exception as e:
            self.logger.critical("Ran into exception when activating channel. Reason: " + str(e))
420

421
422
423
    # ------------------------------------------------------------------------------------------ #
    def channel_volume(self, channel, volume):
        """
424
425
426
427
428
        Set volume of a channel

        Args:
            channel (Channel):      The channel
            volume  (Integer)       Volume between 0 and 100
429
        """
430

431
        channel = str(channel)
432
        try:
433
434
435
436
437
438
            if str(volume) == "100":
                channels = self.get_all_channels()
                index = channels.index(channel)
            else:
                channels = self.get_all_channels()
                index = channels.index(channel)
439
        except ValueError as e:
440
441
            msg = SimpleUtil.red("Cannot set volume of channel " + channel + " to " + str(volume) + "!. Reason: " + str(e))
            self.logger.error(msg)
David Trattnig's avatar
David Trattnig committed
442
            self.logger.info("Available channels: %s" % str(channels))
443
444
445
            return

        try:
446
            if len(channel) < 1:
447
448
                msg = SimpleUtil.red("Cannot set volume of channel " + channel + " to " + str(volume) + "! There are no channels.")
                self.logger.warning(msg)
449
            else:
450
                message = self.__send_lqc_command__(self.client, "mixer", "volume", str(index), str(int(volume)))
451

452
453
                if not self.disable_logging:
                    if message.find('volume=' + str(volume) + '%'):
454
                        self.logger.info(SimpleUtil.pink("Set volume of channel '%s' to %s" % (channel, str(volume))))
455
                    else:
456
457
                        msg = SimpleUtil.red("Setting volume of channel " + channel + " gone wrong! Liquidsoap message: " + message)
                        self.logger.warning(msg)
458

459
                return message
460
        except AttributeError as e: #(LQConnectionError, AttributeError):
461
            self.disable_transaction(force=True)
462
463
            msg = SimpleUtil.red("Ran into exception when setting volume of channel " + channel + ". Reason: " + str(e))
            self.logger.error(msg)
464

465
466

    #
467
    #   Channel Type - Stream 
468
469
    #

David Trattnig's avatar
David Trattnig committed
470
471
472
473

    def stream_load_entry(self, entry):
        """
        Loads the given stream entry and updates the entries's status codes.
David Trattnig's avatar
Docs.    
David Trattnig committed
474
475
476

        Args:
            entry (Entry):  The entry to be pre-loaded
David Trattnig's avatar
David Trattnig committed
477

David Trattnig's avatar
Docs.    
David Trattnig committed
478
479
        Returns:
            (Boolean):  `True` if successfull
David Trattnig's avatar
David Trattnig committed
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
        """
        self.stream_load(entry.channel, entry.source)
        time.sleep(1)

        retry_delay = self.config.get("input_stream_retry_delay") 
        max_retries =  self.config.get("input_stream_max_retries")
        retries = 0

        while not self.stream_is_ready(entry.channel, entry.source):
            self.logger.info("Loading Stream ...")
            if retries >= max_retries:
                raise LoadSourceException("Could not connect to stream while waiting for %s seconds!" % retries*retry_delay)
            time.sleep(retry_delay)
            retries += 1

495
        return True
David Trattnig's avatar
David Trattnig committed
496
497
498
499



    def stream_load(self, channel, url):
David Trattnig's avatar
David Trattnig committed
500
        """
David Trattnig's avatar
David Trattnig committed
501
502
        Preloads the stream URL on the given channel. Note this method is blocking
        some serious amount of time; hence it's worth being called asynchroneously.
David Trattnig's avatar
David Trattnig committed
503
504
505
506
507
508
509

        Args:
            channel (Channel): The stream channel
            uri (String):      The stream URL

        Returns:
            (Boolean):  `True` if successful
David Trattnig's avatar
David Trattnig committed
510
511
        """
        result = None
512

David Trattnig's avatar
David Trattnig committed
513
        self.enable_transaction()
David Trattnig's avatar
David Trattnig committed
514
        result = self.__send_lqc_command__(self.client, channel, "stream_stop")
David Trattnig's avatar
David Trattnig committed
515
516
        
        if result != LiquidsoapResponse.SUCCESS.value:
David Trattnig's avatar
David Trattnig committed
517
            self.logger.error("%s.stop result: %s" % (channel, result))
David Trattnig's avatar
David Trattnig committed
518
            raise LQStreamException("Error while stopping stream!")
519

David Trattnig's avatar
David Trattnig committed
520
        result = self.__send_lqc_command__(self.client, channel, "stream_set_url", url)
521

David Trattnig's avatar
David Trattnig committed
522
        if result != LiquidsoapResponse.SUCCESS.value:
David Trattnig's avatar
David Trattnig committed
523
            self.logger.error("%s.set_url result: %s" % (channel, result))
David Trattnig's avatar
David Trattnig committed
524
            raise LQStreamException("Error while setting stream URL!")
525

David Trattnig's avatar
David Trattnig committed
526
527
        # Liquidsoap ignores commands sent without a certain timeout
        time.sleep(2)
528

David Trattnig's avatar
David Trattnig committed
529
530
        result = self.__send_lqc_command__(self.client, channel, "stream_start")
        self.logger.info("%s.start result: %s" % (channel, result))
531

David Trattnig's avatar
David Trattnig committed
532
533
534
535
536
        self.disable_transaction()
        return result



David Trattnig's avatar
David Trattnig committed
537
    def stream_is_ready(self, channel, url):
David Trattnig's avatar
David Trattnig committed
538
        """
David Trattnig's avatar
David Trattnig committed
539
540
        Checks if the stream on the given channel is ready to play. Note this method is blocking
        some serious amount of time even when successfull; hence it's worth being called asynchroneously.
David Trattnig's avatar
David Trattnig committed
541
542
543
544
545
546
547

        Args:
            channel (Channel): The stream channel
            uri (String):      The stream URL

        Returns:
            (Boolean):  `True` if successful
David Trattnig's avatar
David Trattnig committed
548
549
550
551
552
        """
        result = None

        self.enable_transaction()

David Trattnig's avatar
David Trattnig committed
553
554
        result = self.__send_lqc_command__(self.client, channel, "stream_status")
        self.logger.info("%s.status result: %s" % (channel, result))
David Trattnig's avatar
David Trattnig committed
555
556
557
558
559
560
561
562
563
564
565

        if not result.startswith(LiquidsoapResponse.STREAM_STATUS_CONNECTED.value):
            return False

        lqs_url = result.split(" ")[1]
        if not url == lqs_url:
            self.logger.error("Wrong URL '%s' set for channel '%s', expected: '%s'." % (lqs_url, channel, url))
            return False

        self.disable_transaction()

David Trattnig's avatar
David Trattnig committed
566
567
568
        stream_buffer = self.config.get("input_stream_buffer")
        self.logger.info("Ready to play stream, but wait %s seconds until the buffer is filled..." % str(stream_buffer))
        time.sleep(round(float(stream_buffer)))
David Trattnig's avatar
David Trattnig committed
569
        return True
570
571


David Trattnig's avatar
David Trattnig committed
572

573

574
575
576
    #
    #   Channel Type - Playlist 
    #
David Trattnig's avatar
David Trattnig committed
577

578
579
580
581
    # FIXME
    # def playlist_activate(self, playlist, cue_in=0.0):
    #     """
    #     Activates a new Playlist.
582

583
584
585
586
587
588
589
590
591
592
    #     Args:
    #         new_entry (Playlist):       The playlist to be played
    #         cue_in (Float):             Start/cue-time of track (For some reason Liquidsoap doesn't acknowledge this yet)
        
    #     Raises:
    #         (LQConnectionError): In case connecting to LiquidSoap isn't possible
    #     """
        
    #     # Grab the actual active entry
    #     # active_entry = self.scheduler.get_active_entry()
593

594
595
    #     # Set default channel, if no previous track is available
    #     current_channel = self.active_channel[ChannelType.FILESYSTEM]
596

597
598
    #     # if active_entry:
    #     #     current_channel = active_entry.channel
599

600
601
602
603
604
605
    #     try:
    #         # FIXME clearing creates some serious timing issues
    #         # To activate this feature we'd need some more sophisticated
    #         # Liquidsoap logic, such as >= 2 filesystem channels and
    #         # possiblities to pause pre-queued channels or cleaning them
    #         # after each completed schedule.
606

607
608
609
610
611
612
    #         # self.enable_transaction()
    #         # #if active_entry:
    #         #     #self.fade_out(active_entry)
    #         # res = self.playlist_clear(current_channel)
    #         # self.logger.info("Clear Queue Response: "+res)
    #         # self.disable_transaction()
613
614


615
616
617
618
619
620
621
622
623
624
    #         self.enable_transaction()
    #         self.reload_channels()
    #         # self.fade_in(playlist.entries[0])
    #         # FIXME rework
    #         for new_entry in playlist.entries:
    #             if current_channel == new_entry.channel:
    #                 self.activate_same_channel(new_entry, cue_in)
    #             else:
    #                 self.activate_different_channel(new_entry, cue_in, current_channel)
    #                 current_channel = new_entry.channel
625

626
    #         self.disable_transaction()
627

628
629
630
631
632
633
    #         # self.logger.critical("FIXME: Implement TrackService")
    #         #self.scheduler.update_track_service(new_entry)
    #     except LQConnectionError:
    #         # we already caught and handled this error in __send_lqc_command__, 
    #         # but we do not want to execute this function further and pass the exception
    #         pass
634
635
636



637
638
639
    def playlist_push(self, channel, uri):
        """
        Adds an filesystem URI to the given `ChannelType.FILESYSTEM` channel.
640

641
        Args:
David Trattnig's avatar
David Trattnig committed
642
643
644
            channel (Channel): The channel to push the file to
            uri (String):      The URI of the file

645
        Returns:
David Trattnig's avatar
David Trattnig committed
646
            (Boolean):  `True` if successful
647
648
649
650
        """
        if channel not in ChannelType.FILESYSTEM.channels:
            raise InvalidChannelException
        self.logger.info(SimpleUtil.pink("playlist.push('%s', '%s'" % (channel, uri)))
651
652
653
654
655
656

        self.enable_transaction()
        result = self.__send_lqc_command__(self.client, channel, "playlist_push", uri)
        self.logger.info("%s.playlist_push result: %s" % (channel, result))
        self.disable_transaction()

657
        return result == "1"
658
659
660



661
662
663
    def playlist_seek(self, channel, seconds_to_seek):
        """
        Forwards the player of the given `ChannelType.FILESYSTEM` channel by (n) seconds.
664

665
        Args:
David Trattnig's avatar
David Trattnig committed
666
            channel (Channel): The channel to push the file to
667
            seconds_to_seeks (Float):   The seconds to skip
David Trattnig's avatar
David Trattnig committed
668
669
670

        Returns:
            (String):   Liquidsoap response
671
672
673
        """
        if channel not in ChannelType.FILESYSTEM.channels:
            raise InvalidChannelException
674

675
676
677
678
679
680
        self.enable_transaction()
        result = self.__send_lqc_command__(self.client, channel, "playlist_seek", str(seconds_to_seek))
        self.logger.info("%s.playlist_seek result: %s" % (channel, result))
        self.disable_transaction()

        return result
681
682


683
684
685
    def playlist_clear(self, channel):
        """
        Removes all tracks currently queued in the given `ChannelType.FILESYSTEM` channel.
David Trattnig's avatar
David Trattnig committed
686
687
688
689
690
691

        Args:
            channel (Channel): The channel to push the file to

        Returns:
            (String):   Liquidsoap response
692
693
694
695
696
        """
        if channel not in ChannelType.FILESYSTEM.channels:
            raise InvalidChannelException

        self.logger.info(SimpleUtil.pink("Clearing filesystem queue '%s'!" % channel))
697

698
699
700
701
        self.enable_transaction()
        result = self.__send_lqc_command__(self.client, channel, "playlist_clear")
        self.logger.info("%s.playlist_clear result: %s" % (channel, result))
        self.disable_transaction()
702

703
        return result
704
705
706
707
708

    #
    #   Fading 
    #

709
710
711
712
713

    def fade_in(self, entry):
        """
        Performs a fade-in for the given `entry` to the `entry.volume` loudness
        at channel `entry.channel`.
David Trattnig's avatar
David Trattnig committed
714
715
716
717
718
719

        Args:
            entry (Entry):  The entry to fade
        
        Returns:
            (Boolean):  `True` if successful
720
        """
721
722
723
724
725
        try:
            fade_in_time = float(self.config.get("fade_in_time"))

            if fade_in_time > 0:
                self.fade_in_active = True
726
                target_volume = entry.volume
727
728
729

                step = fade_in_time / target_volume

730
731
732
                msg = "Starting to fading-in '%s'. Step is %ss and target volume is %s." % \
                    (entry.channel, str(step), str(target_volume))
                self.logger.info(SimpleUtil.pink(msg))
733

734
                # Enable logging, which might have been disabled in a previous fade-out
735
736
737
738
                self.disable_logging = True
                self.client.disable_logging = True

                for i in range(target_volume):
739
                    self.channel_volume(entry.channel.value, i + 1)
740
741
                    time.sleep(step)

742
743
                msg = "Finished with fading-in '%s'." % entry.channel
                self.logger.info(SimpleUtil.pink(msg))
744
745
746
747
748

                self.fade_in_active = False
                if not self.fade_out_active:
                    self.disable_logging = False
                    self.client.disable_logging = False
749

750
751
752
753
754
        except LQConnectionError as e:
            self.logger.critical(str(e))

        return True

755
756
757
758
759


    def fade_out(self, entry):
        """
        Performs a fade-out for the given `entry` at channel `entry.channel`.
David Trattnig's avatar
David Trattnig committed
760
761
762
763
764
765
        
        Args:
            entry (Entry):  The entry to fade
        
        Returns:
            (Boolean):  `True` if successful
766
        """
767
768
769
770
        try:
            fade_out_time = float(self.config.get("fade_out_time"))

            if fade_out_time > 0:
771
                step = abs(fade_out_time) / entry.volume
772

773
774
                msg = "Starting to fading-out '%s'. Step is %ss." % (entry.channel, str(step))
                self.logger.info(SimpleUtil.pink(msg))
775

776
                # Disable logging... it is going to be enabled again after fadein and -out is finished
777
778
779
                self.disable_logging = True
                self.client.disable_logging = True

780
781
                for i in range(entry.volume):
                    self.channel_volume(entry.channel.value, entry.volume-i-1)
782
783
                    time.sleep(step)

784
785
                msg = "Finished with fading-out '%s'" % entry.channel
                self.logger.info(SimpleUtil.pink(msg))
786

787
                # Enable logging again
788
789
790
791
                self.fade_out_active = False
                if not self.fade_in_active:
                    self.disable_logging = False
                    self.client.disable_logging = False
792

793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
        except LQConnectionError as e:
            self.logger.critical(str(e))

        return True



    #
    #   Recording
    #


    # ------------------------------------------------------------------------------------------ #
    def recorder_stop(self):
        self.enable_transaction()

        for i in range(5):
            if self.config.get("rec_" + str(i)) == "y":
                self.__send_lqc_command__(self.client, "recorder_" + str(i), "stop")

        self.disable_transaction()

    # ------------------------------------------------------------------------------------------ #
    def recorder_start(self, num=-1):
        if not self.is_liquidsoap_running:
            if num==-1:
                msg = "Want to start recorder, but LiquidSoap is not running"
            else:
                msg = "Want to start recorder " + str(num) + ", but LiquidSoap is not running"
            self.logger.warning(msg)
            return False

        self.enable_transaction()

        if num == -1:
            self.recorder_start_all()
        else:
            self.recorder_start_one(num)

        self.disable_transaction()

    # ------------------------------------------------------------------------------------------ #
    def recorder_start_all(self):
        if not self.is_liquidsoap_running:
            self.logger.warning("Want to start all recorder, but LiquidSoap is not running")
            return False

        self.enable_transaction()
        for i in range(5):
            self.recorder_start_one(i)
        self.disable_transaction()

    # ------------------------------------------------------------------------------------------ #
    def recorder_start_one(self, num):
        if not self.is_liquidsoap_running:
            return False

        if self.config.get("rec_" + str(num)) == "y":
            returnvalue = self.__send_lqc_command__(self.client, "recorder", str(num), "status")

            if returnvalue == "off":
                self.__send_lqc_command__(self.client, "recorder", str(num), "start")

    # ------------------------------------------------------------------------------------------ #
    def get_recorder_status(self):
        self.enable_transaction(self.client)
        recorder_state = self.__send_lqc_command__(self.client, "record", "status")
        self.disable_transaction(self.client)

        return recorder_state



    #
    #   Basic Methods
    #


    def init_player(self):
872
        """
873
874
875
876
        Initializes the LiquidSoap Player after startup of the engine.

        Returns:
            (String):   Message that the player is started.
877
        """
878
        t = StartupThread(self)
879
880
        t.start()

881
        return "Engine Core startup done!"
882

883
884

    # ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
885
    def __send_lqc_command__(self, lqs_instance, namespace, command, *args):
886
887
888
889
890
891
892
893
894
895
896
897
898
899
        """
        Ein Kommando an Liquidsoap senden
        @type  lqs_instance: object
        @param lqs_instance: Instance of LiquidSoap Client
        @type  namespace:    string
        @param namespace:    Namespace of function
        @type  command:      string
        @param command:      Function name
        @type args:          list
        @param args:         List of parameters
        @rtype:              string
        @return:             Response from LiquidSoap
        """
        try:
900
901
            if not self.disable_logging:
                if namespace == "recorder":
902
                    self.logger.debug("LiquidSoapCommunicator is calling " + str(namespace) + "_" + str(command) + "." + str(args))
903
                else:
904
                    if command == "":
905
                        self.logger.debug("LiquidSoapCommunicator is calling " + str(namespace) + str(args))
906
                    else:
907
                        self.logger.debug("LiquidSoapCommunicator is calling " + str(namespace) + "." + str(command) + str(args))
908

909
            # call wanted function ...
910
911

            # FIXME REFACTOR all calls in a common way
David Trattnig's avatar
David Trattnig committed
912
            if command in  ["playlist_push", "playlist_seek", "playlist_clear", "stream_set_url", "stream_start", "stream_stop", "stream_status"]:
913
914
915
916
917
918
                func = getattr(lqs_instance, command)
                result = func(str(namespace), *args)
            else:
                func = getattr(lqs_instance, namespace)
                result = func(command, *args)            

919

920
921
            if not self.disable_logging:
                self.logger.debug("LiquidSoapCommunicator got response " + str(result))
922

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
923
            self.connection_attempts = 0
924

925
926
            return result

927
        except LQConnectionError as e:
928
            self.logger.error("Connection Error when sending " + str(namespace) + "." + str(command) + str(args))
929
            if self.try_to_reconnect():
930
                time.sleep(0.2)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
931
932
                self.connection_attempts += 1
                if self.connection_attempts < 5:
933
934
935
936
937
938
939
940
941
                    # reconnect
                    self.__open_conn(self.client)
                    self.logger.info("Trying to resend " + str(namespace) + "." + str(command) + str(args))
                    # grab return value
                    retval = self.__send_lqc_command__(lqs_instance, namespace, command, *args)
                    # disconnect
                    self.__close_conn(self.client)
                    # return the val
                    return retval
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
942
                else:
943
944
945
946
947
948
                    if command == "":
                        msg = "Rethrowing Exception while trying to send " + str(namespace) + str(args)
                    else:
                        msg = "Rethrowing Exception while trying to send " + str(namespace) + "." + str(command) + str(args)

                    self.logger.info(msg)
949
                    self.disable_transaction(socket=self.client, force=True)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
950
                    raise e
951
            else:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
952
                # also store when was last admin mail sent with which content...
David Trattnig's avatar
David Trattnig committed
953
                # FIXME implement admin mail sending
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
954
                self.logger.critical("SEND ADMIN MAIL AT THIS POINT")
955
956
                raise e

David Trattnig's avatar
David Trattnig committed
957
958
959
960
961

    def is_active(self):
        """
        Checks if Liquidsoap is running
        """
962
963
964
965
966
967
968
969
970
        try:
            self.uptime()
            self.is_liquidsoap_running = True
        except LQConnectionError as e:
            self.logger.info("Liquidsoap is not running so far")
            self.is_liquidsoap_running = False
        except Exception as e:
            self.logger.error("Cannot check if Liquidsoap is running. Reason: " + str(e))
            self.is_liquidsoap_running = False
David Trattnig's avatar
David Trattnig committed
971
972
        
        return self.is_liquidsoap_running
973

David Trattnig's avatar
David Trattnig committed
974
975
976
977
978
979

    def engine_state(self):
        """
        Retrieves the state of all inputs and outputs.
        """
        state = self.__send_lqc_command__(self.client, "engine", "state")
980
981
        return state

David Trattnig's avatar
David Trattnig committed
982

983
    def liquidsoap_help(self):
David Trattnig's avatar
David Trattnig committed
984
985
986
        """
        Retrieves the Liquidsoap help.
        """
987
988
989
990
991
992
993
        data = self.__send_lqc_command__(self.client, "help", "")
        if not data:
            self.logger.warning("Could not get Liquidsoap's help")
        else:
            self.logger.debug("Got Liquidsoap's help")
        return data

David Trattnig's avatar
David Trattnig committed
994

995
996
    def version(self):
        """
David Trattnig's avatar
David Trattnig committed
997
        Get the version of Liquidsoap.
998
999
1000
        """
        data = self.__send_lqc_command__(self.client, "version", "")
        self.logger.debug("Got Liquidsoap's version")