forked from SensorsIot/IOTstack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.py
executable file
·332 lines (282 loc) · 12.1 KB
/
build.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
220
221
222
223
224
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env python3
issues = {} # Returned issues dict
buildHooks = {} # Options, and others hooks
haltOnErrors = True
# Main wrapper function. Required to make local vars work correctly
def main():
import os
import time
import ruamel.yaml
import signal
import sys
from blessed import Terminal
from deps.chars import specialChars, commonTopBorder, commonBottomBorder, commonEmptyLine, padText
from deps.consts import servicesDirectory, templatesDirectory
from deps.common_functions import getExternalPorts, getInternalPorts, checkPortConflicts, enterPortNumberWithWhiptail
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
global dockerComposeServicesYaml # The loaded memory YAML of all checked services
global toRun # Switch for which function to run when executed
global buildHooks # Where to place the options menu result
global currentServiceName # Name of the current service
global issues # Returned issues dict
global haltOnErrors # Turn on to allow erroring
global hideHelpText # Showing and hiding the help controls text
global serviceService
serviceService = servicesDirectory + currentServiceName
serviceTemplate = templatesDirectory + currentServiceName
try: # If not already set, then set it.
hideHelpText = hideHelpText
except:
hideHelpText = False
documentationHint = 'https://sensorsiot.github.io/IOTstack/Containers/MotionEye'
# runtime vars
portConflicts = []
# This lets the menu know whether to put " >> Options " or not
# This function is REQUIRED.
def checkForOptionsHook():
try:
buildHooks["options"] = callable(runOptionsMenu)
except:
buildHooks["options"] = False
return buildHooks
return buildHooks
# This function is REQUIRED.
def checkForPreBuildHook():
try:
buildHooks["preBuildHook"] = callable(preBuild)
except:
buildHooks["preBuildHook"] = False
return buildHooks
return buildHooks
# This function is REQUIRED.
def checkForPostBuildHook():
try:
buildHooks["postBuildHook"] = callable(postBuild)
except:
buildHooks["postBuildHook"] = False
return buildHooks
return buildHooks
# This function is REQUIRED.
def checkForRunChecksHook():
try:
buildHooks["runChecksHook"] = callable(runChecks)
except:
buildHooks["runChecksHook"] = False
return buildHooks
return buildHooks
# This service will not check anything unless this is set
# This function is optional, and will run each time the menu is rendered
def runChecks():
checkForIssues()
return []
# This function is optional, and will run after the docker-compose.yml file is written to disk.
def postBuild():
return True
# This function is optional, and will run just before the build docker-compose.yml code.
def preBuild():
global dockerComposeServicesYaml
global currentServiceName
if os.path.exists('/dev/video0'):
dockerComposeServicesYaml[currentServiceName]["devices"] = [
'/dev/video0'
]
# Setup service directory
if not os.path.exists(serviceService):
os.makedirs(serviceService, exist_ok=True)
os.makedirs(serviceService + '/etc_motioneye', exist_ok=True)
os.makedirs(serviceService + '/var_lib_motioneye', exist_ok=True)
return True
# #####################################
# Supporting functions below
# #####################################
def checkForIssues():
for (index, serviceName) in enumerate(dockerComposeServicesYaml):
if not currentServiceName == serviceName: # Skip self
currentServicePorts = getExternalPorts(currentServiceName, dockerComposeServicesYaml)
portConflicts = checkPortConflicts(serviceName, currentServicePorts, dockerComposeServicesYaml)
if (len(portConflicts) > 0):
issues["portConflicts"] = portConflicts
# #####################################
# End Supporting functions
# #####################################
############################
# Menu Logic
############################
global currentMenuItemIndex
global selectionInProgress
global menuNavigateDirection
global needsRender
selectionInProgress = True
currentMenuItemIndex = 0
menuNavigateDirection = 0
needsRender = 1
term = Terminal()
hotzoneLocation = [((term.height // 16) + 6), 0]
def goBack():
global selectionInProgress
global needsRender
selectionInProgress = False
needsRender = 1
return True
def enterPortNumberExec():
# global term
global needsRender
global dockerComposeServicesYaml
externalPort = getExternalPorts(currentServiceName, dockerComposeServicesYaml)[0]
internalPort = getInternalPorts(currentServiceName, dockerComposeServicesYaml)[0]
newPortNumber = enterPortNumberWithWhiptail(term, dockerComposeServicesYaml, currentServiceName, hotzoneLocation, externalPort)
if newPortNumber > 0:
dockerComposeServicesYaml[currentServiceName]["ports"][0] = "{newExtPort}:{oldIntPort}".format(
newExtPort = newPortNumber,
oldIntPort = internalPort
)
createMenu()
needsRender = 1
def onResize(sig, action):
global motionEyeBuildOptions
global currentMenuItemIndex
mainRender(1, motionEyeBuildOptions, currentMenuItemIndex)
motionEyeBuildOptions = []
def createMenu():
global motionEyeBuildOptions
try:
motionEyeBuildOptions = []
portNumber = getExternalPorts(currentServiceName, dockerComposeServicesYaml)[0]
motionEyeBuildOptions.append([
"Change external WUI Port Number from: {port}".format(port=portNumber),
enterPortNumberExec
])
except: # Error getting port
pass
motionEyeBuildOptions.append(["Go back", goBack])
def runOptionsMenu():
createMenu()
menuEntryPoint()
return True
def renderHotZone(term, menu, selection, hotzoneLocation):
lineLengthAtTextStart = 71
print(term.move(hotzoneLocation[0], hotzoneLocation[1]))
for (index, menuItem) in enumerate(menu):
toPrint = ""
if index == selection:
toPrint += ('{bv} -> {t.blue_on_green} {title} {t.normal} <-'.format(t=term, title=menuItem[0], bv=specialChars[renderMode]["borderVertical"]))
else:
toPrint += ('{bv} {t.normal} {title} '.format(t=term, title=menuItem[0], bv=specialChars[renderMode]["borderVertical"]))
for i in range(lineLengthAtTextStart - len(menuItem[0])):
toPrint += " "
toPrint += "{bv}".format(bv=specialChars[renderMode]["borderVertical"])
toPrint = term.center(toPrint)
print(toPrint)
def mainRender(needsRender, menu, selection):
term = Terminal()
if needsRender == 1:
print(term.clear())
print(term.move_y(term.height // 16))
print(term.black_on_cornsilk4(term.center('IOTstack MotionEye Options')))
print("")
print(term.center(commonTopBorder(renderMode)))
print(term.center(commonEmptyLine(renderMode)))
print(term.center("{bv} Select Option to configure {bv}".format(bv=specialChars[renderMode]["borderVertical"])))
print(term.center(commonEmptyLine(renderMode)))
if needsRender >= 1:
renderHotZone(term, menu, selection, hotzoneLocation)
if needsRender == 1:
print(term.center(commonEmptyLine(renderMode)))
print(term.center(commonEmptyLine(renderMode)))
if not hideHelpText:
print(term.center(commonEmptyLine(renderMode)))
print(term.center("{bv} Controls: {bv}".format(bv=specialChars[renderMode]["borderVertical"])))
print(term.center("{bv} [Up] and [Down] to move selection cursor {bv}".format(bv=specialChars[renderMode]["borderVertical"])))
print(term.center("{bv} [H] Show/hide this text {bv}".format(bv=specialChars[renderMode]["borderVertical"])))
print(term.center("{bv} [Enter] to run command or save input {bv}".format(bv=specialChars[renderMode]["borderVertical"])))
print(term.center("{bv} [Escape] to go back to build stack menu {bv}".format(bv=specialChars[renderMode]["borderVertical"])))
print(term.center(commonEmptyLine(renderMode)))
if len(documentationHint) > 1:
if len(documentationHint) > 56:
documentationAndPadding = padText(documentationHint, 71)
print(term.center("{bv} Documentation: {bv}".format(bv=specialChars[renderMode]["borderVertical"])))
print(term.center("{bv} {dap} {bv}".format(bv=specialChars[renderMode]["borderVertical"], dap=documentationAndPadding)))
else:
documentationAndPadding = padText(documentationHint, 56)
print(term.center("{bv} Documentation: {dap} {bv}".format(bv=specialChars[renderMode]["borderVertical"], dap=documentationAndPadding)))
print(term.center(commonEmptyLine(renderMode)))
print(term.center(commonEmptyLine(renderMode)))
print(term.center(commonBottomBorder(renderMode)))
def runSelection(selection):
import types
global motionEyeBuildOptions
if len(motionEyeBuildOptions[selection]) > 1 and isinstance(motionEyeBuildOptions[selection][1], types.FunctionType):
motionEyeBuildOptions[selection][1]()
else:
print(term.green_reverse('IOTstack Error: No function assigned to menu item: "{}"'.format(nodeRedBuildOptions[selection][0])))
def isMenuItemSelectable(menu, index):
if len(menu) > index:
if len(menu[index]) > 2:
if menu[index][2]["skip"] == True:
return False
return True
def menuEntryPoint():
# These need to be reglobalised due to eval()
global currentMenuItemIndex
global selectionInProgress
global menuNavigateDirection
global needsRender
global hideHelpText
global motionEyeBuildOptions
term = Terminal()
with term.fullscreen():
menuNavigateDirection = 0
mainRender(needsRender, motionEyeBuildOptions, currentMenuItemIndex)
selectionInProgress = True
with term.cbreak():
while selectionInProgress:
menuNavigateDirection = 0
if needsRender: # Only rerender when changed to prevent flickering
mainRender(needsRender, motionEyeBuildOptions, currentMenuItemIndex)
needsRender = 0
key = term.inkey(esc_delay=0.05)
if key.is_sequence:
if key.name == 'KEY_TAB':
menuNavigateDirection += 1
if key.name == 'KEY_DOWN':
menuNavigateDirection += 1
if key.name == 'KEY_UP':
menuNavigateDirection -= 1
if key.name == 'KEY_LEFT':
goBack()
if key.name == 'KEY_ENTER':
runSelection(currentMenuItemIndex)
if key.name == 'KEY_ESCAPE':
return True
elif key:
if key == 'h': # H pressed
if hideHelpText:
hideHelpText = False
else:
hideHelpText = True
mainRender(1, motionEyeBuildOptions, currentMenuItemIndex)
if menuNavigateDirection != 0: # If a direction was pressed, find next selectable item
currentMenuItemIndex += menuNavigateDirection
currentMenuItemIndex = currentMenuItemIndex % len(motionEyeBuildOptions)
needsRender = 2
while not isMenuItemSelectable(motionEyeBuildOptions, currentMenuItemIndex):
currentMenuItemIndex += menuNavigateDirection
currentMenuItemIndex = currentMenuItemIndex % len(motionEyeBuildOptions)
return True
####################
# End menu section
####################
if haltOnErrors:
eval(toRun)()
else:
try:
eval(toRun)()
except:
pass
# This check isn't required, but placed here for debugging purposes
global currentServiceName # Name of the current service
if currentServiceName == 'motioneye':
main()
else:
print("Error. '{}' Tried to run 'motioneye' config".format(currentServiceName))