This repository was archived by the owner on Feb 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
345 lines (302 loc) · 10.9 KB
/
main.py
File metadata and controls
345 lines (302 loc) · 10.9 KB
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
333
334
335
336
337
338
339
340
341
342
343
344
345
import subprocess, threading, time, importlib, sys, requests
import config
threads = []
def block_tup_to_class(tup):
block_module = importlib.import_module('commands.' + tup[0])
block = block_module.Block(tup[3])
block.type = tup[0]
block.icon = tup[1]
block.interval = tup[2]
return block
blocks = list(map(block_tup_to_class, config.blocks))
def setroot(name):
name = name + config.suffix
return subprocess.run(["xsetroot", "-name", name])
def block_fn(block):
t = threading.currentThread()
if not block:
return stop_threads()
while getattr(t, "do_run", True):
block.fetch()
time.sleep(block.interval / 1000)
def create_blocks_threads():
global threads
stop_threads()
threads = []
for block in blocks:
t = threading.Thread(
target=block_fn,
daemon=True,
args=[block] # have to use either [block] or (block,)
)
t.start()
threads.append(t)
def block_to_str(block):
prefix = block.get_icon() if block.override_icon else block.icon
content = block.content
return prefix + content
def stop_threads():
for t in threads:
t.do_run = False
for t in threads:
if not t.is_alive():
t.join() # Waits until thread terminates
def construct_multi_price_url(inputs, outputs):
return f'''https://min-api.cryptocompare.com/data/pricemulti?fsyms={','.join(inputs)}&tsyms={','.join(outputs)}'''
def fetch_crypto_fn():
url = construct_multi_price_url(config.crypto_currencies, [config.fiat_currency])
crypto_module = importlib.import_module('commands.crypto')
t = threading.currentThread()
while getattr(t, "do_run", True):
res = requests.get(url)
data = res.json()
crypto_module.Block.cache = data
time.sleep(config.crypto_interval / 1000)
def create_crypto_thread():
t = threading.Thread(
target=fetch_crypto_fn,
daemon=True
)
t.start()
threads.append(t)
def main():
create_blocks_threads()
if len(config.crypto_currencies) != 0:
create_crypto_thread()
def setter_thread_fn():
t = threading.currentThread()
while getattr(t, "do_run", True):
blocks_strs = map(block_to_str, blocks)
root_str = config.delimeter.join(blocks_strs)
print(root_str)
if '--no-setroot' not in sys.argv:
setroot(root_str)
time.sleep(config.interval / 1000)
global threads
t = threading.Thread(target=setter_thread_fn, daemon=True, name='setter_thread')
t.start()
threads.append(t)
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
print("Recieved SIGINT, stopping xblocks")
stop_threads()
break
if __name__ == "__main__":
main()
import sys
sys.exit()
import subprocess, threading, requests, json, datetime, time, importlib, sys
config = importlib.import_module('config')
blocks_cached_data = {}
threads = []
def reload_config():
global config
config = importlib.import_module('config')
def setroot(name):
reload_config()
name = name + config.suffix
return subprocess.run(["xsetroot", "-name", name])
def get_clock_icon():
clock_pos = datetime.datetime.now().strftime("%I")
if clock_pos == "00": clock_icon = "🕛"
elif clock_pos == "01": clock_icon = "🕐"
elif clock_pos == "02": clock_icon = "🕑"
elif clock_pos == "03": clock_icon = "🕒"
elif clock_pos == "04": clock_icon = "🕓"
elif clock_pos == "05": clock_icon = "🕔"
elif clock_pos == "06": clock_icon = "🕕"
elif clock_pos == "07": clock_icon = "🕖"
elif clock_pos == "08": clock_icon = "🕗"
elif clock_pos == "09": clock_icon = "🕘"
elif clock_pos == "10": clock_icon = "🕙"
elif clock_pos == "11": clock_icon = "🕚"
elif clock_pos == "12": clock_icon = "🕛"
else: clock_icon = "❌"
return clock_icon
def block_to_str(block):
prefix = block[2] if config.use_emoji else block[1]
temp_blocks_cache = blocks_cached_data
if 'crypto' in temp_blocks_cache:
temp_blocks_cache.pop('crypto')
content = temp_blocks_cache.get(block[0], 'Loading')
if type(content) == tuple:
content = content[0]
if prefix == '{}' and block[0] == 'time':
prefix = prefix.format(get_clock_icon())
return prefix + content
def construct_multi_price_url(inputs, outputs):
return f'''https://min-api.cryptocompare.com/data/pricemulti?fsyms={','.join(inputs)}&tsyms={','.join(outputs)}'''
def create_listener_thread(listener):
t = threading.Thread(
target=listener['function'],
daemon=True,
name=listener.get('name', 'Generic listener thread'),
args=listener.get('args', None)
)
return t
def block_fn(block):
t = threading.currentThread()
if not block:
return do_exit()
while getattr(t, "do_run", True):
# TODO do stuff here
if callable(block[0]):
blocks_cached_data[block[0]] = block[0]()
elif 'price ' in block[0]:
# is crypto handler
cryptos_cache = blocks_cached_data.get('price', 'Loading')
if cryptos_cache == 'Loading':
crypto_price = cryptos_cache
else:
# crypto_price = cryptos_cache[0].get(config.fiat_currency.upper(), {})
# crypto_price = crypto_price.get(block[0].replace('price ', '').upper(), 'Error!')
crypto_price = cryptos_cache[0].get(block[0].replace('price ', '').upper(), {})
crypto_price = crypto_price.get(config.fiat_currency.upper(), 'Error!')
crypto_price = f'{config.fiat_currency_prefix}{crypto_price}'
crypto_price = f'{crypto_price}{config.fiat_currency_suffix}'
blocks_cached_data[block[0]] = (crypto_price, datetime.datetime.now())
elif 'cmd ' in block[0]:
command = block[0].replace('cmd ', '')
proc = subprocess.run(["bash", "-c", command], capture_output=True)
raw_output = proc.stdout
output_str = raw_output.decode('utf-8')
blocks_cached_data[block[0]] = output_str
elif block[0] == 'time':
blocks_cached_data[block[0]] = time.strftime('%H:%M:%S')
elif block[0] == 'date':
blocks_cached_data[block[0]] = datetime.date.today().strftime('%d.%m.%Y')
elif block[0] == 'datetime':
blocks_cached_data[block[0]] = datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
else:
pass # is invalid
time.sleep(block[3] / 1000)
if config.debug:
print("Stopped " + t.name + " thread.")
def fetch_fn(options):
name = options['name']
get_url = options['get_url']
use_json = options['use_json']
cache_key = options['cache_key']
get_interval = options['get_interval']
if config.debug:
print('Fetch thread ' + name + ' started')
t = threading.currentThread()
while getattr(t, "do_run", True):
def get_data():
if config.debug:
print('Fetch thread ' + name + ' getting data')
global blocks_cached_data
url = get_url()
res = requests.get(url)
data = res.json() if use_json else res.text
blocks_cached_data[cache_key] = (data, datetime.datetime.now())
def check_get():
if not blocks_cached_data.get(cache_key):
return get_data()
# diff between last request and right now
time_diff = (datetime.datetime.now() - blocks_cached_data[cache_key][1])
time_diff_ms = time_diff.total_seconds() * 1000
# if more diff than interval
if time_diff_ms > get_interval():
return get_data()
time.sleep(1)
check_get()
if config.debug:
print('Stopped ' + name + ' thread.')
def create_crypto_thread():
def get_crypto_url():
reload_config()
return construct_multi_price_url(config.crypto_currencies, [config.fiat_currency])
def get_crypto_interval():
reload_config()
return config.crypto_interval
t = create_listener_thread({
'function': fetch_fn,
'name': 'crypto',
'args': [{
'name': 'crypto',
'get_url': get_crypto_url,
'cache_key': 'price',
'get_interval': get_crypto_interval,
'use_json': True,
}],
})
t.start()
threads.append(t)
def create_weather_thread():
def get_weather_interval():
reload_config()
return config.weather_interval
t = create_listener_thread({
'function': fetch_fn,
'name': 'crypto',
'args': [{
'name': 'weather',
'get_url': lambda: 'https://wttr.in/' + config.weather_location + '?format=%t',
'cache_key': 'weather',
'get_interval': get_weather_interval,
'use_json': False,
}],
})
t.start()
threads.append(t)
def create_blocks_threads():
global threads
stop_threads()
threads = []
for block in config.blocks:
t = create_listener_thread({
'function': block_fn,
'name': block[1],
'args': [block] # have to use either [block] or (block,)
})
t.start()
threads.append(t)
def stop_threads():
for t in threads:
if config.debug:
print("Trying to stop " + t.name + " thread.")
t.do_run = False
for t in threads:
if not t.is_alive():
t.join() # Waits until thread terminates
def do_exit():
if config.debug:
print("Trying to stop listener threads.")
stop_threads()
if config.debug:
print("Stopped listener threads.")
print("Trying to stop main thread.")
setter_thread.do_run = False
setter_thread.join() # Waits until thread terminates
if __name__ == "__main__":
create_blocks_threads()
if len(config.crypto_currencies) > 0:
create_crypto_thread()
if config.fetch_weather:
create_weather_thread()
def setter_thread_fn():
t = threading.currentThread()
while getattr(t, "do_run", True):
blocks_strs = map(block_to_str, config.blocks)
root_str = config.delimeter.join(blocks_strs)
print(root_str)
if '--no-setroot' not in sys.argv:
setroot(root_str)
time.sleep(1)
if config.debug:
print("Stopped main thread.")
setter_thread = threading.Thread(target=setter_thread_fn, daemon=True, name='setter_thread')
setter_thread.start()
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
print("Recieved SIGINT, stopping xblocks")
if config.debug:
print("Cache:", blocks_cached_data)
print("Threads:", threads)
do_exit()
break