LiquidSoapCommunicator.py 31.6 KB
Newer Older
1
2
3
4
5
import os
import codecs
import urllib
import tempfile
import simplejson
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
6
import traceback
7
8

from libraries.base.parsexml import parsexml
9
from modules.communication.liquidsoap.LiquidSoapPlayerClient import LiquidSoapPlayerClient
10
11
12
from modules.communication.liquidsoap.LiquidSoapRecorderClient import LiquidSoapRecorderClient
from modules.communication.liquidsoap.LiquidSoapInitThread import LiquidSoapInitThread

13
14

class LiquidSoapCommunicator:
15
16
    lqc = None
    lqcr = None
17
    debug = None
18
    transaction = False
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
19
    controller = None
20
21

    # ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
22
    def __init__(self, controller, config, debug=True):
23
24
25
26
27
28
29
30

        """
                Constructor
                @type    lqs_socket: string
                @param   lqs_socket: Liquidsoap Player Socket
                @type    lqs_recsocket: string
                @param   lqs_recsocket: Liquidsoap Recorder Socket
                """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
31
        self.controller = controller
32
33
34
35
        # Der Liquidsoap Client
        #        print("lqs_socket: " + lqs_socket)
        self.lqc = LiquidSoapPlayerClient(config.get('socketdir') + '/simplestmixer.sock', debug)
        self.lqcr = LiquidSoapRecorderClient(config.get('socketdir') + '/record.sock', debug)
36
37

        # Der Liquidsoap Client
38
39
        #        lqs_socket = "/home/gg/PycharmProjects/aura/modules/liquidsoap/simplestmixer.sock"
        #        self.lqs = LiquidSoapPlayerClient(lqs_socket)
40
41
        self.debug = debug

42
43
    # ------------------------------------------------------------------------------------------ #
    def switch_mixer_number(self, mixernumber, activate=True):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
44
        return self.__send_lqc_command__(self.lqc, "mixer", "select", mixernumber, activate)
45

46
47
48
    # ------------------------------------------------------------------------------------------ #
    def set_volume(self, mixernumber, volume):
        print("LiquidSoapCommunicator.set_volume")
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
49
        return self.__send_lqc_command__(self.lqc, "mixer", "volume", mixernumber, volume)
50
51
52

    # ------------------------------------------------------------------------------------------ #
    def get_active_mixer(self):
53
54
        activeinputs = []

55
        # enable more control over the connection
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
56
57
        self.enable_transaction()
        self.open_conn(self.lqc)
58

59
        inputs = self.__get_mixer_inputs__()
60
61
62

        cnt = 0
        for input in inputs:
63
            status = self.__get_mixer_status__(cnt)
64
65
66
67
68
69

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

            cnt = cnt + 1

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
70
71
        self.close_conn(self.lqc)
        self.disable_transaction()
72
73
74

        return activeinputs

75
76
    # ------------------------------------------------------------------------------------------ #
    def get_mixer_status(self):
77
78
        inputstate = {}

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
79
80
        self.enable_transaction()
        self.open_conn(self.lqc)
81

82
        inputs = self.__get_mixer_inputs__()
83
84
85

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

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
89
90
        self.disable_transaction()
        self.close_conn(self.lqc)
91
92
93

        return inputstate

94
95
    # ------------------------------------------------------------------------------------------ #
    def __get_mixer_inputs__(self):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
96
        return self.__send_lqc_command__(self.lqc, "mixer", "inputs")
97
98
99

    # ------------------------------------------------------------------------------------------ #
    def __get_mixer_status__(self, mixernumber):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
