client.py 8.96 KB
Newer Older
1
#
David Trattnig's avatar
David Trattnig committed
2
# Aura Engine (https://gitlab.servus.at/aura/engine)
3
#
David Trattnig's avatar
David Trattnig committed
4
# Copyright (C) 2017-2020 - The Aura Engine Team.
5
#
David Trattnig's avatar
David Trattnig committed
6
7
8
9
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
10
#
David Trattnig's avatar
David Trattnig committed
11
12
13
14
# This program 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 Affero General Public License for more details.
15
#
David Trattnig's avatar
David Trattnig committed
16
17
18
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

19

20
21
22
import socket
import urllib.parse
import configparser
23
import logging
24

25
from multiprocessing import Lock
26

27
28
from src.base.exceptions import LQConnectionError
from src.base.utils import TerminalColors
29

30

31
32


33
class LiquidSoapClient:
34
35
36
37
38
    """ 
    LiquidSoapClient Class
    
    Connects to a LiquidSoap instance over a socket and sends commands to it
    """
39
40
    mutex = None
    logger = None
41
    debug = False
42
    socket_path = ""
43
    disable_logging = True
44

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

54
        self.logger.debug("LiquidSoapClient using socketpath: " + self.socket_path)
55

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

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

84
85
86

# AttributeError('characters_written')

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

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

    # ------------------------------------------------------------------------------------------ #
    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
113
        data = ''
114
115

        try:
116
            # set timeout
117
            self.socket.settimeout(timeout)
118
119
120
121
122

            # acquire the lock
            self.mutex.acquire()

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

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

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

        return data

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

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

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

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

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

            return self.message

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

            try:
199
                if not self.disable_logging:
David Trattnig's avatar
David Trattnig committed
200
                    self.logger.debug("LiquidSoapClient sending to LiquidSoap Server: " + message[0:len(message)-1])
201
202

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

205
                if not self.disable_logging:
206
                    self.logger.debug("LiquidSoapClient waiting for reply from LiquidSoap Server")
207
208

                # wait for reply
209
                self.read()
210

211
                if not self.disable_logging:
David Trattnig's avatar
David Trattnig committed
212
                    self.logger.debug("LiquidSoapClient got reply: " + self.message)
213
            except BrokenPipeError as e:
214
                self.logger.error(TerminalColors.RED.value+"Detected a problem with liquidsoap connection while sending: " + message + ". Reason: " + str(e) + "! Trying to reconnect."+TerminalColors.RED.value)
215
216
217
                self.connect()
                raise

218
219
            except Exception as e:
                self.logger.error("Unexpected error: " + str(e))
220
221
222
223
                raise

            return self.message
        else:
224
            msg = "LiquidsoapClient not connected to LiquidSoap Server"
225
            self.logger.error(msg)
226
            raise LQConnectionError(msg)
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
268
269
270
271

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