temp share support
[pyTivo/wmcbrine/lucasnz.git] / config.py
blob20fa9382975d81102164e34e006b804e4b59f817
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', '4K']:
72 tivos_found = True
73 tivos[tsn] = Bdict(config.items(section))
75 for section in ['Server', '_tivo_SD', '_tivo_HD', '_tivo_4K']:
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 getFFmpegPrams(tsn):
263 return get_tsn('ffmpeg_pram', tsn, True)
265 def isHDtivo(tsn): # TSNs of High Definition TiVos
266 return bool(tsn and tsn[0] >= '6' and tsn[:3] != '649')
268 def is4Ktivo(tsn): # TSNs of 4K TiVos
269 return bool(tsn[:3] in ('849', '8F9'))
271 def has_ts_flag():
272 try:
273 return config.getboolean('Server', 'ts')
274 except:
275 return False
277 def is_ts_capable(tsn): # tsn's of Tivos that support transport streams
278 return bool(tsn and (tsn[0] >= '7' or tsn.startswith('663')))
280 def getValidWidths():
281 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
283 def getValidHeights():
284 return [1080, 720, 480] # Technically 240 is also supported
286 # Return the number in list that is nearest to x
287 # if two values are equidistant, return the larger
288 def nearest(x, list):
289 return reduce(lambda a, b: closest(x, a, b), list)
291 def closest(x, a, b):
292 da = abs(x - a)
293 db = abs(x - b)
294 if da < db or (da == db and a > b):
295 return a
296 else:
297 return b
299 def nearestTivoHeight(height):
300 return nearest(height, getValidHeights())
302 def nearestTivoWidth(width):
303 return nearest(width, getValidWidths())
305 def getTivoHeight(tsn):
306 if is4Ktivo(tsn):
307 return 2160
308 else:
309 return [480, 1080][isHDtivo(tsn)]
311 def getTivoWidth(tsn):
312 if is4Ktivo(tsn):
313 return 3840
314 else:
315 return [544, 1920][isHDtivo(tsn)]
317 def _trunc64(i):
318 return max(int(strtod(i)) / 64000, 1) * 64
320 def getAudioBR(tsn=None):
321 rate = get_tsn('audio_br', tsn)
322 if not rate:
323 rate = '448k'
324 # convert to non-zero multiple of 64 to ensure ffmpeg compatibility
325 # compare audio_br to max_audio_br and return lowest
326 return str(min(_trunc64(rate), getMaxAudioBR(tsn))) + 'k'
328 def _k(i):
329 return str(int(strtod(i)) / 1000) + 'k'
331 def getVideoBR(tsn=None):
332 rate = get_tsn('video_br', tsn)
333 if rate:
334 return _k(rate)
335 if is4Ktivo(tsn):
336 return getMaxVideoBR(tsn)
337 else:
338 return ['4096K', '16384K'][isHDtivo(tsn)]
340 def getMaxVideoBR(tsn=None):
341 rate = get_tsn('max_video_br', tsn)
342 if rate:
343 return _k(rate)
344 return '30000k'
346 def getBuffSize(tsn=None):
347 size = get_tsn('bufsize', tsn)
348 if size:
349 return _k(size)
350 if is4Ktivo(tsn):
351 return '8192k'
352 else:
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 if is4Ktivo(tsn):
364 return '_tivo_4K'
365 else:
366 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
368 def get_tsn(name, tsn=None, raw=False):
369 try:
370 return config.get('_tivo_' + tsn, name, raw)
371 except:
372 try:
373 return config.get(get_section(tsn), name, raw)
374 except:
375 try:
376 return config.get('Server', name, raw)
377 except:
378 return None
380 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
381 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
382 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
383 def strtod(value):
384 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
385 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
386 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
387 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
388 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
389 m = p.match(value)
390 if not m:
391 raise SyntaxError('Invalid bit value syntax')
392 (coef, prefix, power, byte) = m.groups()
393 if prefix is None:
394 value = float(coef)
395 else:
396 exponent = float(prefixes[prefix])
397 if power == 'i':
398 # Use powers of 2
399 value = float(coef) * pow(2.0, exponent / 0.3)
400 else:
401 # Use powers of 10
402 value = float(coef) * pow(10.0, exponent)
403 if byte == 'B': # B == Byte, b == bit
404 value *= 8;
405 return value
407 def init_logging():
408 if (config.has_section('loggers') and
409 config.has_section('handlers') and
410 config.has_section('formatters')):
412 logging.config.fileConfig(config_files)
414 elif getDebug():
415 logging.basicConfig(level=logging.DEBUG)
416 else:
417 logging.basicConfig(level=logging.INFO)