client.py 8.59 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
27
import socket
import urllib.parse
import configparser
28
import logging
29

30
from multiprocessing import Lock
31

32
from libraries.exceptions.auraexceptions import LQConnectionError
33
34


35
36
37
""" 
    LiquidSoapClient Class 
    Connects to a LiquidSoap instance over a socket and sends commands to it
38
39
40
"""


41
class LiquidSoapClient:
42
43
    mutex = None
    logger = None
44
    debug = False
45
    socket_path = ""
46

47
    def __init__(self, config, socket_filename):
48
49
        """
        Constructor
50
51
        @type    socket_path: string
        @param   socket_path: Der Pfad zum Socket des Liquidsoap-Scripts
52
        """
53
        self.logger = logging.getLogger("AuraEngine")
54
55
        self.socket_path = config.get('socketdir') + '/' + socket_filename

56
        self.logger.debug("LiquidSoapClient using socketpath: " + self.socket_path)
57

58
        # init
59
        self.mutex = Lock()
60
61
62
        self.connected = False
        self.can_connect = True
        self.message = ''
63
64
        self.socket = None
        self.metareader = configparser.ConfigParser()
65
66
67
68
69
70
71

    # ------------------------------------------------------------------------------------------ #
    def connect(self):
        """
        Verbindung herstellen
        """
        try:
72
73
74
            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)
75
        except socket.error as e:
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
76
77
            msg = "Cannot connect to socketpath " + self.socket_path + ". Reason: "+str(e)
            self.logger.critical(msg)
78
            self.can_connect = False
79
            self.connected = False
Gottfried Gaisbauer's avatar
Gottfried Gaisbauer committed
80
#            raise e
81
82
83
84
85
86
        else:
            self.can_connect = True
            self.connected = True
            return True

    # ------------------------------------------------------------------------------------------ #
87
    def is_connected(self):
88
89
90
91
92
93
94
95
96
97
        return self.connected

    # ------------------------------------------------------------------------------------------ #
    def write(self, data):
        """
        Auf den Socket schreiben
        @type    data: string
        @param   data: Der String der gesendet wird
        """
        if self.connected:
98
            self.socket.sendall(data.decode("UTF-8"))
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

    # ------------------------------------------------------------------------------------------ #
    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:
115
            # set timeout
116
            self.socket.settimeout(timeout)
117
118
119
120
121

            # acquire the lock
            self.mutex.acquire()

            while True:
122
                data += self.socket.recv(1).decode("utf-8")
123
124
125
126
127
128
129
130
131

                # 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()

132
        except Exception as e:
133
            self.logger.error(str(e))
134
            self.mutex.release()
135
136
137
138
139
140

        return data

    # ------------------------------------------------------------------------------------------ #
    def read(self):
        """
141
        read from socket and store return value in self.message
142
        @rtype:  string
143
        @return: The answer of liquidsoap server
144
145
        """
        if self.connected:
146
            ret = self.read_all().splitlines()
147
148

            try:
149
                last = ret.pop() # pop out end
150

151
152
153
154
                if len(ret) > 1:
                    self.message = str.join(" - ", ret)
                elif len(ret) == 1:
                    self.message = ret[0]
155

156
157
                if last == "Bye!":
                    self.message = last
158

159
            except Exception as e:
160
                self.logger.error(str(e))
161
162
163
164
165
166
167
168
169
170

            return self.message

    # ------------------------------------------------------------------------------------------ #
    def close(self):
        """
        Quit senden und Verbindung schließen
        """
        if self.connected:
            message = "quit\r"
171
172
            self.socket.sendall(message.decode("UTF-8"))
            self.socket.close()
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
            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 "":
193
                message = str(command) + str(param) + str("\n")
194
            else:
195
                message = str(namespace) + str(".") + str(command) + str(param) + str("\n")
196
197

            try:
198
                self.logger.info("LiquidSoapClient sending to LiquidSoap Server: " + message[0:len(message)-1])
199
200

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

203
                self.logger.debug("LiquidSoapClient waiting for reply from LiquidSoap Server")
204
205

                # wait for reply
206
                self.read()
207

208
                self.logger.info("LiquidSoapClient got reply: " + self.message)
209
210
211
212
213
            except BrokenPipeError as e:
                self.logger.error("Detected a problem with liquidsoap connection while sending: " + message + ". Reason: " + str(e) + "! Trying to reconnect.")
                self.connect()
                raise

214
215
            except Exception as e:
                self.logger.error("Unexpected error: " + str(e))
216
217
218
219
                raise

            return self.message
        else:
220
221
222
            msg = "LiquidsoapClient not connected to LiquidSoap Server"
            self.logger.debug(msg)
            raise LQConnectionError(msg)
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

    # ------------------------------------------------------------------------------------------ #
    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:
268
            self.command("", "quit")
269
            return self.message