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
= inet_aton(config
.get_ip())
38 port
= int(config
.getPort())
39 logger
.info('Announcing shares...')
40 for section
, settings
in config
.getShares():
41 ct
= GetPlugin(settings
['type']).CONTENT_TYPE
42 if ct
.startswith('x-container/'):
44 platform
= PLATFORM_VIDEO
46 platform
= PLATFORM_MAIN
47 logger
.info('Registering: %s' % section
)
48 self
.share_names
.append(section
)
49 desc
= {'path': SHARE_TEMPLATE
% quote(section
),
50 'platform': platform
, 'protocol': 'http'}
54 while title
in old_titles
:
56 title
= '%s [%d]' % (section
, count
)
57 self
.renamed
[section
] = title
58 info
= Zeroconf
.ServiceInfo('_%s._tcp.local.' % tt
,
59 '%s._%s._tcp.local.' % (title
, tt
),
60 address
, port
, 0, 0, desc
)
61 self
.rz
.registerService(info
)
62 self
.share_info
.append(info
)
65 """ Look for TiVos using Zeroconf. """
66 VIDS
= '_tivo-videos._tcp.local.'
69 self
.logger
.info('Scanning for TiVos...')
71 # Get the names of servers offering TiVo videos
72 browser
= Zeroconf
.ServiceBrowser(self
.rz
, VIDS
, ZCListener(names
))
74 # Give them half a second to respond
77 # Now get the addresses -- this is the slow part
79 info
= self
.rz
.getServiceInfo(VIDS
, name
+ '.' + VIDS
)
80 if info
and 'TSN' in info
.properties
:
81 tsn
= info
.properties
['TSN']
82 address
= inet_ntoa(info
.getAddress())
83 config
.tivos
[tsn
] = address
84 self
.logger
.info(name
)
85 config
.tivo_names
[tsn
] = name
90 self
.logger
.info('Unregistering: %s' % ' '.join(self
.share_names
))
91 for info
in self
.share_info
:
92 self
.rz
.unregisterService(info
)
97 self
.UDPSock
= socket(AF_INET
, SOCK_DGRAM
)
98 self
.UDPSock
.setsockopt(SOL_SOCKET
, SO_BROADCAST
, 1)
101 self
.platform
= PLATFORM_VIDEO
102 for section
, settings
in config
.getShares():
103 ct
= GetPlugin(settings
['type']).CONTENT_TYPE
104 if ct
in ('x-container/tivo-music', 'x-container/tivo-photos'):
105 self
.platform
= PLATFORM_MAIN
109 logger
= logging
.getLogger('pyTivo.beacon')
111 self
.bd
= ZCBroadcast(logger
)
113 logger
.error('Zeroconf failure')
118 def add_service(self
, service
):
119 self
.services
.append(service
)
122 def format_services(self
):
123 return ';'.join(self
.services
)
125 def format_beacon(self
, conntype
, services
=True):
126 beacon
= ['tivoconnect=1',
127 'method=%s' % conntype
,
128 'identity=%s' % config
.getGUID(),
129 'machine=%s' % gethostname(),
130 'platform=%s' % self
.platform
]
133 beacon
.append('services=' + self
.format_services())
135 beacon
.append('services=TiVoMediaServer:0/http')
137 return '\n'.join(beacon
) + '\n'
139 def send_beacon(self
):
140 beacon_ips
= config
.getBeaconAddresses()
141 beacon
= self
.format_beacon('broadcast')
142 for beacon_ip
in beacon_ips
.split():
143 if beacon_ip
!= 'listen':
147 result
= self
.UDPSock
.sendto(packet
, (beacon_ip
, 2190))
150 packet
= packet
[result
:]
156 self
.timer
= Timer(60, self
.start
)
164 def recv_bytes(self
, sock
, length
):
166 while len(block
) < length
:
167 add
= sock
.recv(length
- len(block
))
173 def recv_packet(self
, sock
):
174 length
= struct
.unpack('!I', self
.recv_bytes(sock
, 4))[0]
175 return self
.recv_bytes(sock
, length
)
177 def send_bytes(self
, sock
, block
):
179 sent
= sock
.send(block
)
184 def send_packet(self
, sock
, packet
):
185 self
.send_bytes(sock
, struct
.pack('!I', len(packet
)) + packet
)
188 """ For the direct-connect, TCP-style beacon """
192 TCPSock
= socket(AF_INET
, SOCK_STREAM
)
193 TCPSock
.bind(('', 2190))
197 # Wait for a connection
198 client
, address
= TCPSock
.accept()
200 # Accept (and discard) the client's beacon
201 self
.recv_packet(client
)
204 self
.send_packet(client
, self
.format_beacon('connected'))
208 thread
.start_new_thread(server
, ())
210 def get_name(self
, address
):
211 """ Exchange beacons, and extract the machine name. """
212 our_beacon
= self
.format_beacon('connected', False)
213 machine_name
= re
.compile('machine=(.*)\n').search
217 tsock
.connect((address
, 2190))
218 self
.send_packet(tsock
, our_beacon
)
219 tivo_beacon
= self
.recv_packet(tsock
)
221 name
= machine_name(tivo_beacon
).groups()[0]