Other code tidy ups and alignment with wmcbrine's fork
[pyTivo/wmcbrine/lucasnz.git] / beacon.py
blobdbcbd31eff1979c4352a48d91cd522fc06a57c51
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'
15 PLATFORM_MAIN = 'pyTivo'
16 PLATFORM_VIDEO = 'pc' # For the nice icon
18 class ZCListener:
19 def __init__(self, names):
20 self.names = names
22 def removeService(self, server, type, name):
23 if name in self.names:
24 self.names.remove(name)
26 def addService(self, server, type, name):
27 self.names.append(name)
29 class ZCBroadcast:
30 def __init__(self, logger):
31 """ Announce our shares via Zeroconf. """
32 self.share_names = []
33 self.share_info = []
34 self.logger = logger
35 self.rz = Zeroconf.Zeroconf()
36 address = inet_aton(config.get_ip())
37 port = int(config.getPort())
38 for section, settings in config.getShares():
39 ct = GetPlugin(settings['type']).CONTENT_TYPE
40 if ct.startswith('x-container/'):
41 if 'video' in ct:
42 platform = PLATFORM_VIDEO
43 else:
44 platform = PLATFORM_MAIN
45 logger.info('Registering: %s' % section)
46 self.share_names.append(section)
47 desc = {'path': SHARE_TEMPLATE % quote(section),
48 'platform': platform, 'protocol': 'http'}
49 tt = ct.split('/')[1]
50 info = Zeroconf.ServiceInfo('_%s._tcp.local.' % tt,
51 '%s._%s._tcp.local.' % (section, tt),
52 address, port, 0, 0, desc)
53 self.rz.registerService(info)
54 self.share_info.append(info)
56 def scan(self):
57 """ Look for TiVos using Zeroconf. """
58 VIDS = '_tivo-videos._tcp.local.'
59 names = []
61 # Get the names of servers offering TiVo videos
62 browser = Zeroconf.ServiceBrowser(self.rz, VIDS, ZCListener(names))
64 # Give them half a second to respond
65 time.sleep(0.5)
67 # Now get the addresses -- this is the slow part
68 for name in names:
69 info = self.rz.getServiceInfo(VIDS, name)
70 if info and 'TSN' in info.properties:
71 tsn = info.properties['TSN']
72 address = inet_ntoa(info.getAddress())
73 config.tivos[tsn] = address
74 name = name.replace('.' + VIDS, '')
75 self.logger.info(name)
76 config.tivo_names[tsn] = name
78 def shutdown(self):
79 self.logger.info('Unregistering: %s' % ' '.join(self.share_names))
80 for info in self.share_info:
81 self.rz.unregisterService(info)
82 self.rz.close()
84 class Beacon:
85 def __init__(self):
86 self.UDPSock = socket(AF_INET, SOCK_DGRAM)
87 self.UDPSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
88 self.services = []
90 if config.get_zc():
91 logger = logging.getLogger('pyTivo.beacon')
92 try:
93 logger.info('Announcing shares...')
94 self.bd = ZCBroadcast(logger)
95 except:
96 logger.error('Zeroconf failure')
97 self.bd = None
98 else:
99 logger.info('Scanning for TiVos...')
100 self.bd.scan()
101 else:
102 self.bd = None
104 def add_service(self, service):
105 self.services.append(service)
106 self.send_beacon()
108 def format_services(self):
109 return ';'.join(self.services)
111 def format_beacon(self, conntype, services=True):
112 beacon = ['tivoconnect=1',
113 'swversion=1',
114 'method=%s' % conntype,
115 'identity=%s' % config.getGUID(),
116 'machine=%s' % gethostname(),
117 'platform=%s' % PLATFORM_MAIN]
119 if services:
120 beacon.append('services=' + self.format_services())
121 else:
122 beacon.append('services=TiVoMediaServer:0/http')
124 return '\n'.join(beacon)
126 def send_beacon(self):
127 beacon_ips = config.getBeaconAddresses()
128 for beacon_ip in beacon_ips.split():
129 if beacon_ip != 'listen':
130 try:
131 self.UDPSock.sendto(self.format_beacon('broadcast'),
132 (beacon_ip, 2190))
133 except error, e:
134 print e
136 def start(self):
137 self.send_beacon()
138 self.timer = Timer(60, self.start)
139 self.timer.start()
141 def stop(self):
142 self.timer.cancel()
143 if self.bd:
144 self.bd.shutdown()
146 def listen(self):
147 """ For the direct-connect, TCP-style beacon """
148 import thread
150 def server():
151 TCPSock = socket(AF_INET, SOCK_STREAM)
152 TCPSock.bind(('', 2190))
153 TCPSock.listen(5)
155 while True:
156 # Wait for a connection
157 client, address = TCPSock.accept()
159 # Accept the client's beacon
160 client_length = struct.unpack('!I', client.recv(4))[0]
161 client_message = client.recv(client_length)
163 # Send ours
164 message = self.format_beacon('connected')
165 client.send(struct.pack('!I', len(message)))
166 client.send(message)
167 client.close()
169 thread.start_new_thread(server, ())
171 def get_name(self, address):
172 """ Exchange beacons, and extract the machine name. """
173 our_beacon = self.format_beacon('connected', False)
174 machine_name = re.compile('machine=(.*)\n').search
176 try:
177 tsock = socket()
178 tsock.connect((address, 2190))
180 tsock.send(struct.pack('!I', len(our_beacon)))
181 tsock.send(our_beacon)
183 length = struct.unpack('!I', tsock.recv(4))[0]
184 tivo_beacon = tsock.recv(length)
186 tsock.close()
188 name = machine_name(tivo_beacon).groups()[0]
189 except:
190 name = address
192 return name