-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.py
195 lines (175 loc) · 7.14 KB
/
helper.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
import subprocess
import os
import getpass
import telnetlib
from datetime import datetime
import shelve
import sys
from cryptography.fernet import Fernet
import base64
import paho.mqtt.publish as publish
BLUE = '\033[1;38;2;32;64;227m'
RED = '\033[1;38;2;227;32;32m'
GREEN = '\033[0;38;2;0;192;0m'
YELLOW ='\033[0;38;2;192;192;0m'
NC = '\033[0m'
# change this to your liking
chatID = getpass.getuser()
[serverChoice, mqttBrokerIP, mqttPort, mqttTopic, mqttUsername, mqttPassword, hostIP, hostPort, hostPassword] = ['','','','','','','','','']
# for executing shell commands
def cmdLine(cmd):
process = subprocess.run(args = cmd, capture_output=True, universal_newlines = True, shell = True)
return process
def cmdLineSuppressed(cmd):
process = subprocess.run(args = cmd, capture_output=False, universal_newlines = True, shell = True)
return process
def cmdLineWaitUntilExecution(cmd):
process = subprocess.Popen(args = cmd, universal_newlines = True, shell = True)
if(wait):
while(process.poll() == None):
continue
def getConfigFiles():
global configFiles
configFiles = []
files = os.listdir(os.path.join(os.getcwd(),'config'))
for file in files:
if file.endswith('.config'):
configFiles.append(file)
print(str(len(configFiles)) + ". " + configFiles[len(configFiles) - 1])
def loadFromConfig():
global configFiles, serverChoice, mqttBrokerIP, mqttPort, mqttTopic, mqttUsername, mqttPassword, hostIP, hostPort, hostPassword
if(len(configFiles) > 0):
x = input("Do you want to load any previous configurations?<y/n> : ")
if(x == 'y'):
fileNumber = int(input("Enter corresponding number of file : "))
if((fileNumber) <= len(configFiles)):
shelfFile = shelve.open(os.path.join('config', configFiles[fileNumber - 1]))
if(list(shelfFile['data'])[0] == 1):
# public server
[serverChoice, mqttBrokerIP, mqttPort, mqttTopic, hostIP, hostPort, hostPassword] = list(shelfFile['data'])
return True
else:
# private server
[serverChoice, mqttBrokerIP, mqttPort, mqttTopic, mqttUsername, mqttPassword, hostIP, hostPort, hostPassword] = list(shelfFile['data'])
return True
else:
return False
else:
return False
def storeConfigFile(name):
shelfFile = shelve.open(os.path.join('config',name+'.config'))
if(serverChoice == 1):
shelfFile['data'] = [serverChoice, mqttBrokerIP, mqttPort, mqttTopic, hostIP, hostPort, hostPassword]
else:
shelfFile['data'] = [serverChoice, mqttBrokerIP, mqttPort, mqttTopic, mqttUsername, mqttPassword, hostIP, hostPort, hostPassword]
def promptSaveConfig():
x = input("Do you want to save the current configuration?(y/n) : ")
if(x == 'y'):
name = input("Give a name to the configuration : ")
storeConfigFile(name)
def printConfig():
print("MQTT Broker IP/Server: "+ mqttBrokerIP)
print("MQTT Port: "+ mqttPort)
print("MQTT Topic: "+ mqttTopic)
if(serverChoice == 2):
print("MQTT Username: "+ mqttUsername)
print("VLC Host IP: "+ hostIP)
print("Host Port: "+ hostPort)
def prepConfig():
# if arguments have been passed, prepare list
args = []
for arg in sys.argv:
args.append(arg)
n = len(args)
# command was directly executed
if(n == 1):
getConfigFiles()
if(not loadFromConfig()):
print("1. Public Server \nor\n2. Private Server\nPublic Servers don't use a username and password.")
serverChoice = int(input("Choose (1 or 2): "))
if(serverChoice == 1):
mqttBrokerIP = input("MQTT Broker IP/Server: ")
mqttPort = input("MQTT Port: ")
mqttTopic = input("MQTT Topic: ")
hostIP = input("VLC Host IP: ")
hostPort = input("Host Port: ")
print("Host ", end='')
sys.stdout.flush()
hostPassword = getpass.getpass()
promptSaveConfig()
elif(serverChoice == 2):
mqttBrokerIP = input("MQTT Broker IP/Server: ")
mqttPort = input("MQTT Port: ")
mqttTopic = input("MQTT Topic: ")
mqttUsername = input("MQTT Username: ")
print("MQTT ", end='')
sys.stdout.flush()
mqttPassword = getpass.getpass()
hostIP = input("VLC Host IP: ")
hostPort = input("Host Port: ")
print("Host ", end='')
sys.stdout.flush()
hostPassword = getpass.getpass()
promptSaveConfig()
else:
sys.exit()
else:
print("Loaded Configuration:")
printConfig()
# command was executed with arguments
elif(n == 9):
mqttBrokerIP = args[1]
mqttPort = args[2]
mqttTopic = args[3]
mqttUsername = args[4]
mqttPassword = args[5]
hostIP = args[6]
hostPort = args[7]
hostPassword = args[8]
promptSaveConfig()
# wrong number of arguments
else:
print("Wrong number of arguments!")
print("Usage:\npython3 vlcMQTTSync.py\nor\npython3 vlcMQTTSync.py <mqttBrokerIP> <mqttPort> <mqttTopic> <mqttUsername> <mqttPassword> <hostIP> <hostPassword> <hostPort>")
print("Exiting...")
sys.exit()
# encrypts message using the global fernetObject from helper
def encryptMessage(msg):
if(not fernetObject):
return msg
else:
return fernetObject.encrypt(msg.encode('utf-8'))
# prepare chatKey
def getChatKey():
global fernetObject
chatKey = getpass.getpass("Enter chat key (32 characters maximum):")
# if(chatKey != 'x' or chatKey != 'X'):
# pad chatKey
for i in range(32-len(chatKey)):
chatKey = chatKey + ''.join('0')
# will have to check for a URL safe key here. Probably look at what exception is thrown
# and ask the user to create a key again
fernetObject = Fernet(base64.b64encode(chatKey.encode('utf-8')))
def publishMQTTMsg(msg):
if(serverChoice == 1):
try:
# Don't worry about conflicting timezones, print local time with messages
tt = datetime.today().timetuple()
# x = "("+str(tt.tm_hour)+":"+str(tt.tm_min) +":"+str(tt.tm_sec)+")- " + chatID + "/: " + x
msg = chatID + "/: " + msg
enc = encryptMessage(msg)
publish.single(mqttTopic, enc, hostname=mqttBrokerIP, port=int(mqttPort))
except Exception as e:
print(RED+"Error while sending message"+NC)
print(str(e)+"\n")
else:
authen = {'username':mqttUsername, 'password':mqttPassword}
try:
publish.single(mqttTopic, msg, hostname=mqttBrokerIP, auth=authen, port=int(mqttPort))
except Exception as e:
print(RED+"Error while sending message"+NC)
print(str(e)+"\n")
def secsToHours(secs):
mm, ss = divmod(secs, 60)
hh, mm = divmod(mm, 60)
return "%d:%02d:%02.2f" % (hh, mm, ss)