client.py 8.98 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 modules.base.exceptions import LQConnectionError
David Trattnig's avatar
David Trattnig committed
33
from modules.base.utils import TerminalColors
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
    disable_logging = True
47

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

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

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

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

87
88
89

# AttributeError('characters_written')

90
    # ------------------------------------------------------------------------------------------ #
91
    def is_connected(self):
92
93
94
95
96
97
98
99
100
101
        return self.connected

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

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

David Trattnig's avatar
David Trattnig committed
116
        data = ''
117
118

        try:
119
            # set timeout
120
            self.socket.settimeout(timeout)
121
122
123
124
125

            # acquire the lock
            self.mutex.acquire()

            while True:
126
                data += self.socket.recv(1).decode("utf-8")
127
128
129
130
131
132
133
134
135

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

136
        except Exception as e:
137
            self.logger.error(TerminalColors.RED.value+str(e)+TerminalColors.ENDC.value)
138
            self.mutex.release()
139
140
141
142
143
144

        return data

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

            try:
153
                last = ret.pop() # pop out end
154

155
156
157
158
                if len(ret) > 1:
                    self.message = str.join(" - ", ret)
                elif len(ret) == 1:
                    self.message = ret[0]
159

160
161
                if last == "Bye!":
                    self.message = last
162

163
            except Exception as e:
164
                self.logger.error(str(e))
165
166
167
168
169
170
171
172
173
174

            return self.message

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

            try:
202
                if not self.disable_logging:
203
                    self.logger.info("LiquidSoapClient sending to LiquidSoap Server: " + message[0:len(message)-1])
204
205

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

208
                if not self.disable_logging:
209
                    self.logger.debug("LiquidSoapClient waiting for reply from LiquidSoap Server")
210
211

                # wait for reply
212
                self.read()
213

214
                if not self.disable_logging:
215
                    self.logger.info("LiquidSoapClient got reply: " + self.message)
216
            except BrokenPipeError as e:
217
                self.logger.error(TerminalColors.RED.value+"Detected a problem with liquidsoap connection while sending: " + message + ". Reason: " + str(e) + "! Trying to reconnect."+TerminalColors.RED.value)
218
219
220
                self.connect()
                raise

221
222
            except Exception as e:
                self.logger.error("Unexpected error: " + str(e))
223
224
225
226
                raise

            return self.message
        else:
227
            msg = "LiquidsoapClient not connected to LiquidSoap Server"
228
            self.logger.error(msg)
229
            raise LQConnectionError(msg)
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

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