100
        return self.__send_lqc_command__(self.lqc, "mixer", "status", mixernumber)
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    # ------------------------------------------------------------------------------------------ #
    def liquid_startup(self):
        LiquidSoapInitThread(self, self.lqc).start()
        return ""
        #self.openConn(self.lqc)
        #reply = self.lqc.init()
        #self.closeConn(self.lqc)
        #return reply

    # ------------------------------------------------------------------------------------------ #
    def get_client(self):
        return self.lqc

    # ------------------------------------------------------------------------------------------ #
    def all_data(self):
        """
        Gibt Metadaten aller Kanäle als JSON-String an den Client zurück
        @rtype:   string/None
        @return:  Die Antwort des Liquidsoap-Servers

        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
123
        channels = self.__send_lqc_command__(self.lqc, 'listChannels')
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

        if not isinstance(channels, list):
            self.warning('01')
            self.notifyClient()
            return

        data = {}
        pdata = {}

        try:
            self.is_intern = True
            playlist_data = simplejson.loads(self.playlist_data(True))
            self.is_intern = False
        except:
            self.warning('01')
            self.notifyClient()
            return

        # Status des Playlistkanals abfragen
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
143
        status = self.__send_lqc_command__(self.lqc, 'status', 'mixer', '0')
144
145
146
147
148
149
150
151
152
153
154
155
156
157

        states = status.split(' ')
        state_data = {}

        # Die Stati in python dicts einlesen
        for state in states:
            item = state.split('=')
            try:
                state_data[item[0]] = item[1]
            except:
                self.warning('01')
                self.notifyClient()
                return

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
158
        remaining = self.__send_lqc_command__(self.lqc, 'playlist_remaining')
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        state_data['remaining'] = remaining
        # Die Metadaten der Playlist
        pdata['state'] = state_data
        pdata['tracks'] = playlist_data
        data['playlist'] = pdata

        # Servermeldungen abschalten
        self.is_intern = True
        # die channel queues einlesen

        for channel in channels:
            data[channel] = self.channel_queue(channel, True)
        # Servermeldungen einschalten
        self.is_intern = False
        self.success('00', data)
        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def ping(self):
        """
        dem Client antworten
        """
        return self.message('OK')

    # ------------------------------------------------------------------------------------------ #
    def channel_insert(self, channel, uri, pos):
        """
        Track in einen Channel einfuegen
        @type     channel: string
        @param    channel: Kanal
        @type     uri:     string
        @param    uri:     Uri - z.B. file:///my/audio/mp3
        @type     pos:     int
        @param    pos:     Die Position an der eingefügt werden soll
        @rtype:   string/None
        @return:  Die Antwort des Liquidsoap-Servers
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
196
        message = self.__send_lqc_command__(self.lqc, 'insert', uri, pos, channel)
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        message = message.strip()

        try:
            if int(message) > -1:
                self.success()
                return self.message(message)
        except:
            self.warning('01')
            self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_move(self, channel, fromPos, toPos):
        """
        Channel-Eintrag von Position fromPos nach Position toPos verschieben
        @type     channel: string
        @param    channel: Kanal
        @type     fromPos: int
        @param    fromPos: die Position des Eintrags, der verschoben wird
        @type     toPos:   int
        @param    toPos:   Zielposition
        @rtype:   string
        @return:  Die Antwort des Liquidsoap-Servers
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
220
        message = self.__send_lqc_command__(self.lqc, 'get_queue', channel, 'secondary_queue')
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241

        rids = message.strip().split(' ')

        try:
            rid = rids[int(fromPos) - 1]
        except:
            self.warning('01')
            self.notifyClient()
            return
        try:
            target = rids[int(toPos) - 1]
        except:
            self.warning('01')
            self.notifyClient()
            return

        if rids[int(fromPos) - 1] == rids[int(toPos) - 1]:
            self.warning('02')
            self.notifyClient()
            return

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
242
        message = self.__send_lqc_command__(self.lqc, 'move', rid, str(int(toPos) - 1), channel)
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
        message = message.strip()

        if message.strip().find('OK') > -1:
            self.success()
            self.notifyClient()
            return
        else:
            self.warning('03')
            self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_off(self, channel):
        """
        Channel deaktivieren
        @type     channel: string
        @param    channel: Kanal
        @rtype:   string
        @return:  Die Antwort des Liquidsoap-Servers
        """
        # internal channel name for playlist is 'common'
        if channel == 'playlist':
            channel = 'common'

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
266
        channels = self.__send_lqc_command__(self.lqc, 'listChannels', False)
267
268

        index = channels.index(channel)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
269
        message = self.__send_lqc_command__(self.lqc, 'deactivate', str(index))
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
        if message.find('selected=false'):
            self.success()
        else:
            self.warning('01')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_on(self, channel):
        """
        Channel aktivieren
        @type     channel: string
        @param    channel: Kanal
        @rtype:   string
        @return:  Die Antwort des Liquidsoap-Servers
        """

        # Find channels
        if channel == 'playlist':
            channel = 'common'

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
291
        channels = self.__send_lqc_command__(self.lqc, 'listChannels', False)
292
293
294

        index = channels.index(channel)
        # a activate channel
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
295
        message = self.__send_lqc_command__(self.lqc, 'activate', str(index))
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318

        if message.find('selected=true'):
            self.success()
        else:
            self.warning('01')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_queue(self, channel, raw=False):
        """
        Channel Queue abrufen
        @type     channel: string
        @param    channel: Kanal
        @type     raw:     boolean
        @param    raw:     Wenn true, Rückgabe als Python dict Object, andernfalls als JSON-String
        @rtype:   string/dict
        @return:  Der Channel Queue
        """
        data = {}

        # queue will return request id's (rids)

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
319
        message = self.__send_lqc_command__(self.lqc, 'get_queue', channel)
320
321
322
323
324
325

        rids = message.strip().split(' ')
        data['tracks'] = []
        for rid in rids:
            if rid != '':
                # get each rids metadata
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
326
                metadata = self.__send_lqc_command__(self.lqc, 'getMetadata', rid)
327
328
329
330
331
332
333
334
335
336
                track = self._metadata_format(metadata)
                if not 'title' in track:
                    if 'location' in track:
                        track['title'] = os.path.basename(track['location'])
                    elif 'filename' in track:
                        track['title'] = os.path.basename(track['filename'])
                    else:
                        track['title'] = 'unknown'

                data['tracks'].extend([track])
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
337
        channels = self.__send_lqc_command__(self.lqc, 'listChannels')
338
339
340
341
342
343
344

        """
        now get channels state 
        self.lqc.status: ready=false volume=100% single=false selected=false remaining=0.00
        """
        try:
            index = channels.index(channel)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
345
            status = self.__send_lqc_command__(self.lqc, 'status', 'mixer', str(index + 1))
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
            states = status.split(' ')
            state_data = {}
            for state in states:
                item = state.split('=')
                if len(item) > 1:
                    state_data[item[0]] = item[1]
        except:
            state_data = {}
            self.error('01')
            self.notifyClient()
            return

        data['state'] = state_data

        if raw:
            # return the list internal
            data['state'] = state_data
            return data
        else:
            self.success('00', data)
            self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_remove(self, channel, pos):
        """
        Channel-Eintrag löschen
        @type     channel: string
        @param    channel: Kanal
        @type     pos:     int
        @param    pos:     Position des Eintrags
        """
        # Es kann nur vom Secondary Queue gelöscht werden
        # Falls der Track im Primary Queue gelöscht werden soll, ist ein skip nötg

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
380
        message = self.__send_lqc_command__(self.lqc, 'get_queue', channel, 'secondary_queue')
381
382
383
384
385
386
387
        rids = message.strip().split(' ')
        try:
            rid = rids[int(pos) - 1]
        except:
            self.warning('02')
            self.notifyClient()
            return
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
388
        message = self.__send_lqc_command__(self.lqc, 'remove', rid, channel)
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
        if message.find('OK') > -1:
            self.success()
        else:
            self.warning('01')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_seek(self, channel, duration):
        """
        Im aktuell spielenden Track auf dem Kanal <channel> <duration> Sekunden "vorspulen"
        @type     channel:  string
        @param    channel:  Kanal
        @type     duration: int
        @param    duration: Dauer in Sekunden
        """
        # Liquidsoap Kommando
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
406
        data = self.__send_lqc_command__(self.lqc, 'seek', duration, channel)
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

        # Resultate prüfen
        if self._check_result(data):
            self.success('00', self.lq_error['value'])
        else:
            self.warning('01')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_skip(self, channel):
        """
        Kanal skippen
        @type     channel:  string
        @param    channel:  Kanal
        """

        # Liquidsoap Kommando
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
425
        channels = self.__send_lqc_command__(self.lqc, 'listChannels')
426
427
428
429
430
431
432

        foundChannel = ''
        if not isinstance(channels, list):
            self.error('02')
        else:
            for index, item in enumerate(channels):
                if item == channel:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
433
                    foundChannel = self.__send_lqc_command__(self.lqc, 'skip', 'mixer', str(index + 1))
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
                    break

            if foundChannel.strip().find('OK') > -1:
                self.success()
            elif len(channels) < 1:
                self.warning('01')
            else:
                self.error('03')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def channel_volume(self, channel, volume):
        """
        Lautstärke auf Kanal <channel> setzen
        @type     channel:  string
        @param    channel:  Kanal
        @type     volume:   int
        @param    volume:  Lautstärke von 1-100
        """

        if channel == 'playlist':
            channel = 'common'
        # Liquidsoap Kommando
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
458
        #channels = self.__sendLqcCommand__(self.lqc, 'listChannels', False)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
459
        channels = self.__send_lqc_command__(self.lqc, "mixer", "inputs")
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
460
        print(channels)
461
462
463
464
465
466
467
468
        try:
            index = channels.index(channel)
            if len(channel) < 1:
                self.warning('02')
        except:
            self.error('03')

        else:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
469
            message = self.__send_lqc_command__(self.lqc, 'mixer', 'volume', str(index), str(int(volume)))
470
471

            if message.find('volume=' + str(volume) + '%'):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
472
                self.controller.success('01', str(volume))
473
            else:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
474
                self.controller.warning('01')
475
476
477
478
479
480
481
482
483

    # ------------------------------------------------------------------------------------------ #
    def current_data(self):
        """
        Metadaten des gespielten Tracks im JSON-Format
        Beispiel: {"title": "Deserted Cities of the Heart", "filename": "/home/michel/Nas-audio/cream/the_very_best_of/17_Deserted_Cities_of_the_Heart.mp3", "source": "ch2", "on_air": "2014/07/23 23:46:37",  "rid": "2"}
        """

        # Liquidsoap Kommando
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
484
        message = self.__send_lqc_command__(self.lqc, 'currentTrack')
485
486
487

        rid = message.strip()

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
488
        metadata = self.__send_lqc_command__(self.lqc, 'getMetadata', rid)
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505

        data = self._metadata_format(metadata)

        if data:
            self.success('00', simplejson.dumps(data))
        elif rid == '':
            self.warning('01')
        else:
            self.warning('02', rid)

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def get_channel_state(self, channel):

        if channel == 'playlist':
            channel = 'common'
506

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
507
        channels = self.__send_lqc_command__(self.lqc, 'listChannels', False)
508
509
510
511
512

        index = channels.index(channel)
        state_data = {}
        try:
            index = channels.index(channel)
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
513
            status = self.__send_lqc_command__(self.lqc, 'status', 'mixer', str(index + 1))
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
            states = status.split(' ')
            for state in states:
                item = state.split('=')
                if len(item) > 1:
                    state_data[item[0]] = item[1]
        except:
            state_data = {}
            self.error('01')
            self.notifyClient()
            return
        self.success('00', simplejson.dumps(state_data))
        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def help(self):
        """
        Gibt die Hilfe aus
        """

        errNum = '11'
        try:
            file = open(os.path.dirname(os.path.abspath(__file__)) + '/doc/comba.hlp', 'r')
            doc = file.read()
            return self.message(doc)
        except:
            self.warning('01')
            self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def liquidsoap_help(self):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
544
        data = self.__send_lqc_command__(self.lqc, 'help')
545
546
547
548
549
550
551
552
553
554
555
556
557
        if not data:
            self.warning('01')
        else:
            self.success('00', data)
        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def list_channels(self):
        """
        Channels auflisten (Simple JSON)
        """
        # Liquidsoap Kommando

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
558
        channels = self.__send_lqc_command__(self.lqc, 'listChannels')
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575

        if not isinstance(channels, list):
            self.error('02')
        elif len(channels) < 1:
            self.warning('01')
        else:
            self.success('00', channels)

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_data(self, raw=False):
        """
        Aktuelle Playlist Daten im JSON-Format
        """

        # Liquidsoap Kommando
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
576
        data = self.__send_lqc_command__(self.lqc, 'playlistData')
577
578
579
580
581
582
583
584
585
586
587
        if not raw:
            self.success('00', simplejson.loads(data))
            self.notifyClient()
        else:
            return data

    # ------------------------------------------------------------------------------------------ #
    def playlist_flush(self):
        """
        Aktuelle Playlist leeren
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
588
        data = self.__send_lqc_command__(self.lqc, 'flush')
