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