Validate data entered into fields
[pyTivo.git] / config.py
blobd6e3e3087135a9b9d8f0682ec764c7a2d221ed8e
1 import ConfigParser, os
2 import re
3 from ConfigParser import NoOptionError
5 BLACKLIST_169 = ('540', '649')
7 config = ConfigParser.ConfigParser()
8 p = os.path.dirname(__file__)
9 config_file = os.path.join(p, 'pyTivo.conf')
10 config.read(config_file)
12 def reset():
13 global config
14 del config
15 config = ConfigParser.ConfigParser()
16 config.read(config_file)
18 def getGUID():
19 if config.has_option('Server', 'GUID'):
20 guid = config.get('Server', 'GUID')
21 else:
22 guid = '123456'
23 return guid
25 def getBeaconAddresses():
26 if config.has_option('Server', 'beacon'):
27 beacon_ips = config.get('Server', 'beacon')
28 else:
29 beacon_ips = '255.255.255.255'
30 return beacon_ips
32 def getPort():
33 return config.get('Server', 'Port')
35 def get169Setting(tsn):
36 if not tsn:
37 return True
39 if config.has_section('_tivo_' + tsn):
40 if config.has_option('_tivo_' + tsn, 'aspect169'):
41 try:
42 return config.getboolean('_tivo_' + tsn, 'aspect169')
43 except ValueError:
44 pass
46 if tsn[:3] in BLACKLIST_169:
47 return False
49 return True
51 def getShares(tsn=''):
52 shares = [(section, dict(config.items(section)))
53 for section in config.sections()
54 if not(section.startswith('_tivo_') or section == 'Server')]
56 if config.has_section('_tivo_' + tsn):
57 if config.has_option('_tivo_' + tsn, 'shares'):
58 # clean up leading and trailing spaces & make sure ref is valid
59 tsnshares = []
60 for x in config.get('_tivo_' + tsn, 'shares').split(','):
61 y = x.lstrip().rstrip()
62 if config.has_section(y):
63 tsnshares += [(y, dict(config.items(y)))]
64 if tsnshares:
65 shares = tsnshares
67 for name, data in shares:
68 if not data.get('auto_subshares', 'False').lower() == 'true':
69 continue
71 base_path = data['path']
72 for item in os.listdir(base_path):
73 item_path = os.path.join(base_path, item)
74 if not os.path.isdir(item_path):
75 continue
77 new_name = name + '/' + item
78 new_data = dict(data)
79 new_data['path'] = item_path
81 shares.append((new_name, new_data))
83 return shares
85 def getDebug():
86 try:
87 return config.getboolean('Server', 'debug')
88 except NoOptionError, ValueError:
89 return False
91 def getHack83():
92 try:
93 debug = config.get('Server', 'hack83')
94 if debug.lower() == 'true':
95 return True
96 else:
97 return False
98 except NoOptionError:
99 return False
101 def getOptres():
102 try:
103 return config.getboolean('Server', 'optres')
104 except NoOptionError, ValueError:
105 return False
107 def get(section, key):
108 return config.get(section, key)
110 def getFFMPEGTemplate(tsn):
111 if tsn and config.has_section('_tivo_' + tsn):
112 try:
113 return config.get('_tivo_' + tsn, 'ffmpeg_prams', raw=True)
114 except NoOptionError:
115 pass
116 try:
117 return config.get('Server', 'ffmpeg_prams', raw=True)
118 except NoOptionError: #default
119 return '-vcodec mpeg2video -r 29.97 -b %(video_br)s -maxrate %(max_video_br)s -bufsize %(buff_size)s %(aspect_ratio)s -comment pyTivo.py -ab %(audio_br)s %(audio_fr)s %(audio_codec)s -f vob -'
121 def isHDtivo(tsn): # tsn's of High Definition Tivo's
122 return tsn != '' and tsn[:3] in ['648', '652']
124 def getValidWidths():
125 return [1920, 1440, 1280, 720, 704, 544, 480, 352]
127 def getValidHeights():
128 return [1080, 720, 480] # Technically 240 is also supported
130 # Return the number in list that is nearest to x
131 # if two values are equidistant, return the larger
132 def nearest(x, list):
133 return reduce(lambda a, b: closest(x, a, b), list)
135 def closest(x, a, b):
136 if abs(x - a) < abs(x - b) or (abs(x - a) == abs(x - b) and a > b):
137 return a
138 else:
139 return b
141 def nearestTivoHeight(height):
142 return nearest(height, getValidHeights())
144 def nearestTivoWidth(width):
145 return nearest(width, getValidWidths())
147 def getTivoHeight(tsn):
148 if tsn and config.has_section('_tivo_' + tsn):
149 try:
150 height = config.getint('_tivo_' + tsn, 'height')
151 return nearestTivoHeight(height)
152 except NoOptionError:
153 pass
154 try:
155 height = config.getint('Server', 'height')
156 return nearestTivoHeight(height)
157 except NoOptionError: #defaults for S3/S2 TiVo
158 if isHDtivo(tsn):
159 return 720
160 else:
161 return 480
163 def getTivoWidth(tsn):
164 if tsn and config.has_section('_tivo_' + tsn):
165 try:
166 width = config.getint('_tivo_' + tsn, 'width')
167 return nearestTivoWidth(width)
168 except NoOptionError:
169 pass
170 try:
171 width = config.getint('Server', 'width')
172 return nearestTivoWidth(width)
173 except NoOptionError: #defaults for S3/S2 TiVo
174 if isHDtivo(tsn):
175 return 1280
176 else:
177 return 544
179 def getAudioBR(tsn = None):
180 #convert to non-zero multiple of 64 to ensure ffmpeg compatibility
181 #compare audio_br to max_audio_br and return lowest
182 if tsn and config.has_section('_tivo_' + tsn):
183 try:
184 audiobr = int(max(int(strtod(config.get('_tivo_' + tsn, 'audio_br'))/1000), 64)/64)*64
185 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
186 except NoOptionError:
187 pass
188 try:
189 audiobr = int(max(int(strtod(config.get('Server', 'audio_br'))/1000), 64)/64)*64
190 return str(min(audiobr, getMaxAudioBR(tsn))) + 'k'
191 except NoOptionError: #defaults for S3/S2 TiVo
192 if isHDtivo(tsn):
193 return '384k'
194 else:
195 return '192k'
197 def getVideoBR(tsn = None):
198 if tsn and config.has_section('_tivo_' + tsn):
199 try:
200 return config.get('_tivo_' + tsn, 'video_br')
201 except NoOptionError:
202 pass
203 try:
204 return config.get('Server', 'video_br')
205 except NoOptionError: #defaults for S3/S2 TiVo
206 if isHDtivo(tsn):
207 return '8192k'
208 else:
209 return '4096K'
211 def getMaxVideoBR():
212 try:
213 return str(int(strtod(config.get('Server', 'max_video_br'))/1000)) + 'k'
214 except NoOptionError: #default to 17Mi
215 return '17408k'
217 def getBuffSize():
218 try:
219 return config.get('Server', 'bufsize')
220 except NoOptionError: #default 1024k
221 return '1024k'
223 def getMaxAudioBR(tsn = None):
224 #convert to non-zero multiple of 64 for ffmpeg compatibility
225 if tsn and config.has_section('_tivo_' + tsn):
226 try:
227 return int(int(strtod(config.get('_tivo_' + tsn, 'max_audio_br'))/1000)/64)*64
228 except NoOptionError:
229 pass
230 try:
231 return int(int(strtod(config.get('Server', 'max_audio_br'))/1000)/64)*64
232 except NoOptionError:
233 return int(448) #default to 448
235 # Parse a bitrate using the SI/IEEE suffix values as if by ffmpeg
236 # For example, 2K==2000, 2Ki==2048, 2MB==16000000, 2MiB==16777216
237 # Algorithm: http://svn.mplayerhq.hu/ffmpeg/trunk/libavcodec/eval.c
238 def strtod(value):
239 prefixes = {'y': -24, 'z': -21, 'a': -18, 'f': -15, 'p': -12,
240 'n': -9, 'u': -6, 'm': -3, 'c': -2, 'd': -1,
241 'h': 2, 'k': 3, 'K': 3, 'M': 6, 'G': 9,
242 'T': 12, 'P': 15, 'E': 18, 'Z': 21, 'Y': 24}
243 p = re.compile(r'^(\d+)(?:([yzafpnumcdhkKMGTPEZY])(i)?)?([Bb])?$')
244 m = p.match(value)
245 if m is None:
246 raise SyntaxError('Invalid bit value syntax')
247 (coef, prefix, power, byte) = m.groups()
248 if prefix is None:
249 value = float(coef)
250 else:
251 exponent = float(prefixes[prefix])
252 if power == 'i':
253 # Use powers of 2
254 value = float(coef) * pow(2.0, exponent / 0.3)
255 else:
256 # Use powers of 10
257 value = float(coef) * pow(10.0, exponent)
258 if byte == 'B': # B == Byte, b == bit
259 value *= 8;
260 return value