589
590
591
592
593
594
595
596
        self.success('00')
        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_insert(self, uri, pos):
        """
        Track in die Playlist einfuegen
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
597
        data = self.__send_lqc_command__(self.lqc, 'insert', uri, pos)
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
        if not self._check_result(data):
            self.warning('01')
        else:
            self.success('00')
        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_load(self, uri):
        """
        Playlist laden
        @type   uri:   string
        @param  uri:   Uri der Playlist
        """
        try:
            xml = urllib.urlopen(uri).read().decode('utf8')

        except:
            try:
                xml = open(uri).read().decode('utf8')
            except:
                self.error('01', self.lq_error['message'])
                self.notifyClient()
                return

        (num, filename) = tempfile.mkstemp(suffix=".xspf")

        with codecs.open(filename, "w", encoding='utf8') as text_file:
            text_file.write(xml)

        playlist = parsexml(xml)

        if not isinstance(playlist, dict):
            self.error('02')
            self.notifyClient()
        else:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
633
634
            self.__send_lqc_command__(self.lqc, 'flush')
            data = self.__send_lqc_command__(self.lqc, 'loadPlaylist', filename)
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656

            if not self._check_result(data):
                self.error('01', self.lq_error['message'])

            else:
                os.remove(filename)
                self._updateEventQueue(playlist)
                event = {'job': 'loadplaylist', 'uri': uri}
                self.messenger.fire_event('loadplaylist', event, 'player')
                self.success('00')

            self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_move(self, fromPos, toPos):
        """
        Playlist-Eintrag von Position fromPos nach Position toPos verschieben
        @type     fromPos: int
        @param    fromPos: die Position des Eintrags, der verschoben wird
        @type     toPos:   int
        @param    toPos:   Zielposition
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
657
        data = self.__send_lqc_command__(self.lqc, 'move', str(int(fromPos) + 1), str(int(toPos) + 1))
