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
from modules.base.exceptions import LQConnectionError
David Trattnig's avatar
David Trattnig committed
28
from modules.base.utils import TerminalColors
29

30
31
32
""" 
    LiquidSoapClient Class 
    Connects to a LiquidSoap instance over a socket and sends commands to it
33
34
35
"""


36
class LiquidSoapClient:
37
38
    mutex = None
    logger = None
39
    debug = False
40
    socket_path = ""
41
    disable_logging = True
42

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

52
        self.logger.debug("LiquidSoapClient using socketpath: " + self.socket_path)
53

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

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

82
83
84

# AttributeError('characters_written')

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

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

    # ------------------------------------------------------------------------------------------ #
    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
111
        data = ''
112
113

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

            # acquire the lock
            self.mutex.acquire()

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

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

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

        return data

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

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

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

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

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

            return self.message

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

            try:
197
                if not self.disable_logging:
David Trattnig's avatar
David Trattnig committed
198
                    self.logger.debug("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
                if not self.disable_logging:
204
                    self.logger.debug("LiquidSoapClient waiting for reply from LiquidSoap Server")
205
206

                # wait for reply
207
                self.read()
208

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

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

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

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