Merge pull request #4 from jpenney/master
[pyTivo/wmcbrine.git] / pyTivo.py
blob30eee67056022f441140f7b4688c55bc4c7c400c
1 #!/usr/bin/env python
3 import logging
4 import os
5 import platform
6 import sys
7 import time
9 if sys.version_info[0] != 2 or sys.version_info[1] < 4:
10 print ('ERROR: pyTivo requires Python >= 2.4, < 3.0.\n')
11 sys.exit(1)
13 import beacon
14 import config
15 import httpserver
16 from plugin import GetPlugin
18 def exceptionLogger(*args):
19 sys.excepthook = sys.__excepthook__
20 logging.getLogger('pyTivo').error('Exception in pyTivo', exc_info=args)
22 def last_date():
23 lasttime = -1
24 path = os.path.dirname(__file__)
25 if not path:
26 path = '.'
27 for root, dirs, files in os.walk(path):
28 for name in files:
29 if name.endswith('.py'):
30 tm = os.stat(os.path.join(root, name)).st_mtime
31 if tm > lasttime:
32 lasttime = tm
34 return time.asctime(time.localtime(lasttime))
36 def setup(in_service=False):
37 config.init(sys.argv[1:])
38 config.init_logging()
39 sys.excepthook = exceptionLogger
41 port = config.getPort()
43 httpd = httpserver.TivoHTTPServer(('', int(port)),
44 httpserver.TivoHTTPHandler)
46 logger = logging.getLogger('pyTivo')
47 logger.info('Last modified: ' + last_date())
48 logger.info('Python: ' + platform.python_version())
49 logger.info('System: ' + platform.platform())
51 for section, settings in config.getShares():
52 httpd.add_container(section, settings)
53 # Precaching of files: does a recursive list of base path
54 if settings.get('precache', 'False').lower() == 'true':
55 plugin = GetPlugin(settings.get('type'))
56 if hasattr(plugin, 'pre_cache'):
57 logger.info('Pre-caching the ' + section + ' share.')
58 pre_cache_filter = getattr(plugin, 'pre_cache')
60 def build_recursive_list(path):
61 try:
62 for f in os.listdir(path):
63 f = os.path.join(path, f)
64 if os.path.isdir(f):
65 build_recursive_list(f)
66 else:
67 pre_cache_filter(f)
68 except:
69 pass
71 build_recursive_list(settings.get('path'))
73 b = beacon.Beacon()
74 b.add_service('TiVoMediaServer:%s/http' % port)
75 b.start()
76 if 'listen' in config.getBeaconAddresses():
77 b.listen()
79 httpd.set_beacon(b)
80 httpd.set_service_status(in_service)
82 logger.info('pyTivo is ready.')
83 return httpd
85 def serve(httpd):
86 try:
87 httpd.serve_forever()
88 except KeyboardInterrupt:
89 pass
91 def mainloop():
92 httpd = setup()
93 serve(httpd)
94 httpd.beacon.stop()
95 return httpd.restart
97 if __name__ == '__main__':
98 while mainloop():
99 time.sleep(5)