-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig.py
286 lines (236 loc) · 8.25 KB
/
config.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
import sys
import os
from glob import glob
import pickle
import configparser
import logging
import logging.config
from tzlocal import get_localzone
from pytz import timezone
from pytz.exceptions import UnknownTimeZoneError
from tablo.api import Api
logger = logging.getLogger(__name__)
# For batch Api call
MAX_BATCH = 50
config = configparser.ConfigParser()
# TODO: see about using this for cleaner variable interpolation
# config = configparser.ConfigParser(
# interpolation=configparser.ExtendedInterpolation
# )
# prevent lowercasing options
config.optionxform = lambda option: option
orig_config = configparser.ConfigParser()
# built in shared options that we aren't allowing to be user-configurable
built_ins = {}
def view():
print(f"Settings from: {built_ins['config_file']}")
print("-" * 50)
# for display purposes...
orig_config['DEFAULT']['base_path'] = built_ins['base_path']
for sect in config.sections():
print(f'[{sect}]')
for item, val in config.items(sect):
ipol_disp = None
if item == 'base_path':
continue
else:
try:
test = orig_config.get(sect, item)
except configparser.NoOptionError:
test = None
def_val = f'{val} (default)'
if not test and not val:
val_disp = def_val
elif test and not val:
val_disp = f'{test} (default) '
elif val == test:
# The cheeky way I'm setting defaults means this can show
# up when it should just be "(default)"
val = config.get(sect, item)
raw_val = config.get(sect, item, raw=True)
if raw_val != val:
val_disp = f'{val} (set to default) '
ipol_disp = raw_val
else:
val_disp = f'{val} (set to default) '
else:
# print(f'{item} = {val}')
val_disp = val
pass
print('{:10}'.format(item) + " = " + val_disp)
if ipol_disp:
print('{:>10}'.format('real') + " = " + ipol_disp)
print()
print()
print("Built-in settings")
print("-" * 50)
print_dict(built_ins, '')
print()
print("Cached Devices")
print("-" * 50)
for name in glob(built_ins['db']['path'] + "device_*"):
with open(name, 'rb') as file:
device = pickle.load(file)
device.dump_info()
print()
print("Devices pre-loaded in Api")
print("-" * 50)
for device in Api.getTablos():
print(f"{device.ID} - {device.IP} - {device.modified}")
if Api.selectDevice(device.ID):
print("\tSuccessfully connected to Tablo!")
else:
print("\tUnable to connect to Tablo!")
print()
def discover(display=True):
Api.discover()
devices = Api.getTablos()
if not devices:
if display:
print("Unable to locate any Tablo devices!")
else:
for device in devices:
device.dump_info()
Api.selectDevice(device.ID)
if display:
print('srvInfo: ')
print_dict(Api.serverInfo)
print('subscription:')
print_dict(Api.subscription)
# cache the devices for later
# TODO: maybe save serverinfo and subscription if find a need
name = "device_" + device.ID
with open(built_ins['db']['path'] + name, 'wb') as file:
pickle.dump(device, file)
def setup():
# create/find what should our config file
if sys.platform == 'win32': # pragma: no cover
path = os.path.expanduser(r'~\Tablo')
else:
path = os.path.expanduser('~/Tablo')
built_ins['base_path'] = path
built_ins['config_file'] = built_ins['base_path'] + "/tablo.ini"
# this is here primarily for display order... :/
built_ins['dry_run'] = False
db_path = built_ins['base_path'] + "/db/"
built_ins['db'] = {
'path': db_path,
'guide': db_path + "guide.json",
'recordings': db_path + "recordings.json",
'recording_shows': db_path + "recording_shows.json"
}
os.makedirs(db_path, exist_ok=True)
if os.path.exists(built_ins['config_file']):
config.read(built_ins['config_file'])
else:
# write out a default config file
config.read_string(DEFAULT_CONFIG_FILE)
with open(built_ins['config_file'], 'w') as configfile:
configfile.write(DEFAULT_CONFIG_FILE)
orig_config.read_string(DEFAULT_CONFIG_FILE)
# Setup config defaults we're not configuring yet, but need
config['DEFAULT']['base_path'] = built_ins['base_path']
tz = ''
try:
tz = config.get('General', 'Timezone')
except configparser.NoSectionError:
config['General'] = {}
try:
timezone(tz)
except UnknownTimeZoneError:
if tz:
print("INVALID Timezone: '" + tz + "' - using defaults")
tz = get_localzone()
if tz:
config.set('General', 'Timezone', str(tz))
orig_config.set('General', 'Timezone', str(tz))
else:
config.set('General', 'Timezone', 'UTC')
orig_config.set('General', 'Timezone', 'UTC')
# Load cached devices so we don't *have* to discover
for name in glob(built_ins['db']['path'] + "device_*"):
with open(name, 'rb') as file:
device = pickle.load(file)
Api.add_device(device)
# if we cn, go ahead and select a default device
# TODO: try to use the config ip/id here too
if Api.devices and len(Api.devices.tablos) == 1:
Api.device = Api.devices.tablos[0]
def setup_logger(level=logging.CRITICAL):
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format':
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': level,
'formatter': 'default',
'stream': 'ext://sys.stdout'
},
},
'root': {
'level': 'DEBUG',
'handlers': ['console']
},
'loggers': {
'default': {
'level': 'DEBUG',
'handlers': ['console']
}
},
})
"""
'file': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'default',
'filename': log_path,
'maxBytes': 1024,
'backupCount': 3
}
"""
# This should be in "util". Either I'm done or python's resolving of cyclical
# imports is ... so here it lays.
def print_dict(dictionary, prefix='\t', braces=1):
""" Recursively prints nested dictionaries."""
for key, value in dictionary.items():
if isinstance(value, dict):
print()
print('%s%s%s%s' % (prefix, braces * '[', key, braces * ']'))
print_dict(value, prefix + ' ', braces + 1)
else:
width = 20 - len(prefix)
w_fmt = '{:' + str(width) + '}'
txt = prefix + w_fmt.format(key) + " = " + str(value)
print(txt)
# print( + '%s = %s' % (key, value))
DEFAULT_CONFIG_FILE = \
"""[General]
Timezone =
# Timezone: defaults to your system, then UTC
[Tablo]
# Define settings for the Tablo device you want to use. Usually only one Tablo
# exists and will be found/used by default, so there's usually no need to set
# these.
#
# The values can be found by running './tablo.py config --discover'
#
# IMPORTANT: If these are set and wrong, you'll need to remove or manually
# change them before things work.
ID =
# ID: the device ID (see above) selects a specific Tablo regardless of IP
# (great for non-reserved DHCP addresses)
IP =
# IP: the device IP address.
[Output Locations]
# The locations/paths recordings will be output to
# These will default to HOME_DIR-Tablo
TV = %(base_path)s/TV
Movies = %(base_path)s/Movies
"""