7 from threading
import Timer
8 from urllib
import quote
13 from plugin
import GetPlugin
15 SHARE_TEMPLATE
= '/TiVoConnect?Command=QueryContainer&Container=%s'
16 PLATFORM_MAIN
= 'pyTivo'
17 PLATFORM_VIDEO
= 'pc/pyTivo' # For the nice icon
20 def __init__(self
, names
):
23 def removeService(self
, server
, type, name
):
24 self
.names
.remove(name
.replace('.' + type, ''))
26 def addService(self
, server
, type, name
):
27 self
.names
.append(name
.replace('.' + type, ''))
30 def __init__(self
, logger
):
31 """ Announce our shares via Zeroconf. """
35 self
.rz
= Zeroconf
.Zeroconf()
37 old_titles
= self
.scan()
38 address
= socket
.inet_aton(config
.get_ip())
39 port
= int(config
.getPort())
40 logger
.info('Announcing shares...')
41 for section
, settings
in config
.getShares():
43 ct
= GetPlugin(settings
['type']).CONTENT_TYPE
46 if ct
.startswith('x-container/'):
48 platform
= PLATFORM_VIDEO
50 platform
= PLATFORM_MAIN
51 logger
.info('Registering: %s' % section
)
52 self
.share_names
.append(section
)
53 desc
= {'path': SHARE_TEMPLATE
% quote(section
),
54 'platform': platform
, 'protocol': 'http',
55 'tsn': '{%s}' % uuid
.uuid4()}
59 while title
in old_titles
:
61 title
= '%s [%d]' % (section
, count
)
62 self
.renamed
[section
] = title
63 info
= Zeroconf
.ServiceInfo('_%s._tcp.local.' % tt
,
64 '%s._%s._tcp.local.' % (title
, tt
),
65 address
, port
, 0, 0, desc
)
66 self
.rz
.registerService(info
)
67 self
.share_info
.append(info
)
70 """ Look for TiVos using Zeroconf. """
71 VIDS
= '_tivo-videos._tcp.local.'
74 self
.logger
.info('Scanning for TiVos...')
76 # Get the names of servers offering TiVo videos
77 browser
= Zeroconf
.ServiceBrowser(self
.rz
, VIDS
, ZCListener(names
))
79 # Give them a second to respond
84 config
.tivos_found
= True
86 # Now get the addresses -- this is the slow part
88 info
= self
.rz
.getServiceInfo(VIDS
, name
+ '.' + VIDS
)
89 if info
and 'TSN' in info
.properties
:
90 tsn
= info
.properties
['TSN']
91 address
= socket
.inet_ntoa(info
.getAddress())
93 config
.tivos
[tsn
] = {'name': name
, 'address': address
,
95 config
.tivos
[tsn
].update(info
.properties
)
96 self
.logger
.info(name
)
101 self
.logger
.info('Unregistering: %s' % ' '.join(self
.share_names
))
102 for info
in self
.share_info
:
103 self
.rz
.unregisterService(info
)
108 self
.UDPSock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_DGRAM
)
109 self
.UDPSock
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_BROADCAST
, 1)
112 self
.platform
= PLATFORM_VIDEO
113 for section
, settings
in config
.getShares():
115 ct
= GetPlugin(settings
['type']).CONTENT_TYPE
118 if ct
in ('x-container/tivo-music', 'x-container/tivo-photos'):
119 self
.platform
= PLATFORM_MAIN
123 logger
= logging
.getLogger('pyTivo.beacon')
125 self
.bd
= ZCBroadcast(logger
)
127 logger
.error('Zeroconf failure')
132 def add_service(self
, service
):
133 self
.services
.append(service
)
136 def format_services(self
):
137 return ';'.join(self
.services
)
139 def format_beacon(self
, conntype
, services
=True):
140 beacon
= ['tivoconnect=1',
141 'method=%s' % conntype
,
142 'identity={%s}' % config
.getGUID(),
143 'machine=%s' % socket
.gethostname(),
144 'platform=%s' % self
.platform
]
147 beacon
.append('services=' + self
.format_services())
149 beacon
.append('services=TiVoMediaServer:0/http')
151 return '\n'.join(beacon
) + '\n'
153 def send_beacon(self
):
154 beacon_ips
= config
.getBeaconAddresses()
155 beacon
= self
.format_beacon('broadcast')
156 for beacon_ip
in beacon_ips
.split():
157 if beacon_ip
!= 'listen':
161 result
= self
.UDPSock
.sendto(packet
, (beacon_ip
, 2190))
164 packet
= packet
[result
:]
170 self
.timer
= Timer(60, self
.start
)
178 def recv_bytes(self
, sock
, length
):
180 while len(block
) < length
:
181 add
= sock
.recv(length
- len(block
))
187 def recv_packet(self
, sock
):
188 length
= struct
.unpack('!I', self
.recv_bytes(sock
, 4))[0]
189 return self
.recv_bytes(sock
, length
)
191 def send_packet(self
, sock
, packet
):
192 sock
.sendall(struct
.pack('!I', len(packet
)) + packet
)
195 """ For the direct-connect, TCP-style beacon """
199 TCPSock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
200 TCPSock
.bind(('', 2190))
204 # Wait for a connection
205 client
, address
= TCPSock
.accept()
207 # Accept (and discard) the client's beacon
208 self
.recv_packet(client
)
211 self
.send_packet(client
, self
.format_beacon('connected'))
215 thread
.start_new_thread(server
, ())
217 def get_name(self
, address
):
218 """ Exchange beacons, and extract the machine name. """
219 our_beacon
= self
.format_beacon('connected', False)
220 machine_name
= re
.compile('machine=(.*)\n').search
223 tsock
= socket
.socket()
224 tsock
.connect((address
, 2190))
225 self
.send_packet(tsock
, our_beacon
)
226 tivo_beacon
= self
.recv_packet(tsock
)
228 name
= machine_name(tivo_beacon
).groups()[0]