658
659
660
661
662
663
664
665
666
667
668
669
670

        if not self._check_result(data):
            self.warning('01')
        else:
            self.success('00')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_pause(self):
        """
        Playlist pausieren
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
671
        data = self.__send_lqc_command__(self.lqc, 'pause')
672
673
674
675
676
677
678
679
680
681
682
683
684
685

        if not self._check_result(data):
            self.info('01')
        else:
            self.success('00')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_stop(self):
        """
        Playlist stoppen - der Kanal wird deaktiviert
        """
        # Kanal 0 (Playlist) deaktivieren
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
686
        self.__send_lqc_command__(self.lqc, 'deactivate', '0')
687

Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
688
        data = self.__send_lqc_command__(self.lqc, 'pause')
689
690
691
692
693
694
695

        if not self._check_result(data):
            self.info('01')
        else:
            self.success('00')

        self.notifyClient()
696
697

    # ------------------------------------------------------------------------------------------ #
698
699
700
701
702
703
704
    def playlist_play(self, when='now'):
        """
        Playlist starten
        @type   when:   string
        @param  when:   Wenn "now" werden alle anderen Kanäle deaktiviert und geskipped
        """
        # Playlist Kanal aktivieren
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
705
        self.__send_lqc_command__(self.lqc, 'activate', '0')
706
707
708
709

        if when == 'now':
            # immediately skip all playing channels
            # and activate the playlist channel
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
710
            channels = self.__send_lqc_command__(self.lqc, 'listChannels')
711
712
713
714
715
716
717
            if not isinstance(channels, list):
                self.error('03')
            elif len(channels) < 1:
                self.warning('02')
            else:
                # xrange
                for i in range(len(channels)):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
718
                    status = self.__send_lqc_command__(self.lqc, 'status', 'mixer', str(i + 1))
719
                    if "selected=true" in status:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
720
721
722
                        status = self.__send_lqc_command__(self.lqc, 'deactivate', str(i + 1))
                        status = self.__send_lqc_command__(self.lqc, 'skip', 'mixer', str(i + 1))
                        self.__send_lqc_command__(self.lqc, 'activate', '0')
723
724

        # send the play command
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
725
        data = self.__send_lqc_command__(self.lqc, 'play')
726
727
728
729
730
731
732
733
734
735
736
737
738
739
        if not self._check_result(data):
            self.info('01')
        else:
            self.success('00')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_push(self, uri):
        """
        Eine Uri in die Playlist einfügen
        @type   uri:   str
        @param  uri:   Die Uri
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
740
        data = self.__send_lqc_command__(self.lqc, 'push', uri)
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755

        if not self._check_result(data):
            self.info('01')
        else:
            self.success('00')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_remove(self, pos):
        """
        Playlist-Eintrag löschen
        @type     pos:     int
        @param    pos:     Position des Eintrags
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
756
        data = self.__send_lqc_command__(self.lqc, 'remove', pos)
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771

        if not self._check_result(data):
            self.info('01')
        else:
            self.success('00')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_seek(self, duration):
        """
        Im aktuell spielenden Track auf dem der Playlist "vorspulen"
        @type     duration: int
        @param    duration: Dauer in Sekunden
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
772
        data = self.__send_lqc_command__(self.lqc, 'seek', duration)
