6 from threading
import Timer
7 from urllib
import quote
12 from plugin
import GetPlugin
14 SHARE_TEMPLATE
= '/TiVoConnect?Command=QueryContainer&Container=%s'
15 PLATFORM_MAIN
= 'pyTivo'
16 PLATFORM_VIDEO
= 'pc/pyTivo' # For the nice icon
19 def __init__(self
, names
):
22 def removeService(self
, server
, type, name
):
23 self
.names
.remove(name
.replace('.' + type, ''))
25 def addService(self
, server
, type, name
):
26 self
.names
.append(name
.replace('.' + type, ''))
29 def __init__(self
, logger
):
30 """ Announce our shares via Zeroconf. """
34 self
.rz
= Zeroconf
.Zeroconf()
36 old_titles
= self
.scan()
37 address
= socket
.inet_aton(config
.get_ip())
38 port
= int(config
.getPort())
39 logger
.info('Announcing shares...')
40 for section
, settings
in config
.getShares():
42 ct
= GetPlugin(settings
['type']).CONTENT_TYPE
45 if ct
.startswith('x-container/'):
47 platform
= PLATFORM_VIDEO
49 platform
= PLATFORM_MAIN
50 logger
.info('Registering: %s' % section
)
51 self
.share_names
.append(section
)
52 desc
= {'path': SHARE_TEMPLATE
% quote(section
),
53 'platform': platform
, 'protocol': 'http'}
57 while title
in old_titles
:
59 title
= '%s [%d]' % (section
, count
)
60 self
.renamed
[section
] = title
61 info
= Zeroconf
.ServiceInfo('_%s._tcp.local.' % tt
,
62 '%s._%s._tcp.local.' % (title
, tt
),
63 address
, port
, 0, 0, desc
)
64 self
.rz
.registerService(info
)
65 self
.share_info
.append(info
)
68 """ Look for TiVos using Zeroconf. """
69 VIDS
= '_tivo-videos._tcp.local.'
72 self
.logger
.info('Scanning for TiVos...')
74 # Get the names of servers offering TiVo videos
75 browser
= Zeroconf
.ServiceBrowser(self
.rz
, VIDS
, ZCListener(names
))
77 # Give them a second to respond
82 config
.tivos_found
= True
84 # Now get the addresses -- this is the slow part
86 info
= self
.rz
.getServiceInfo(VIDS
, name
+ '.' + VIDS
)
87 if info
and 'TSN' in info
.properties
:
88 tsn
= info
.properties
['TSN']
89 address
= socket
.inet_ntoa(info
.getAddress())
91 config
.tivos
[tsn
] = {'name': name
, 'address': address
,
93 config
.tivos
[tsn
].update(info
.properties
)
94 self
.logger
.info(name
)
99 self
.logger
.info('Unregistering: %s' % ' '.join(self
.share_names
))
100 for info
in self
.share_info
:
101 self
.rz
.unregisterService(info
)
106 self
.UDPSock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
107 self
.UDPSock
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_BROADCAST
, 1)
110 self
.platform
= PLATFORM_VIDEO
111 for section
, settings
in config
.getShares():
113 ct
= GetPlugin(settings
['type']).CONTENT_TYPE
116 if ct
in ('x-container/tivo-music', 'x-container/tivo-photos'):
117 self
.platform
= PLATFORM_MAIN
121 logger
= logging
.getLogger('pyTivo.beacon')
123 self
.bd
= ZCBroadcast(logger
)
125 logger
.error('Zeroconf failure')
130 def add_service(self
, service
):
131 self
.services
.append(service
)
134 def format_services(self
):
135 return ';'.join(self
.services
)
137 def format_beacon(self
, conntype
, services
=True):
138 beacon
= ['tivoconnect=1',
139 'method=%s' % conntype
,
140 'identity={%s}' % config
.getGUID(),
141 'machine=%s' % socket
.gethostname(),
142 'platform=%s' % self
.platform
]
145 beacon
.append('services=' + self
.format_services())
147 beacon
.append('services=TiVoMediaServer:0/http')
149 return '\n'.join(beacon
) + '\n'
151 def send_beacon(self
):
152 beacon_ips
= config
.getBeaconAddresses()
153 beacon
= self
.format_beacon('broadcast')
154 for beacon_ip
in beacon_ips
.split():
155 if beacon_ip
!= 'listen':
159 result
= self
.UDPSock
.sendto(packet
, (beacon_ip
, 2190))
162 packet
= packet
[result
:]
168 self
.timer
= Timer(60, self
.start
)
176 def recv_bytes(self
, sock
, length
):
178 while len(block
) < length
:
179 add
= sock
.recv(length
- len(block
))
185 def recv_packet(self
, sock
):
186 length
= struct
.unpack('!I', self
.recv_bytes(sock
, 4))[0]
187 return self
.recv_bytes(sock
, length
)
189 def send_packet(self
, sock
, packet
):
190 sock
.sendall(struct
.pack('!I', len(packet
)) + packet
)
193 """ For the direct-connect, TCP-style beacon """
197 TCPSock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
198 TCPSock
.bind(('', 2190))
202 # Wait for a connection
203 client
, address
= TCPSock
.accept()
205 # Accept (and discard) the client's beacon
206 self
.recv_packet(client
)
209 self
.send_packet(client
, self
.format_beacon('connected'))
213 thread
.start_new_thread(server
, ())
215 def get_name(self
, address
):
216 """ Exchange beacons, and extract the machine name. """
217 our_beacon
= self
.format_beacon('connected', False)
218 machine_name
= re
.compile('machine=(.*)\n').search
221 tsock
= socket
.socket()
222 tsock
.connect((address
, 2190))
223 self
.send_packet(tsock
, our_beacon
)
224 tivo_beacon
= self
.recv_packet(tsock
)
226 name
= machine_name(tivo_beacon
).groups()[0]