client.py 8.7 KB
Newer Older
1
2
3
4
5
6
7
8
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import time
import socket
import urllib.parse
import configparser
9
import logging
10
11

from io import StringIO
12
from multiprocessing import Lock
13

14
from libraries.exceptions.auraexceptions import LQConnectionError
15
16


17
18
""" LiquidSoapClient Class 
    Repräsentiert alle Kommandos, die Soundserver und Recorder kennen
19
20
21
"""


22
class LiquidSoapClient:
23
24
    mutex = None
    logger = None
25
    debug = False
26
    socket_path = ""
27

28
    def __init__(self, config, socket_filename):
29
30
        """
        Constructor
31
32
        @type    socket_path: string
        @param   socket_path: Der Pfad zum Socket des Liquidsoap-Scripts
33
        """
34
        self.logger = logging.getLogger("AuraEngine")
35
36
        self.socket_path = config.get('socketdir') + '/' + socket_filename

37
        self.logger.debug("LiquidSoapClient using socketpath: " + self.socket_path)
38

39
        # init
40
        self.mutex = Lock()
41
42
43
        self.connected = False
        self.can_connect = True
        self.message = ''
44
45
        self.socket = None
        self.metareader = configparser.ConfigParser()
46
47
48
49
50
51
52

    # ------------------------------------------------------------------------------------------ #
    def connect(self):
        """
        Verbindung herstellen
        """
        try:
53
54
55
            self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.connect(self.socket_path)
56
        except socket.error as e:
57
            self.can_connect = False
58
            self.connected = False
59
            raise e
60
61
62
63
64
65
        else:
            self.can_connect = True
            self.connected = True
            return True

    # ------------------------------------------------------------------------------------------ #
66
    def is_connected(self):
67
68
69
70
71
72
73
74
75
76
        return self.connected

    # ------------------------------------------------------------------------------------------ #
    def write(self, data):
        """
        Auf den Socket schreiben
        @type    data: string
        @param   data: Der String der gesendet wird
        """
        if self.connected:
77
            self.socket.sendall(data.decode("UTF-8"))
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

    # ------------------------------------------------------------------------------------------ #
    def read_all(self, timeout=2):
        """
        Vom Socket lesen, bis dieser "END" sendet
        @type    timeout: int
        @param   timeout: Ein optionales Timeout
        @rtype:  string
        @return: Die Antwort des Liquidsoap-Servers
        """
        # make socket non blocking
        # self.client.setblocking(0)

        data = '';

        try:
94
            # set timeout
95
            self.socket.settimeout(timeout)
96
97
98
99
100

            # acquire the lock
            self.mutex.acquire()

            while True:
101
                data += self.socket.recv(1).decode("utf-8")
102
103
104
105
106
107
108
109
110

                # receive as long as we are not at the END or recv a Bye! from liquidsoap
                if data.find("END\r\n") != -1 or data.find("Bye!\r\n") != -1:
                    data.replace("END\r\n", "")
                    break

            # release the lock
            self.mutex.release()

111
        except Exception as e:
112
            self.logger.error(str(e))
113
            self.mutex.release()
114
115
116
117
118
119

        return data

    # ------------------------------------------------------------------------------------------ #
    def read(self):
        """
120
        read from socket and store return value in self.message
121
        @rtype:  string
122
        @return: The answer of liquidsoap server
123
124
        """
        if self.connected:
125
            ret = self.read_all().splitlines()
126
127

            try:
128
                last = ret.pop() # pop out end
129

130
131
132
133
                if len(ret) > 1:
                    self.message = str.join(" - ", ret)
                elif len(ret) == 1:
                    self.message = ret[0]
134

135
136
                if last == "Bye!":
                    self.message = last
137

138
            except Exception as e:
139
                self.logger.error(str(e))
140
141
142
143
144
145
146
147
148
149

            return self.message

    # ------------------------------------------------------------------------------------------ #
    def close(self):
        """
        Quit senden und Verbindung schließen
        """
        if self.connected:
            message = "quit\r"
