mimetype.guess_type() returns a tuple, and it might be (None, None).
[pyTivo/TheBayer.git] / beacon.py
blob2dc9f46cd85c20c674803c929fe786663d8b4880
1 import logging
2 import re
3 import struct
4 import time
5 from socket import *
6 from threading import Timer
7 from urllib import quote
9 import Zeroconf
11 import config
12 from plugin import GetPlugin
14 SHARE_TEMPLATE = '/TiVoConnect?Command=QueryContainer&Container=%s'
16 class ZCListener:
17 def __init__(self, names):
18 self.names = names
20 def removeService(self, server, type, name):
21 if name in self.names:
22 self.names.remove(name)
24 def addService(self, server, type, name):
25 self.names.append(name)
27 class ZCBroadcast:
28 def __init__(self, logger):
29 """ Announce our shares via Zeroconf. """
30 self.share_names = []
31 self.share_info = []
32 self.logger = logger
33 self.rz = Zeroconf.Zeroconf()
34 address = inet_aton(config.get_ip())
35 port = int(config.getPort())
36 for section, settings in config.getShares():
37 ct = GetPlugin(settings['type']).CONTENT_TYPE
38 if ct.startswith('x-container/'):
39 logger.info('Registering: %s' % section)
40 self.share_names.append(section)
41 desc = {'path': SHARE_TEMPLATE % quote(section),
42 'platform': 'pc', 'protocol': 'http'}
43 tt = ct.split('/')[1]
44 info = Zeroconf.ServiceInfo('_%s._tcp.local.' % tt,
45 '%s._%s._tcp.local.' % (section, tt),
46 address, port, 0, 0, desc)
47 self.rz.registerService(info)
48 self.share_info.append(info)
50 def scan(self):
51 """ Look for TiVos using Zeroconf. """
52 VIDS = '_tivo-videos._tcp.local.'
53 names = []
55 # Get the names of servers offering TiVo videos
56 browser = Zeroconf.ServiceBrowser(self.rz, VIDS, ZCListener(names))
58 # Give them half a second to respond
59 time.sleep(0.5)
61 # Now get the addresses -- this is the slow part
62 for name in names:
63 info = self.rz.getServiceInfo(VIDS, name)
64 if info and 'TSN' in info.properties:
65 tsn = info.properties['TSN']
66 address = inet_ntoa(info.getAddress())
67 config.tivos[tsn] = address
68 config.tivo_names[tsn] = name.replace('.' + VIDS, '')
70 def shutdown(self):
71 self.logger.info('Unregistering: %s' % ' '.join(self.share_names))
72 for info in self.share_info:
73 self.rz.unregisterService(info)
74 self.rz.close()
76 class Beacon:
78 UDPSock = socket(AF_INET, SOCK_DGRAM)
79 UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
80 services = []
82 def __init__(self):
83 if config.get_zc():
84 logger = logging.getLogger('pyTivo.beacon')
85 try:
86 logger.info('Announcing shares...')
87 self.bd = ZCBroadcast(logger)
88 except:
89 logger.error('Zeroconf failure')
90 self.bd = None
91 else:
92 logger.info('Scanning for TiVos...')
93 self.bd.scan()
94 else:
95 self.bd = None
97 def add_service(self, service):
98 self.services.append(service)
99 self.send_beacon()
101 def format_services(self):
102 return ';'.join(self.services)
104 def format_beacon(self, conntype, services=True):
105 beacon = ['tivoconnect=1',
106 'swversion=1',
107 'method=%s' % conntype,
108 'identity=%s' % config.getGUID(),
109 'machine=%s' % gethostname(),
110 'platform=pc']
112 if services:
113 beacon.append('services=' + self.format_services())
114 else:
115 beacon.append('services=TiVoMediaServer:0/http')
117 return '\n'.join(beacon)
119 def send_beacon(self):
120 beacon_ips = config.getBeaconAddresses()
121 for beacon_ip in beacon_ips.split():
122 if beacon_ip != 'listen':
123 try:
124 self.UDPSock.sendto(self.format_beacon('broadcast'),
125 (beacon_ip, 2190))
126 except error, e:
127 print e
129 def start(self):
130 self.send_beacon()
131 self.timer = Timer(60, self.start)
132 self.timer.start()
134 def stop(self):
135 self.timer.cancel()
136 if self.bd:
137 self.bd.shutdown()
139 def listen(self):
140 """ For the direct-connect, TCP-style beacon """
141 import thread
143 def server():
144 TCPSock = socket(AF_INET, SOCK_STREAM)
145 TCPSock.bind(('', 2190))
146 TCPSock.listen(5)
148 while True:
149 # Wait for a connection
150 client, address = TCPSock.accept()
152 # Accept the client's beacon
153 client_length = struct.unpack('!I', client.recv(4))[0]
154 client_message = client.recv(client_length)
156 # Send ours
157 message = self.format_beacon('connected')
158 client.send(struct.pack('!I', len(message)))
159 client.send(message)
160 client.close()
162 thread.start_new_thread(server, ())
164 def get_name(self, address):
165 """ Exchange beacons, and extract the machine name. """
166 our_beacon = self.format_beacon('connected', False)
167 machine_name = re.compile('machine=(.*)\n').search
169 try:
170 tsock = socket()
171 tsock.connect((address, 2190))
173 tsock.send(struct.pack('!I', len(our_beacon)))
174 tsock.send(our_beacon)
176 length = struct.unpack('!I', tsock.recv(4))[0]
177 tivo_beacon = tsock.recv(length)
179 tsock.close()
181 name = machine_name(tivo_beacon).groups()[0]
182 except:
183 name = address
185 return name