773
774
775
776
777
778
779
780
781
782
783
784
785
786

        # Resultate prüfen
        if self._check_result(data):
            self.success('00', self.lq_error['value'])
        else:
            self.warning('01')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def playlist_skip(self):
        """
        Playlist skippen
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
787
        data = self.__send_lqc_command__(self.lqc, 'skip')
788
789
790
791
792
793
794
795
796
797

        self.success('00')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def version(self):
        """
        get version
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
798
        data = self.__send_lqc_command__(self.lqc, 'version')
799
800
        self.success('00', data)
        self.notifyClient()
801
802

    # ------------------------------------------------------------------------------------------ #
803
804
805
806
    def uptime(self):
        """
        get uptime
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
807
        data = self.__send_lqc_command__(self.lqc, 'uptime')
808
809
810
811
812
813
814
815
        self.success('00', data)
        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def on_air(self):
        """
        get whats playing now
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
816
        data = self.__send_lqc_command__(self.lqc, 'on_air')
817
818
819
820
821
822
823
824
825
826
        self.success('00', data)
        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def recorder_start(self):
        """
        Recorder starten
        @rtype:   string
        @return:  Die Antwort des Liquidsoap-Servers
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
827
        message = self.__send_lqc_command__(self.lqcr, 'start_record')
828
829
830
831
832
833
834
835
836
837
838
839
        if message.strip() == 'OK':
            self.success('00')
        else:
            self.warning('01')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def recorder_stop(self):
        """
        Recorder stoppen
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
840
        message = self.__send_lqc_command__(self.lqcr, 'stop_record')
