-
Notifications
You must be signed in to change notification settings - Fork 0
/
coherence.py
373 lines (307 loc) · 11.2 KB
/
coherence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#! /usr/bin/python
#
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
import coherence
# Copyright 2006,2007,2008 Frank Scholz <coherence@beebits.net>
""" Coherence is a framework to host DLNA/UPnP devices
For more information about it and its available backends
point your browser to: http://coherence-project.org
"""
import os, sys
import string
from coherence import __version__
from coherence.extern.simple_config import Config,ConfigItem
from twisted.python import usage, text
"""
thankfully taken from twisted.scripts._twistd_unix.py
"""
def daemonize():
return
# See http://www.erlenstar.demon.co.uk/unix/faq_toc.html#TOC16
# if os.fork(): # launch child and...
# os._exit(0) # kill off parent
# os.setsid()
# if os.fork(): # launch child and...
# os._exit(0) # kill off parent again.
# os.umask(077)
# null=os.open('/dev/null', os.O_RDWR)
# for i in range(3):
# try:
# os.dup2(null, i)
# except OSError, e:
# if e.errno != errno.EBADF:
# raise
# os.close(null)
"""
taken with minor adjustments from twisted.python.text.py
"""
def greedyWrap(inString, width=80):
"""Given a string and a column width, return a list of lines.
Caveat: I'm use a stupid greedy word-wrapping
algorythm. I won't put two spaces at the end
of a sentence. I don't do full justification.
And no, I've never even *heard* of hypenation.
"""
outLines = []
#eww, evil hacks to allow paragraphs delimited by two \ns :(
if inString.find('\n\n') >= 0:
paragraphs = inString.split('\n\n')
for para in paragraphs:
outLines.extend(greedyWrap(para, width) + [''])
return outLines
inWords = inString.split()
column = 0
ptr_line = 0
while inWords:
column = column + len(inWords[ptr_line])
ptr_line = ptr_line + 1
if (column > width):
if ptr_line == 1:
# This single word is too long, it will be the whole line.
pass
else:
# We've gone too far, stop the line one word back.
ptr_line = ptr_line - 1
(l, inWords) = (inWords[0:ptr_line], inWords[ptr_line:])
outLines.append(string.join(l,' '))
ptr_line = 0
column = 0
elif not (len(inWords) > ptr_line):
# Clean up the last bit.
outLines.append(' '.join(inWords))
del inWords[:]
else:
# Space
column = column + 1
# next word
return outLines
"""
taken with minor adjustments from twisted.python.usage.py
"""
def docMakeChunks(optList, width=80):
"""
Makes doc chunks for option declarations.
Takes a list of dictionaries, each of which may have one or more
of the keys 'long', 'short', 'doc', 'default', 'optType'.
Returns a list of strings.
The strings may be multiple lines,
all of them end with a newline.
"""
# XXX: sanity check to make sure we have a sane combination of keys.
maxOptLen = 0
for opt in optList:
optLen = len(opt.get('long', ''))
if optLen:
if opt.get('optType', None) == "parameter":
# these take up an extra character
optLen = optLen + 1
maxOptLen = max(optLen, maxOptLen)
colWidth1 = maxOptLen + len(" -s, -- ")
colWidth2 = width - colWidth1
# XXX - impose some sane minimum limit.
# Then if we don't have enough room for the option and the doc
# to share one line, they can take turns on alternating lines.
colFiller1 = " " * colWidth1
optChunks = []
seen = {}
for opt in optList:
if opt.get('short', None) in seen or opt.get('long', None) in seen:
continue
for x in opt.get('short', None), opt.get('long', None):
if x is not None:
seen[x] = 1
optLines = []
comma = " "
if opt.get('short', None):
short = "-%c" % (opt['short'],)
else:
short = ''
if opt.get('long', None):
long = opt['long']
if opt.get("optType", None) == "parameter":
long = long + '='
long = "%-*s" % (maxOptLen, long)
if short:
comma = ","
else:
long = " " * (maxOptLen + len('--'))
if opt.get('optType', None) == 'command':
column1 = ' %s ' % long
else:
column1 = " %2s%c --%s " % (short, comma, long)
if opt.get('doc', ''):
doc = opt['doc'].strip()
else:
doc = ''
if (opt.get("optType", None) == "parameter") \
and not (opt.get('default', None) is None):
doc = "%s [default: %s]" % (doc, opt['default'])
if (opt.get("optType", None) == "parameter") \
and opt.get('dispatch', None) is not None:
d = opt['dispatch']
if isinstance(d, usage.CoerceParameter) and d.doc:
doc = "%s. %s" % (doc, d.doc)
if doc:
column2_l = greedyWrap(doc, colWidth2)
else:
column2_l = ['']
optLines.append("%s%s\n" % (column1, column2_l.pop(0)))
for line in column2_l:
optLines.append("%s%s\n" % (colFiller1, line))
optChunks.append(''.join(optLines))
return optChunks
usage.docMakeChunks = docMakeChunks
def setConfigFile():
def findConfigDir():
try:
configDir = os.path.expanduser('~')
except:
configDir = os.getcwd()
return configDir
return os.path.join( findConfigDir(), '.coherence')
class Options(usage.Options):
optFlags = [['daemon','d', 'daemonize'],
['noconfig', None, 'ignore any configfile found'],
['version','v', 'print out version']
]
optParameters = [['configfile', 'c', setConfigFile(), 'configfile'],
['logfile', 'l', None, 'logfile'],
['option', 'o', None, 'activate option'],
['plugin', 'p', None, 'activate plugin'],
]
def __init__(self):
usage.Options.__init__(self)
self['plugins'] = []
self['options'] = {}
def opt_version(self):
print "Coherence version:", __version__
sys.exit(0)
def opt_help(self):
sys.argv.remove('--help')
from coherence.base import Plugins
p = Plugins()
for opt,doc in self.docs.items():
if opt == 'plugin':
self.docs[opt] = doc + '\n\nExample: --plugin=backend:FSStore,name:MyCoherence\n\nAvailable backends are:\n\n'
self.docs[opt] += ', '.join(p.keys())
print self.__str__()
sys.exit(0)
def opt_plugin(self,option):
self['plugins'].append(option)
def opt_option(self,option):
try:
key,value = option.split(':')
self['options'][key] = value
except:
pass
def main(config):
from coherence.base import Coherence
c = Coherence(config)
#c = Coherence(plugins={'FSStore': {'content_directory':'tests/content'},
# 'Player': {})
#c.add_plugin('FSStore', content_directory='tests/content', version=1)
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, errortext:
print '%s: %s' % (sys.argv[0], errortext)
print '%s: Try --help for usage details.' % (sys.argv[0])
sys.exit(0)
try:
if options['daemon'] == 1:
daemonize()
except:
print traceback.format_exc()
config = {}
config['logging'] = {'level': 'info'}
if options['noconfig'] != 1:
try:
config = Config(options['configfile'],root='config',element2attr_mappings={'active':'active'}).config
except SyntaxError:
import traceback
#print traceback.format_exc()
try:
from configobj import ConfigObj
config = ConfigObj(options['configfile'])
except:
print "hmm, seems we are in trouble reading in any sort of config file"
print traceback.format_exc()
except IOError:
print "no config file %r found" % options['configfile']
pass
if options['logfile'] != None:
if isinstance(config,(ConfigItem,dict)):
if 'logging' not in config:
config['logging'] = {}
config['logging']['logfile'] = options['logfile']
else:
config['logfile'] = options['logfile']
for k,v in options['options'].items():
if k == 'logfile':
continue
config[k] = v
if options['daemon'] == 1:
if isinstance(config,(ConfigItem,dict)):
if config.get('logging',None) == None:
config['logging'] = {}
if config['logging'].get('logfile',None) == None:
config['logging']['level'] = 'debug'
try:
del config['logging']['logfile']
except KeyError:
pass
else:
if config.get('logfile',None) == None:
config.set('logmode','none')
try:
del config['logfile']
except KeyError:
pass
use_qt = config.get('qt', 'no') == 'yes'
if(config.get('use_dbus', 'no') == 'yes' or
config.get('glib', 'no') == 'yes' or
use_qt or
config.get('transcoding', 'no') == 'yes'):
if use_qt:
pass
#from coherence.extern import qt4reactor
#qt4reactor.install()
else:
try:
from twisted.internet import glib2reactor
glib2reactor.install()
except AssertionError:
print "error installing glib2reactor"
if len(options['plugins']) > 0:
plugins = config.get('plugin')
if isinstance(plugins,dict):
config['plugin']=[plugins]
if plugins is None:
plugins = config.get('plugins',None)
if plugins == None:
config['plugin'] = []
plugins = config['plugin']
while len(options['plugins']) > 0:
p = options['plugins'].pop()
plugin = {}
plugin_conf = p.split(',')
for pair in plugin_conf:
pair = pair.split(':',1)
if len(pair) == 2:
pair[0] = pair[0].strip()
if pair[0] in plugin:
if not isinstance(plugin[pair[0]],list):
new_list = [plugin[pair[0]]]
plugin[pair[0]] = new_list
plugin[pair[0]].append(pair[1])
else:
plugin[pair[0]] = pair[1]
try:
plugins.append(plugin)
except AttributeError:
print "mixing commandline plugins and configfile does not work with the old config file format"
from twisted.internet import reactor
reactor.callWhenRunning(main, config)
reactor.run()