-
Notifications
You must be signed in to change notification settings - Fork 0
/
addon.py
executable file
·219 lines (183 loc) · 6.9 KB
/
addon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/python3
'''
Envia comandos ao XBMC.
'''
from importlib import util
import threading
import subprocess
import socket
import sys
import os
import time
import http.server
import socketserver
from urllib.parse import urlparse, parse_qs
os.chdir( os.path.join(os.path.dirname(os.path.abspath(__file__))) )
xbmc_path = util.find_spec("kodi_six")
if xbmc_path:
from kodi_six import xbmc, xbmcaddon, xbmcplugin, xbmcgui
def mPrint(msg):
if xbmc_path:
xbmc.log(msg, level=xbmc.LOGINFO)
else:
print(msg)
def Notificar(msg):
if xbmc_path:
dialog = xbmcgui.Dialog()
dialog.notification('Kodi Alexa TV', msg, xbmcgui.NOTIFICATION_INFO, 5000)
# xbmc.executebuiltin("Notification(Kodi Alexa TV, %s)" % msg)
def NotificarWarn(msg):
if xbmc_path:
dialog = xbmcgui.Dialog()
dialog.notification('Kodi Alexa TV', msg, xbmcgui.NOTIFICATION_WARNING, 5000)
def NotificarErr(msg):
if xbmc_path:
dialog = xbmcgui.Dialog()
dialog.notification('Kodi Alexa TV', msg, xbmcgui.NOTIFICATION_ERROR, 5000)
def lancar_servico(app, secret, tv):
t1 = threading.Thread(
target= lambda: subprocess.call('python3 servico.py %d %s %s %s' % (os.getpid(), app, secret, tv), shell=True, cwd=os.path.dirname(os.path.abspath(__file__)))
)
t1.start()
# Addon settings parse:
def get_setting(setting_id):
if not xbmc_path:
return ""
addon = xbmcaddon.Addon()
setting = addon.getSetting(setting_id)
if setting == 'true':
return True
elif setting == 'false':
return False
else:
return setting
def set_setting(key, value):
if not xbmc_path:
return
return xbmcaddon.Addon().setSetting(key, value)
def get_string(idStr):
if not xbmc_path:
return ""
return xbmcaddon.Addon().getLocalizedString(idStr)
# Web settings page:
class WebKeysSetupHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if "/alexatv" not in self.path:
self.send_response(403)
return
# self.server.server_close()
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
appkey = get_setting('appkey')
secretkey = get_setting('secretkey')
tvKey = get_setting('myTv')
query_components = parse_qs(urlparse(self.path).query)
if ('appkey' in query_components) and ('secretkey' in query_components) and ('tvKey' in query_components):
mPrint('ADDON HTTP> %s' % str(query_components))
appkey = query_components["appkey"][0]
secretkey = query_components["secretkey"][0]
tvKey = query_components["tvKey"][0]
set_setting("appkey", appkey)
set_setting("secretkey", secretkey)
set_setting("myTv", tvKey)
Notificar(get_string(32010)) # Saved settings, rebooting
time.sleep(5)
xbmc.executebuiltin("Reboot")
self.wfile.write(bytes("<h1>Rebooting.</h1>", "utf8"))
return
# Some custom HTML code, possibly generated by another function
html = f"""<html><head><title>Kodi Alexa TV - Settings</title></head>
<body>
<form action="/alexatv" method="get">
<p>Create credentials on <a href="https://sinric.pro/" target="_blank">Sinric.pro</a>.</p>
<br/>
appKey:<input name="appkey" value="{appkey}" type="text"/><br/>
secretkey:<input name="secretkey" value="{secretkey}" type="text"/><br/>
tvKey:<input name="tvKey" value="{tvKey}" type="text"/><br/>
<input value="Save and reboot" type="submit"/>
</form>
</body></html>"""
self.wfile.write(bytes(html, "utf8"))
return
# return http.server.SimpleHTTPRequestHandler.do_GET(self)
def doPageKeySettings():
handler_object = WebKeysSetupHandler
PORT = 51494 # Sinric
server = socketserver.TCPServer(("", PORT), handler_object)
Notificar("-> http://%s:%d/alexatv <-" % (str(xbmc.getIPAddress()), PORT ) )
server.serve_forever()
def processaInput(inp : list):
if "keyssetup" in inp:
doPageKeySettings()
if __name__ == '__main__':
# Requisicao de keysettings
if len(sys.argv[1:]) >= 1:
processaInput(sys.argv[1:])
exit(1)
if xbmc_path:
appkey = get_setting('appkey')
secretkey = get_setting('secretkey')
tvKey = get_setting('myTv')
if len(appkey) == 0 or len(secretkey) == 0 or len(tvKey) == 0:
NotificarWarn(get_string(32011)) # Configure keys!
time.sleep(4)
processaInput(["keyssetup"])
exit(-1)
else: # LOCAL DEBUG
from config.credentials import appKey, secretKey, myTv
appkey = appKey
secretkey = secretKey
tvKey = myTv
Notificar(get_string(32012)) # Starting service
# mPrint("Script atual: %s | CWD= %s | ARGS= %s\n" % (os.path.abspath(__file__), os.path.abspath(os.getcwd()), str(sys.argv[1:]) ))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('localhost', 10001)
mPrint('ADDON> Iniciando em %s:%s' % server_address)
contagemFalhas = 0
concluido = False
while not concluido:
try:
sock.bind(server_address)
concluido = True
except socket.error as msg:
if contagemFalhas >= 3: # Falhas consecultivas, reinicia
NotificarErr(get_string(32013)) # Reiniciando
time.sleep(3)
xbmc.executebuiltin("Reboot")
contagemFalhas = contagemFalhas+1
mPrint('ADDON ERR> %s' % msg)
time.sleep(2) # Aguarda 2s e tenta dnv
lancar_servico(appkey, secretkey, tvKey)
Notificar(get_string(32014)) # Pronto
mPrint("ADDON> Servico pronto.")
sock.listen(1)
# sock.setblocking(True)
sock.settimeout(0)
while True:
try:
connection, client_address = sock.accept()
except socket.error as E:
continue
try:
data = connection.recv(1024)
if not data:
mPrint("ADDON> ERR")
else:
receive = data.decode("utf-8")
mPrint("ADDON RECV> %s" % receive)
# https://codedocs.xyz/AlwinEsch/kodi/class_x_b_m_c_addon_1_1xbmc_1_1_player.html
if receive == "Play":
if xbmc.Player().isPlaying():
xbmc.Player().pause()
else:
xbmc.Player().play()
elif receive == "Pause":
xbmc.Player().pause()
elif receive == "Stop":
xbmc.Player().stop()
elif "LOG:" not in receive:
xbmc.executebuiltin(receive)
finally:
connection.close()