mimetype.guess_type() returns a tuple, and it might be (None, None).
[pyTivo/TheBayer.git] / config.py
blobebfadef6ea0c3146824e66e270013729f6fefa97
1 import ConfigParser
2 import getopt
3 import logging
4 import logging.config
5 import os
6 import re
7 import random
8 import socket
9 import string
10 import sys
11 from ConfigParser import NoOptionError
13 guid = ''.join([random.choice(string.letters) for i in range(10)])
14 our_ip = ''
15 config = ConfigParser.ConfigParser()
17 p = os.path.dirname(__file__)
18 config_files = ['/etc/pyTivo.conf', os.path.join(p, 'pyTivo.conf')]
19 configs_found = []
21 tivos = {}
22 tivo_names = {}
23 bin_paths = {}
25 def init(argv):
26 global config_files
27 global configs_found
28 global tivo_names
30 try:
31 opts, _ = getopt.getopt(argv, 'c:e:', ['config=', 'extraconf='])
32 except getopt.GetoptError, msg:
33 print msg
35 for opt, value in opts:
36 if opt in ('-c', '--config'):
37 config_files = [value]
38 elif opt in ('-e', '--extraconf'):
39 config_files.append(value)
41 configs_found = config.read(config_files)
42 if not configs_found:
43 print ('ERROR: pyTivo.conf does not exist.\n' +
44 'You must create this file before running pyTivo.')
45 sys.exit(1)
47 for section in config.sections():
48 if section.startswith('_tivo_'):
49 tsn = section[6:]
50 if tsn.upper() not in ['SD', 'HD']:
51 if config.has_option(section, 'name'):
52 tivo_names[tsn] = config.get(section, 'name')
53 else:
54 tivo_names[tsn] = tsn
56 def reset():
57 global config
58 global bin_paths
59 bin_paths.clear()
60 newconfig = ConfigParser.ConfigParser()
61 newconfig.read(config_files)
62 config = newconfig
64 def write():
65 f = open(configs_found[-1], 'w')
66 config.write(f)
67 f.close()
69 def get_server(name, default=None):
70 if config.has_option('Server', name):
71 return config.get('Server', name)
72 else:
73 return default
75 def getGUID():
76 return guid
78 def get_ip():
79 global our_ip
80 if not our_ip:
81 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
82 s.connect(('4.2.2.1', 123))
83 our_ip = s.getsockname()[0]
84 return our_ip
86 def get_zc():
87 opt = get_server('zeroconf', 'auto').lower()
89 if opt == 'auto':
90 for section in config.sections():
91 if section.startswith('_tivo_'):
92 if config.has_option(section, 'shares'):
93 logger = logging.getLogger('pyTivo.config')
94 logger.info('Shares security in use -- zeroconf disabled')
95 return False
96 elif opt in ['false', 'no', 'off']:
97 return False
99 return True
101 def get_mind(tsn):
102 if tsn and tsn.startswith('663'):
103 default = 'symind.tivo.com:8181'
104 else:
105 default = 'mind.tivo.com:8181'
106 return get_server('tivo_mind', default)
108 def getBeaconAddresses():
109 return get_server('beacon', '255.255.255.255')
111 def getPort():
112 return get_server('port', '9032')
114 def get169Blacklist(tsn): # tivo does not pad 16:9 video
115 return tsn and not isHDtivo(tsn) and not get169Letterbox(tsn)
116 # verified Blacklist Tivo's are ('130', '240', '540')
117 # It is assumed all remaining non-HD and non-Letterbox tivos are Blacklist
119 def get169Letterbox(tsn): # tivo pads 16:9 video for 4:3 display
120 return tsn and tsn[:3] in ['649']
122 def get169Setting(tsn):
123 if not tsn:
124 return True
126 tsnsect = '_tivo_' + tsn
127 if config.has_section(tsnsect):
128 if config.has_option(tsnsect, 'aspect169'):
129 try:
130 return config.getboolean(tsnsect, 'aspect169')
131 except ValueError:
132 pass
134 if get169Blacklist(tsn) or get169Letterbox(tsn):
135 return False
137 return True
139 def getAllowedClients():
140 return get_server('allowedips', '').split()
142 def getIsExternal(tsn):
143 tsnsect = '_tivo_' + tsn
144 if tsnsect in config.sections():
145 if config.has_option(tsnsect, 'external'):
146 try:
147 return config.getboolean(tsnsect, 'external')
148 except ValueError:
149 pass
151 return False
153 def isTsnInConfig(tsn):
154 return ('_tivo_' + tsn) in config.sections()
156 def getShares(tsn=''):
157 shares = [(section, dict(config.items(section)))
158 for section in config.sections()
159 if not (section.startswith('_tivo_')
160 or section.startswith('logger_')
161 or section.startswith('handler_')
162 or section.startswith('formatter_')
163 or section in ('Server', 'loggers', 'handlers',
164 'formatters')
168 tsnsect = '_tivo_' + tsn
169 if config.has_section(tsnsect) and config.has_option(tsnsect, 'shares'):
170 # clean up leading and trailing spaces & make sure ref is valid
171 tsnshares = []
172 for x in config.get(tsnsect, 'shares').split(','):
173 y = x.strip()
174 if config.has_section(y):
175 tsnshares.append((y, dict(config.items(y))))
176 shares = tsnshares
178 shares.sort()
180 if get_server('nosettings', 'false').lower() in ['false', 'no', 'off']:
181 shares.append(('Settings', {'type': 'settings'}))
182 if get_server('tivo_mak') and get_server('togo_path'):
183 shares.append(('ToGo', {'type': 'togo'}))
185 return shares
187 def getDebug():
188 try:
189 return config.getboolean('Server', 'debug')
190 except NoOptionError, ValueError:
191 return False
193 def getOptres(tsn=None):
194 if tsn and config.has_section('_tivo_' + tsn):
195 try:
196 return config.getboolean('_tivo_' + tsn, 'optres')
197 except NoOptionError, ValueError:
198 pass
199 section_name = get_section(tsn)
200 if config.has_section(section_name):
201 try:
202 return config.getboolean(section_name, 'optres')
203 except NoOptionError, ValueError:
204 pass
205 try:
206 return config.getboolean('Server', 'optres')
207 except NoOptionError, ValueError:
208 return False
210 def getPixelAR(ref):
211 if config.has_option('Server', 'par'):
212 try:
213 return (True, config.getfloat('Server', 'par'))[ref]
214 except NoOptionError, ValueError:
215 pass
216 return (False, 1.0)[ref]
218 def get_bin(fname):
219 global bin_paths
221 logger = logging.getLogger('pyTivo.config')
223 if fname in bin_paths:
224 fpath = bin_paths[fname]
225 logger.debug('Using %s' % fpath)
226 return fpath
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 logger.debug('Using %s' % fpath)
232 bin_paths[fname] = fpath
233 return fpath
234 else:
235 logger.error('Bad %s path: %s' % (fname, fpath))
237 if sys.platform == 'win32':
238 fext = '.exe'
239 else:
240 fext = ''
242 for path in ([os.path.join(os.path.dirname(__file__), 'bin')] +
243 os.getenv('PATH').split(os.pathsep)):
244 fpath = os.path.join(path, fname + fext)
245 if os.path.exists(fpath) and os.path.isfile(fpath):
246 logger.debug('Using %s' % fpath)
247 bin_paths[fname] = fpath
248 return fpath
250 logger.warn('%s not found' % fname)
251 return None
253 def getFFmpegWait():
254 if config.has_option('Server', 'ffmpeg_wait'):
255 return max(int(float(config.get('Server', 'ffmpeg_wait'))), 1)
256 else:
257 return 10
259 def getFFmpegTemplate(tsn):
260 tmpl = get_tsn('ffmpeg_tmpl', tsn, True)
261 if tmpl:
262 return tmpl
263 return '%(video_codec)s %(video_fps)s %(video_br)s %(max_video_br)s \
264 %(buff_size)s %(aspect_ratio)s %(audio_br)s \
265 %(audio_fr)s %(audio_ch)s %(audio_codec)s %(audio_lang)s \
266 %(ffmpeg_pram)s %(format)s'
268 def getFFmpegPrams(tsn):
269 return get_tsn('ffmpeg_pram', tsn, True)
271 def isHDtivo(tsn): # tsn's of High Definition Tivo's
272 return bool(tsn and tsn[:3] in ['648', '652', '658', '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 getVideoPCT(tsn=None):
338 pct = get_tsn('video_pct', tsn)
339 if pct:
340 return float(pct)
341 return 85
343 def getBuffSize(tsn=None):
344 size = get_tsn('bufsize', tsn)
345 if size:
346 return _k(size)
347 return ['1024k', '4096k'][isHDtivo(tsn)]
349 def getMaxAudioBR(tsn=None):
350 rate = get_tsn('max_audio_br', tsn)
351 # convert to non-zero multiple of 64 for ffmpeg compatibility
352 if rate:
353 return _trunc64(rate)
354 return 448
356 def get_section(tsn):
357 return ['_tivo_SD', '_tivo_HD'][isHDtivo(tsn)]
359 def get_tsn(name, tsn=None, raw=False):
360 if tsn and config.has_section('_tivo_' + tsn):
361 try:
362 return config.get('_tivo_' + tsn, name, raw)
363 except NoOptionError:
364 pass
365 section_name = get_section(tsn)
366 if config.has_section(section_name):
367 try:
368 return config.get(section_name, name, raw)
369 except NoOptionError:
370 pass
371 try:
372 return config.get('Server', name, raw)
373 except NoOptionError:
374 pass
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)