841
842
843
844
845
846
847
848
849
850
851
852
853
854

        if message.strip() == 'OK':
            self.success('00')
        else:
            self.warning('01')

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
    def recorder_data(self):
        """
        Status-Daten des Recorders
        Rückgabe-Beispiel: /var/audio/rec/2014-05-13/2014-05-13-22-00.wav,30 - Aufnahme von 30% der angegebenen Audiodatei
        """
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
855
        message = self.__send_lqc_command__(self.lqcr, 'recorder_data')
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
        l = message.split(',')
        data = {}

        if not isinstance(l, list):
            data = {'file': '', 'recorded': ''}
            self.warning('01')
        else:
            data['file'] = l[0]
            if len(l) > 1:
                data['recorded'] = l[1]
            else:
                data['recorded'] = ''
            self.success('00', data)

        self.notifyClient()

    # ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
873
    def __send_lqc_command__(self, lqs_instance, namespace, command, *args):
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
        """
        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:
            # connect
889
            if not self.transaction:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
890
                self.open_conn(lqs_instance)
891

892
            if self.debug:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
893
                print("LiquidSoapCommunicator trying to call " + str(namespace) + "." + str(command) + " " + str(args))
894

895
896
897
898
899
900
            # call wanted function ...
            func = getattr(lqs_instance, namespace)
            # ... and fetch the result
            result = func(command, *args)

            # say byebye
901
            if not self.transaction:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
902
                self.close_conn(lqs_instance)
903
904
905

        except Exception as e:
            # Verbindung gescheitert - Fehler an Client
906
907
908
909
910
911
            #            if command.find('record') > -1:
            #                raise e
            # self.fatal('02')
            #            else:
            #                raise e
            # self.fatal('01')
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
912
            traceback.print_exc()
913
914
            raise e

915
            # Instanz/Thread zerstören - aufrufende Funktion wird nicht weiter abgearbeitet
916
            #del self
917
918
        else:
            if self.debug:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
919
                if len(args) == 0:
920
921
                    print("response to lqc command [" + namespace + "." + command + "] is " + str(result))
                else:
922
923
                    print("response to lqc command [" + namespace + "." + command + " " + str(args) + "] is " + str(
                        result))
924
925
            return result

926
    # ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
927
    def enable_transaction(self, connect=False):
928
        self.transaction = True
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
929
        if connect:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
930
            self.open_conn()
931

932
    # ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
933
    def disable_transaction(self, disconnect=False):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
934
        if disconnect:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
935
            self.close_conn()
936
937
        self.transaction = False

938
    # ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
939
940
    def open_conn(self, socket=None):
        if socket is None:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
941
            socket = self.lqc
942
943
        if self.debug:
            print("LiquidSoapCommunicator opened conn")
944
945
        socket.connect()

946
    # ------------------------------------------------------------------------------------------ #
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
947
    def close_conn(self, socket=None):
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
948
949
        if socket == None:
            socket = self.lqc
950
951
        if self.debug:
            print("LiquidSoapCommunicator closed conn")
952
        socket.byebye()