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