Bogue exception handling.
[pyTivo/wmcbrine.git] / config.py
blob5e36901a0f852fb737181f6eb5e613cddfdab942
1 import ConfigParser
2 import getopt
3 import logging
4 import logging.config
5 import os
6 import re
7 import socket
8 import sys
9 import uuid
10 from ConfigParser import NoOptionError
12 class Bdict(dict):
13 def getboolean(self, x):
14 return self.get(x, 'False').lower() in ('1', 'yes', 'true', 'on')
16 def init(argv):
17 global tivos
18 global tivo_names
19 global guid
20 global config_files
22 tivos = {}
23 tivo_names = {}
24 guid = uuid.uuid4()
26 p = os.path.dirname(__file__)
27 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
29 try:
30 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
31 except getopt.GetoptError, msg:
32 print msg
34 for opt, value in opts:
35 if opt in ('-c', '--config'):
36 config_files = [value]
37 elif opt in ('-e', '--extraconf'):
38 config_files.append(value)
40 reset()
42 def reset():
43 global bin_paths
44 global config
45 global configs_found
47 bin_paths = {}
49 config = ConfigParser.ConfigParser()
50 configs_found = config.read(config_files)
51 if not configs_found:
52 print ('WARNING: pyTivo.conf does not exist.\n' +
53 'Assuming default values.')
54 configs_found = config_files[-1:]
56 for section in config.sections():
57 if section.startswith('_tivo_'):
58 tsn = section[6:]
59 if tsn.upper() not in ['SD', 'HD']:
60 if config.has_option(section, 'name'):
61 tivo_names[tsn] = config.get(section, 'name')
62 else:
63 tivo_names[tsn] = tsn
64 if config.has_option(section, 'address'):
65 tivos[tsn] = config.get(section, 'address')
67 for section in ['Server', '_tivo_SD', '_tivo_HD']:
68 if not config.has_section(section):
69 config.add_section(section)
71 def write():
72 f = open(configs_found[-1], 'w')
73 config.write(f)
74 f.close()
76 def tivos_by_ip(tivoIP):
77 for key, value in tivos.items():
78 if value == tivoIP:
79 return key
81 def get_server(name, default=None):
82 if config.has_option('Server', name):
83 return config.get('Server', name)
84 else:
85 return default
87 def getGUID():
88 return str(guid)
90 def get_ip(tsn=None):
91 dest_ip = tivos.get(tsn, '4.2.2.1')
92 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
93 s.connect((dest_ip, 123))
94 return s.getsockname()[0]
96 def get_zc():
97 opt = get_server('zeroconf', 'auto').lower()
99 if opt == 'auto':
100 for section in config.sections():
101 if section.startswith('_tivo_'):
102 if config.has_option(section, 'shares'):
103 logger = logging.getLogger('pyTivo.config')
104 logger.info('Shares security in use -- zeroconf disabled')
105 return False
106 elif opt in ['false', 'no', 'off']:
107 return False
109 return True
111 def get_mind(tsn):
112 if tsn and tsn.startswith('663'):
113 default = 'symind.tivo.com:8181'
114 else:
115 default = 'mind.tivo.com:8181'
116 return get_server('tivo_mind', default)
118 def getBeaconAddresses():
119 return get_server('beacon', '255.255.255.255')
121 def getPort():
122 return get_server('port', '9032')
124 def get169Blacklist(tsn): # tivo does not pad 16:9 video
125 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
126 # verified Blacklist Tivo's are ('130', '240', '540')
127 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
129 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
130 return tsn and tsn[:3] in ['649']
132 def get169Setting(tsn):
133 if not tsn:
134 return True
136 tsnsect = '_tivo_' + tsn
137 if config.has_section(tsnsect):
138 if config.has_option(tsnsect, 'aspect169'):
139 try:
140 return config.getboolean(tsnsect, 'aspect169')
141 except ValueError:
142 pass
144 if get169Blacklist(tsn) or get169Letterbox(tsn):
145 return False
147 return True
149 def getAllowedClients():
150 return get_server('allowedips', '').split()
152 def getIsExternal(tsn):
153 tsnsect = '_tivo_' + tsn
154 if tsnsect in config.sections():
155 if config.has_option(tsnsect, 'external'):
156 try:
157 return config.getboolean(tsnsect, 'external')
158 except ValueError:
159 pass
161 return False
163 def isTsnInConfig(tsn):
164 return ('_tivo_' + tsn) in config.sections()
166 def getShares(tsn=''):
167 shares = [(section, Bdict(config.items(section)))
168 for section in config.sections()
169 if not (section.startswith(('_tivo_', 'logger_', 'handler_',
170 'formatter_'))
171 or section in ('Server', 'loggers', 'handlers',
172 'formatters')
176 tsnsect = '_tivo_' + tsn
177 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
178 # clean up leading and trailing spaces & make sure ref is valid
179 tsnshares = []
180 for x in config.get(tsnsect, 'shares').split(','):
181 y = x.strip()
182 if config.has_section(y):
183 tsnshares.append((y, Bdict(config.items(y))))
184 shares = tsnshares
186 shares.sort()
188 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
189 shares.append(('Settings', {'type': 'settings'}))
190 if get_server('tivo_mak') and get_server('togo_path'):
191 shares.append(('ToGo', {'type': 'togo'}))
193 return shares
195 def getDebug():
196 try:
197 return config.getboolean('Server', 'debug')
198 except:
199 return False
201 def getOptres(tsn=None):
202 try:
203 return config.getboolean('_tivo_' + tsn, 'optres')
204 except:
205 try:
206 return config.getboolean(get_section(tsn), 'optres')
207 except:
208 try:
209 return config.getboolean('Server', 'optres')
210 except:
211 return False
213 def get_bin(fname):
214 global bin_paths
216 logger = logging.getLogger('pyTivo.config')
218 if fname in bin_paths:
219 return bin_paths[fname]
221 if config.has_option('Server', fname):
222 fpath = config.get('Server', fname)
223 if os.path.exists(fpath) and os.path.isfile(fpath):
224 bin_paths[fname] = fpath
225 return fpath
226 else:
227 logger.error('Bad %s path: %s' % (fname, fpath))
229 if sys.platform == 'win32':
230 fext = '.exe'
231 else:
232 fext = ''
234 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
235 os.getenv('PATH').split(os.pathsep)):
236 fpath = os.path.join(path, fname + fext)
237 if os.path.exists(fpath) and os.path.isfile(fpath):
238 bin_paths[fname] = fpath
239 return fpath
241 logger.warn('%s not found' % fname)
242 return None
244 def getFFmpegWait():
245 if config.has_option('Server', 'ffmpeg_wait'):
246 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
247 else:
248 return 0
250 def getFFmpegTemplate(tsn):
251 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
252 if tmpl:
253 return tmpl
254 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
255 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
256 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
257 %(ffmpeg_pram)s %(format)s'
259 def getFFmpegPrams(tsn):
260 return get_tsn('ffmpeg_pram', tsn, True)
262 def isHDtivo(tsn): # tsn's of High Definition Tivo's
263 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
265 def has_ts_flag():
266 try:
267 return config.getboolean('Server', 'ts')
268 except:
269 return False
271 def is_ts_capable(tsn): # tsn's of Tivos that support transport streams
272 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
274 def getValidWidths():
275 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
277 def getValidHeights():
278 return [1080, 720, 480] # Technically 240 is also supported
280 # Return the number in list that is nearest to x
281 # if two values are equidistant, return the larger
282 def nearest(x, list):
283 return reduce(lambda a, b: closest(x, a, b), list)
285 def closest(x, a, b):
286 da = abs(x - a)
287 db = abs(x - b)
288 if da < db or (da == db and a > b):
289 return a
290 else:
291 return b
293 def nearestTivoHeight(height):
294 return nearest(height, getValidHeights())
296 def nearestTivoWidth(width):
297 return nearest(width, getValidWidths())
299 def getTivoHeight(tsn):
300 height = get_tsn('height', tsn)
301 if height:
302 return nearestTivoHeight(int(height))
303 return [480, 1080][isHDtivo(tsn)]
305 def getTivoWidth(tsn):
306 width = get_tsn('width', tsn)
307 if width:
308 return nearestTivoWidth(int(width))
309 return [544, 1920][isHDtivo(tsn)]
311 def _trunc64(i):
312 return max(int(strtod(i)) / 64000, 1) * 64
314 def getAudioBR(tsn=None):
315 rate = get_tsn('audio_br', tsn)
316 if not rate:
317 rate = '448k'
318 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
319 # compare audio_br to max_audio_br and return lowest
320 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
322 def _k(i):
323 return str(int(strtod(i)) / 1000) + 'k'
325 def getVideoBR(tsn=None):
326 rate = get_tsn('video_br', tsn)
327 if rate:
328 return _k(rate)
329 return ['4096K', '16384K'][isHDtivo(tsn)]
331 def getMaxVideoBR(tsn=None):
332 rate = get_tsn('max_video_br', tsn)
333 if rate:
334 return _k(rate)
335 return '30000k'
337 def getBuffSize(tsn=None):
338 size = get_tsn('bufsize', tsn)
339 if size:
340 return _k(size)
341 return ['1024k', '4096k'][isHDtivo(tsn)]
343 def getMaxAudioBR(tsn=None):
344 rate = get_tsn('max_audio_br', tsn)
345 # convert to non-zero multiple of 64 for ffmpeg compatibility
346 if rate:
347 return _trunc64(rate)
348 return 448
350 def get_section(tsn):
351 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
353 def get_tsn(name, tsn=None, raw=False):
354 try:
355 return config.get('_tivo_' + tsn, name, raw)
356 except:
357 try:
358 return config.get(get_section(tsn), name, raw)
359 except:
360 try:
361 return config.get('Server', name, raw)
362 except:
363 return None
365 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
366 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
367 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
368 def strtod(value):
369 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
370 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
371 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
372 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
373 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
374 m = p.match(value)
375 if not m:
376 raise SyntaxError('Invalid bit value syntax')
377 (coef, prefix, power, byte) = m.groups()
378 if prefix is None:
379 value = float(coef)
380 else:
381 exponent = float(prefixes[prefix])
382 if power == 'i':
383 # Use powers of 2
384 value = float(coef) * pow(2.0, exponent / 0.3)
385 else:
386 # Use powers of 10
387 value = float(coef) * pow(10.0, exponent)
388 if byte == 'B': # B == Byte, b == bit
389 value *= 8;
390 return value
392 def init_logging():
393 if (config.has_section('loggers') and
394 config.has_section('handlers') and
395 config.has_section('formatters')):
397 logging.config.fileConfig(config_files)
399 elif getDebug():
400 logging.basicConfig(level=logging.DEBUG)
401 else:
402 logging.basicConfig(level=logging.INFO)