150
151
            self.socket.sendall(message.decode("UTF-8"))
            self.socket.close()
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
            self.connected = False

    # ------------------------------------------------------------------------------------------ #
    def command(self, namespace, command, param=""):
        """
        Kommando an Liquidosap senden
        @type    command:   string
        @param   command:   Kommando
        @type    namespace: string
        @param   namespace: Namespace/Kanal der angesprochen wird
        @type    param:     mixed
        @param   param:     ein optionaler Parameter
        @rtype:  string
        @return: Die Antwort des Liquidsoap-Servers
        """

        param = (param.strip() if param.strip() == "" else " " + urllib.parse.unquote(param.strip()))
        if self.connected:
            # print namespace + '.' + command + param + "\n"
            if namespace is "":
172
                message = str(command) + str(param) + str("\n")
173
            else:
174
                message = str(namespace) + str(".") + str(command) + str(param) + str("\n")
175
176

            try:
177
                self.logger.info("LiquidSoapClient sending to LiquidSoap Server: " + message[0:len(message)-1])
178
179

                # send all the stuff over the socket to liquidsoap server
180
                self.socket.sendall(message.encode())
181

182
                self.logger.debug("LiquidSoapClient waiting for reply from LiquidSoap Server")
183
184

                # wait for reply
185
                self.read()
186

187
188
189
                self.logger.info("LiquidSoapClient got reply: " + self.message)
            except Exception as e:
                self.logger.error("Unexpected error: " + str(e))
190
191
192
193
                raise

            return self.message
        else:
194
            raise LQConnectionError("LiquidSoapClient not connected to LiquidSoap Server")
195
196
197
198
199
200
201
202
203
204
205
206
207

    # ------------------------------------------------------------------------------------------ #
    def simplecommand(self, command):
        """
        Parameterloses Kommando ohne Namespace senden
        @type    command:   string
        @param   command:   Kommando
        @rtype:  string
        @return: Die Antwort des Liquidsoap-Servers
        """

        if self.connected:
            message = str(command) + '\n'
208
            self.socket.sendall(message.decode("UTF-8"))
209
210
211
212
213
            self.read()
            # self.client.close()
            return self.message

    # ------------------------------------------------------------------------------------------ #
214
    def get_metadata(self, rid):
215
216
217
218
219
220
221
222
223
224
        """
        Parameterloses Kommando ohne Namespace senden
        @type    rid:   string/int
        @param   rid:   Die ID eines Requests
        @rtype:  dict
        @return: Die Metadaten als dict
        """
        meta = self.command('metadata ' + str(rid), 'request')

        meta = '[root]\n' + meta
225
226
227
228
229
        try:
            self.metareader.read_string(meta)
        except configparser.ParsingError as e:
            self.logger.error("ParsingError. Reason: " + str(e))
            return False
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
        return self.metareader

    # ------------------------------------------------------------------------------------------ #
    def help(self):
        """
        get liquidsoap server help
        @rtype:  string
        @return: the response of the liquidsoap server
        """
        if self.connected:
            self.command('help', '')
            return self.message

    # ------------------------------------------------------------------------------------------ #
    def version(self):
        """
        Liquidsoap get version
        @rtype:  string
        @return: the response of the liquidsoap server
        """
        if self.connected:
            message = 'version'
            self.command(message, '')
            return self.message

    # ------------------------------------------------------------------------------------------ #
    def uptime(self):
        """
        Liquidsoap get uptime
        @rtype:  string
        @return: Die Antwort des Liquidsoap-Servers
        """

        if self.connected:
            self.command('uptime', '')
            return self.message

    # ------------------------------------------------------------------------------------------ #
    def byebye(self):
        """
        Liquidsoap say byebye
        @rtype:  string
        @return: Die Antwort des Liquidsoap-Servers
        """

        if self.connected:
276
            self.command("", "quit")
277
            return self.message