mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 02:13:41 +08:00
MDNS: Add to Comma Menu and Galaxy
This commit is contained in:
@@ -75,8 +75,9 @@ class LocalAccess:
|
||||
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, AttributeError):
|
||||
reason = 'The comma could not read its network addresses. Check its Network settings and refresh.'
|
||||
addresses = []
|
||||
from openpilot.starpilot.galaxy.mdns import published_url
|
||||
self.cached = {'available': bool(addresses), 'addresses': addresses,
|
||||
'reason': '' if addresses else reason}
|
||||
'reason': '' if addresses else reason, 'name': published_url(self.port) or ''}
|
||||
self.expiry = self.clock() + 5.0
|
||||
return self.cached
|
||||
|
||||
|
||||
@@ -38,12 +38,21 @@ PUBLISH_NO_REVERSE = 16
|
||||
ESTABLISHED = 2
|
||||
|
||||
_published = None
|
||||
_redirected = False
|
||||
|
||||
|
||||
def published_record():
|
||||
return _published
|
||||
|
||||
|
||||
def published_url(port):
|
||||
"""Our published name as a link; port-less only while port 80 redirects to Galaxy."""
|
||||
published = _published
|
||||
if published is None:
|
||||
return None
|
||||
return f'http://{published[0]}/' if _redirected else f'http://{published[0]}:{port}/'
|
||||
|
||||
|
||||
def _ifaddr(sock, name):
|
||||
return socket.inet_ntoa(fcntl.ioctl(sock.fileno(), SIOCGIFADDR, struct.pack('256s', name.encode()))[20:24])
|
||||
|
||||
@@ -93,6 +102,7 @@ class Redirect:
|
||||
return self.run(['sudo', '-n', self.firewall, '-w', '2', '-t', 'nat', *args], capture_output=True, timeout=5, check=check)
|
||||
|
||||
def sync(self, addresses):
|
||||
global _redirected
|
||||
wanted = tuple(sorted(a for a in addresses if lan_address(a)))
|
||||
if self.firewall is None or wanted == self.applied:
|
||||
return
|
||||
@@ -106,12 +116,14 @@ class Redirect:
|
||||
self.ipt('-F', CHAIN)
|
||||
for address in wanted:
|
||||
self.ipt('-A', CHAIN, '-d', address, '-p', 'tcp', '-j', 'REDIRECT', '--to-ports', str(self.port))
|
||||
self.applied = wanted
|
||||
self.applied, _redirected = wanted, True
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
self.applied = wanted # retried on the next address change, not every poll
|
||||
self.applied, _redirected = wanted, False # retried on the next address change, not every poll
|
||||
_log(f'port 80 redirect failed ({error}); http://galaxy.local needs :{self.port}')
|
||||
|
||||
def close(self):
|
||||
global _redirected
|
||||
_redirected = False
|
||||
if not self.ready:
|
||||
return
|
||||
try:
|
||||
@@ -194,9 +206,12 @@ class Avahi:
|
||||
def state(self, group):
|
||||
return self.first(group, ENTRY_GROUP, 'GetState', int)
|
||||
|
||||
def claim(self, name, entries, timeout=ESTABLISH_S):
|
||||
"""The committed group once avahi has probed the name, or None if another device holds it."""
|
||||
group = self.first('/', SERVER, 'EntryGroupNew', str)
|
||||
def claim(self, name, entries, timeout=ESTABLISH_S, group=None):
|
||||
"""The committed group once avahi has probed the name, or None if another device holds it; group updates ours in place."""
|
||||
if group is None:
|
||||
group = self.first('/', SERVER, 'EntryGroupNew', str)
|
||||
else:
|
||||
self.call(group, ENTRY_GROUP, 'Reset')
|
||||
try:
|
||||
for number, protocol, address in entries:
|
||||
self.call(group, ENTRY_GROUP, 'AddAddress', 'iiuss', (number, protocol, PUBLISH_NO_REVERSE, name, address))
|
||||
@@ -259,8 +274,8 @@ def held_elsewhere(name, own, run=subprocess.run):
|
||||
return len(fields) == 2 and fields[0] == name and fields[1] not in own
|
||||
|
||||
|
||||
def _claim(avahi, entries, remembered, stop, taken=held_elsewhere):
|
||||
own = {address for _, _, address in entries}
|
||||
def _claim(avahi, entries, remembered, stop, taken=held_elsewhere, ours=frozenset()):
|
||||
own = {address for _, _, address in entries} | set(ours) # our earlier addresses can linger in avahi's answers
|
||||
for name in candidates(remembered):
|
||||
if stop.is_set():
|
||||
break
|
||||
@@ -283,7 +298,7 @@ def publish(stop, *, avahi=None, addresses=interface_addresses, ipv6=link_local,
|
||||
global _published
|
||||
avahi = avahi if avahi is not None else Avahi(stopped=stop.is_set)
|
||||
group, entries, retry_at, failure = None, (), 0.0, None
|
||||
remembered = load_name(name_file)
|
||||
remembered, ours = load_name(name_file), set()
|
||||
|
||||
def failed(message):
|
||||
nonlocal failure
|
||||
@@ -306,13 +321,21 @@ def publish(stop, *, avahi=None, addresses=interface_addresses, ipv6=link_local,
|
||||
if lost and _published is not None:
|
||||
_log(f'lost {_published[0]}; reclaiming')
|
||||
if wanted != entries or lost or (group is None and wanted and time.monotonic() >= retry_at):
|
||||
if group is not None:
|
||||
avahi.free(group)
|
||||
group, _published, entries = None, None, wanted
|
||||
if wanted:
|
||||
name = None
|
||||
held = _published[0] if _published is not None and group is not None and not lost and wanted else None
|
||||
if held is not None:
|
||||
try:
|
||||
name, group = _claim(avahi, wanted, remembered, stop, taken)
|
||||
group = avahi.claim(held, wanted, group=group)
|
||||
except (OSError, AvahiError):
|
||||
group = None
|
||||
if group is not None and held is None:
|
||||
avahi.free(group)
|
||||
group = None
|
||||
_published, entries = None, wanted
|
||||
if wanted:
|
||||
name = held if group is not None else None
|
||||
try:
|
||||
if name is None:
|
||||
name, group = _claim(avahi, wanted, remembered, stop, taken, ours)
|
||||
except (OSError, AvahiError) as error:
|
||||
failed(f'avahi unavailable ({error})')
|
||||
else:
|
||||
@@ -322,6 +345,7 @@ def publish(stop, *, avahi=None, addresses=interface_addresses, ipv6=link_local,
|
||||
retry_at = time.monotonic() + retry
|
||||
else:
|
||||
failure = None
|
||||
ours.update(address for _, _, address in wanted)
|
||||
_published = (name, tuple(address for _, protocol, address in wanted if protocol == PROTO_INET))
|
||||
interfaces = ', '.join(n for n in INTERFACES if found.get(n) in _published[1])
|
||||
_log(f'published {name} on {interfaces}', warning=False)
|
||||
|
||||
@@ -10,6 +10,12 @@ assert.equal(validLocalAccess({ available: false, addresses: [], reason: 'No act
|
||||
assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'javascript:alert(1)' }] }), false)
|
||||
assert.equal(validLocalAccess({ ...snapshot, addresses: [{ ...snapshot.addresses[0], url: 'http://password@example.com' }] }), false)
|
||||
assert.equal(validLocalAccess({ ...snapshot, available: false }), false)
|
||||
assert.equal(validLocalAccess({ ...snapshot, name: 'http://galaxy-2.local/' }), true)
|
||||
assert.equal(validLocalAccess({ ...snapshot, name: 'http://galaxy.local:8082/' }), true)
|
||||
assert.equal(validLocalAccess({ ...snapshot, name: '' }), true)
|
||||
assert.equal(validLocalAccess({ ...snapshot, name: 'javascript:alert(1)' }), false)
|
||||
assert.equal(validLocalAccess({ ...snapshot, name: 'http://evil.example/' }), false)
|
||||
assert.equal(validLocalAccess({ ...snapshot, name: { toString: () => 'http://galaxy.local/' } }), false)
|
||||
const updates = [], requests = [], timers = []
|
||||
let auth = 0
|
||||
const feed = new LocalAccessFeed({ publish: value => updates.push(value), onUnauthorized: () => auth++,
|
||||
|
||||
@@ -32,16 +32,22 @@ class FakeAvahi:
|
||||
"""Names other devices hold collide; dropped groups read as not established."""
|
||||
|
||||
def __init__(self, taken=(), down=0):
|
||||
self.taken, self.down, self.visible = set(taken), down, set()
|
||||
self.claims, self.groups, self.freed, self.closed = [], {}, [], 0
|
||||
self.taken: set[str] = set(taken)
|
||||
self.down, self.visible = down, set()
|
||||
self.claims, self.groups, self.freed, self.updates, self.closed = [], {}, [], [], 0
|
||||
|
||||
def claim(self, name, entries):
|
||||
def claim(self, name, entries, group=None):
|
||||
if self.down:
|
||||
self.down -= 1
|
||||
raise ConnectionRefusedError(111, 'avahi down')
|
||||
self.claims.append((name, entries))
|
||||
if name in self.taken:
|
||||
if group is not None:
|
||||
self.free(group)
|
||||
return None
|
||||
if group is not None:
|
||||
self.updates.append(group)
|
||||
return group
|
||||
group = f'/group/{len(self.claims)}'
|
||||
self.groups[group] = mdns.ESTABLISHED
|
||||
return group
|
||||
@@ -89,6 +95,10 @@ class MdnsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.name_file = Path(self.tmp.name) / 'mdns_name'
|
||||
for name, value in (('_published', None), ('_redirected', False)): # module state the publisher and Redirect share
|
||||
patcher = patch.object(mdns, name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
@@ -162,7 +172,49 @@ class MdnsTest(unittest.TestCase):
|
||||
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}, {'wlan0': '192.168.1.5', 'galaxy0': '172.31.254.1'}])
|
||||
self.assertEqual(avahi.claims, [('galaxy.local', ((12, 0, '192.168.1.5'),)),
|
||||
('galaxy.local', ((12, 0, '192.168.1.5'), (29, 0, '172.31.254.1')))])
|
||||
self.assertEqual(avahi.freed[0], '/group/1')
|
||||
self.assertEqual(avahi.updates, ['/group/1'], 'the established group is republished in place')
|
||||
|
||||
def test_network_switch_keeps_the_name_even_if_our_old_address_still_answers(self):
|
||||
avahi = FakeAvahi()
|
||||
asked = []
|
||||
|
||||
def stale_answer(name, own):
|
||||
asked.append(name)
|
||||
return name == 'galaxy.local' and '10.10.99.177' not in own # avahi still returns our old work address
|
||||
|
||||
stop, steps = threading.Event(), iter([{'wlan0': '10.10.99.177'}, {'wlan0': '172.20.10.4'}])
|
||||
|
||||
def addresses():
|
||||
try:
|
||||
return next(steps)
|
||||
except StopIteration:
|
||||
stop.set()
|
||||
return {}
|
||||
|
||||
mdns.publish(stop, avahi=avahi, addresses=addresses, ipv6=lambda name: None, index=index, taken=stale_answer,
|
||||
name_file=self.name_file, refresh=0, retry=0)
|
||||
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy.local'])
|
||||
self.assertEqual(asked, ['galaxy.local'], 'an in-place update never re-checks a name we hold')
|
||||
self.assertEqual(mdns.load_name(self.name_file), 'galaxy.local')
|
||||
|
||||
def test_our_earlier_addresses_never_count_as_another_device(self):
|
||||
run = Mock(return_value=SimpleNamespace(stdout='galaxy.local\t10.10.99.177\n'))
|
||||
avahi = FakeAvahi()
|
||||
taken = lambda name, own: mdns.held_elsewhere(name, own, run) # noqa: E731
|
||||
entries = ((12, 0, '172.20.10.4'),)
|
||||
self.assertEqual(mdns._claim(avahi, entries, None, threading.Event(), taken, {'10.10.99.177'})[0], 'galaxy.local')
|
||||
self.assertEqual(mdns._claim(FakeAvahi(), entries, None, threading.Event(), taken)[0], 'galaxy-2.local')
|
||||
|
||||
def test_failed_in_place_update_falls_back_to_a_fresh_claim(self):
|
||||
avahi = FakeAvahi()
|
||||
|
||||
def lose_name_on_update():
|
||||
if len(avahi.claims) == 1:
|
||||
avahi.taken.add('galaxy.local')
|
||||
|
||||
self.run_publish(avahi, [{'wlan0': '192.168.1.5'}, {'wlan0': '192.168.1.9'}], check=lose_name_on_update)
|
||||
# update collides, the fresh claim probes galaxy.local once more, then moves on
|
||||
self.assertEqual(self.names(avahi), ['galaxy.local', 'galaxy.local', 'galaxy.local', 'galaxy-2.local'])
|
||||
|
||||
def test_lost_name_is_reclaimed(self):
|
||||
avahi = FakeAvahi()
|
||||
@@ -260,6 +312,14 @@ class MdnsTest(unittest.TestCase):
|
||||
self.assertEqual(mdns._claim(avahi, ((12, 0, '10.10.99.177'),), None, stop, lambda name, own: False), (None, None))
|
||||
self.assertEqual(avahi.claims, [])
|
||||
|
||||
def test_claim_with_our_group_resets_it_in_place(self):
|
||||
connection = FakeConnection()
|
||||
group = mdns.Avahi(connect=lambda: connection).claim('galaxy.local', ((12, 0, '172.20.10.4'),), group='/Client1/EntryGroup1')
|
||||
self.assertEqual(group, '/Client1/EntryGroup1')
|
||||
self.assertEqual([m for m, _ in connection.calls][:3], ['Reset', 'AddAddress', 'Commit'])
|
||||
self.assertNotIn('EntryGroupNew', [m for m, _ in connection.calls])
|
||||
self.assertNotIn('Free', [m for m, _ in connection.calls])
|
||||
|
||||
def test_avahi_reconnects_after_connection_loss(self):
|
||||
connections = [Mock(send_and_get_reply=Mock(side_effect=ConnectionResetError())), FakeConnection()]
|
||||
avahi = mdns.Avahi(connect=lambda: connections.pop(0))
|
||||
@@ -312,6 +372,21 @@ class MdnsTest(unittest.TestCase):
|
||||
self.assertIsNone(mdns.link_local('eth0', proc))
|
||||
self.assertIsNone(mdns.link_local('wlan0', Path(self.tmp.name) / 'missing'))
|
||||
|
||||
def test_published_url_drops_the_port_only_while_port_80_redirects(self):
|
||||
with patch.object(mdns, '_published', None):
|
||||
self.assertIsNone(mdns.published_url(8082))
|
||||
with patch.object(mdns, '_published', ('galaxy-2.local', ('192.168.1.5',))):
|
||||
run = Mock(return_value=SimpleNamespace(returncode=0))
|
||||
redirect = mdns.Redirect(8082, run=run, which=lambda name: '/usr/sbin/iptables')
|
||||
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
|
||||
redirect.sync(['192.168.1.5'])
|
||||
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local/')
|
||||
redirect.close()
|
||||
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
|
||||
with patch.object(mdns, '_log'):
|
||||
mdns.Redirect(8082, run=Mock(side_effect=OSError('denied')), which=lambda name: '/usr/sbin/iptables').sync(['192.168.1.5'])
|
||||
self.assertEqual(mdns.published_url(8082), 'http://galaxy-2.local:8082/')
|
||||
|
||||
def test_redirect_close_removes_rules_once(self):
|
||||
calls = []
|
||||
redirect = mdns.Redirect(8082, run=lambda cmd, **kw: calls.append(cmd[7:]) or SimpleNamespace(returncode=0),
|
||||
|
||||
@@ -7,6 +7,7 @@ import { GxNotice } from "./notice.js"
|
||||
export function validLocalAccess(value) {
|
||||
if (!value || typeof value.available !== "boolean" || typeof value.reason !== "string" || value.reason.length > 1024 ||
|
||||
!Array.isArray(value.addresses) || value.addresses.length > 32 || value.available !== (value.addresses.length > 0)) return false
|
||||
if (value.name !== undefined && (typeof value.name !== "string" || value.name !== "" && !/^http:\/\/galaxy(-[2-9])?\.local(:\d{1,5})?\/$/.test(value.name))) return false
|
||||
return value.addresses.every(address => {
|
||||
if (!address || !["interface", "label", "url"].every(key => typeof address[key] === "string" && address[key].length > 0 && address[key].length <= 512)) return false
|
||||
try {
|
||||
@@ -106,7 +107,8 @@ export const LocalAccess = {
|
||||
<GxNotice v-if="state.error" tone="danger">{{ state.error }}</GxNotice>
|
||||
<template v-else-if="state.data?.available">
|
||||
<p>Connect your phone to the Galaxy hotspot or the same network as your comma, then open an address below. No Internet or Galaxy password needed.</p>
|
||||
<ul class="gx-stack"><li v-for="address in state.data.addresses" :key="address.interface + address.url"><a :href="address.url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">{{ address.label }} · {{ address.url }}</a></li></ul>
|
||||
<ul class="gx-stack"><li v-if="state.data.name"><a :href="state.data.name" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">This comma · {{ state.data.name }}</a></li><li v-for="address in state.data.addresses" :key="address.interface + address.url"><a :href="address.url" target="_blank" rel="noopener" class="gx-btn gx-btn--tonal gx-wrap">{{ address.label }} · {{ address.url }}</a></li></ul>
|
||||
<p v-if="state.data.name" class="gx-note">The first comma on a network is galaxy.local; the next ones become galaxy-2.local, galaxy-3.local, and so on.</p>
|
||||
<p class="gx-note">Use the full http:// address and bookmark it. Allow local-network access if prompted. Your Firestar Link uses Internet instead.</p>
|
||||
</template>
|
||||
<p v-else-if="state.data" class="gx-note" role="status">{{ state.data.reason || 'The comma has no local network address available.' }}</p>
|
||||
|
||||
@@ -24,6 +24,7 @@ GALAXY_ICON = "icons_mici/settings/galaxy.png"
|
||||
REMOTE_URL = re.compile(r"https://galaxy\.firestar\.link/[A-Za-z0-9]{16}\Z")
|
||||
LOCAL_PORT = 8082
|
||||
LOCAL_ORIGIN = f"http://127.0.0.1:{LOCAL_PORT}"
|
||||
LOCAL_NAME = re.compile(r"http://galaxy(-[2-9])?\.local(:8082)?/\Z")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -33,6 +34,7 @@ class RemoteStatus:
|
||||
available: bool = False
|
||||
legacy: bool = False
|
||||
error: str = ""
|
||||
name: str = ""
|
||||
|
||||
|
||||
def _local_api(path: str, *, cookie: str = "", payload: dict | None = None, deadline: float) -> tuple[int, dict, str]:
|
||||
@@ -89,7 +91,16 @@ def _remote_operation(action: str, password: str = "") -> RemoteStatus:
|
||||
if paired and (type(url) is not str or REMOTE_URL.fullmatch(url) is None):
|
||||
return RemoteStatus(error="Galaxy pairing status is unavailable")
|
||||
return RemoteStatus(paired, url if paired and isinstance(url, str) else "", result.get("tunnelClientAvailable") is True,
|
||||
result.get("legacyPairingAvailable") is True)
|
||||
result.get("legacyPairingAvailable") is True, name=_local_name(cookie, deadline))
|
||||
|
||||
|
||||
def _local_name(cookie: str, deadline: float) -> str:
|
||||
try:
|
||||
code, result, _ = _local_api("/api/local-access", cookie=cookie, deadline=deadline)
|
||||
except (OSError, ValueError, http.client.HTTPException):
|
||||
return ""
|
||||
name = result.get("name") if code == 200 else None
|
||||
return name if type(name) is str and LOCAL_NAME.fullmatch(name) else ""
|
||||
|
||||
|
||||
def connection_url(address: str) -> str | None:
|
||||
@@ -134,9 +145,9 @@ class GalaxyAccessFlow:
|
||||
self._remote_future = None
|
||||
try:
|
||||
updated = future.result()
|
||||
self.remote = replace(self.remote, error=updated.error) if updated.error and self._remote_action == "status" else updated
|
||||
self.remote = replace(self.remote, error=updated.error, name="") if updated.error and self._remote_action == "status" else updated
|
||||
except (OSError, ValueError, RuntimeError, http.client.HTTPException):
|
||||
self.remote = replace(self.remote, error="Local Galaxy is unavailable") if self._remote_action == "status" else \
|
||||
self.remote = replace(self.remote, error="Local Galaxy is unavailable", name="") if self._remote_action == "status" else \
|
||||
RemoteStatus(error="Local Galaxy is unavailable")
|
||||
if self._remote_future is None and time.monotonic() >= self._remote_next_check:
|
||||
self._submit("status")
|
||||
@@ -286,12 +297,17 @@ class GalaxyConnectionView(Widget):
|
||||
message = ("Or open this address on the same network:" if self._url else
|
||||
"Connect to Wi-Fi to show the local address.")
|
||||
rl.draw_text_ex(font, message, rl.Vector2(left, rect.y + 680), 36, 0, rl.LIGHTGRAY)
|
||||
y = rect.y + 745
|
||||
if remote.name:
|
||||
rl.draw_text_ex(font, remote.name, rl.Vector2(left, y), 44, 0, rl.WHITE)
|
||||
y += 60
|
||||
if self._url:
|
||||
rl.draw_text_ex(font, self._url, rl.Vector2(left, rect.y + 745), 44, 0, rl.WHITE)
|
||||
rl.draw_text_ex(font, self._url, rl.Vector2(left, y), 44, 0, rl.WHITE)
|
||||
y += 65
|
||||
if self._qr is not None:
|
||||
rl.draw_texture_pro(self._qr, rl.Rectangle(0, 0, self._qr.width, self._qr.height),
|
||||
rl.Rectangle(rect.x + rect.width - 420, rect.y + 610, 220, 220), rl.Vector2(0, 0), 0, rl.WHITE)
|
||||
rl.draw_text_ex(font, "No password is needed on this network.", rl.Vector2(left, rect.y + 810), 36, 0, rl.LIGHTGRAY)
|
||||
rl.draw_text_ex(font, "No password is needed on this network.", rl.Vector2(left, max(y, rect.y + 810)), 36, 0, rl.LIGHTGRAY)
|
||||
self._close.render(rl.Rectangle(rect.x + rect.width - 430, rect.y + rect.height - 165, 300, 110))
|
||||
|
||||
def __del__(self):
|
||||
@@ -318,6 +334,7 @@ class GalaxyConnectionPage:
|
||||
self._remote_url: str | None = None
|
||||
self._remote_qr = QR("", width=300)
|
||||
self._address = GreyBigButton("local Galaxy • no password", "connect to Wi-Fi")
|
||||
self._name = GreyBigButton("this comma's name", "")
|
||||
self._remote_address = GreyBigButton("remote Galaxy", "checking pairing")
|
||||
self._remote_state = GreyBigButton("remote connection", "")
|
||||
self._pair = BigButton("pair with Galaxy", "1. set a password", gui_app.texture(GALAXY_ICON, 64, 64))
|
||||
@@ -325,7 +342,7 @@ class GalaxyConnectionPage:
|
||||
self._unpair = BigButton("unpair remote Galaxy", "", gui_app.texture(GALAXY_ICON, 64, 64))
|
||||
self._unpair.set_click_callback(self._confirm_unpair)
|
||||
self._scroller.add_widgets([self._pair, self._remote_qr, self._remote_address, self._remote_state,
|
||||
self._unpair, self._qr, self._address])
|
||||
self._unpair, self._name, self._qr, self._address])
|
||||
|
||||
def _submit_password(self, password: str) -> None:
|
||||
flow.pair(password)
|
||||
@@ -358,6 +375,8 @@ class GalaxyConnectionPage:
|
||||
self._set_qr(self._qr, url or "")
|
||||
self._address.set_value(url or "connect to Wi-Fi to show the local address")
|
||||
remote = flow.update_remote()
|
||||
self._name.set_value(remote.name)
|
||||
self._name.set_visible(bool(remote.name))
|
||||
self._remote_url = remote.url
|
||||
self._set_qr(self._remote_qr, remote.url)
|
||||
self._remote_address.set_value(remote.url if remote.paired else "not paired • set a password")
|
||||
|
||||
@@ -7,6 +7,7 @@ from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from openpilot.starpilot.galaxy import mdns
|
||||
from openpilot.starpilot.galaxy.access import AccessStatus, GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.remote import RemotePairing
|
||||
from openpilot.starpilot.galaxy.server import make_server
|
||||
@@ -30,7 +31,10 @@ class TestGalaxyConnection(unittest.TestCase):
|
||||
try:
|
||||
with patch.object(galaxy_access, "LOCAL_PORT", server.server_port), \
|
||||
patch.object(galaxy_access, "LOCAL_ORIGIN", f"http://127.0.0.1:{server.server_port}"):
|
||||
self.assertFalse(galaxy_access._remote_operation("status").paired)
|
||||
with patch.object(mdns, "_published", ("galaxy-2.local", ("127.0.0.1",))), patch.object(mdns, "_redirected", True):
|
||||
status = galaxy_access._remote_operation("status")
|
||||
self.assertFalse(status.paired)
|
||||
self.assertEqual(status.name, "http://galaxy-2.local/")
|
||||
paired = galaxy_access._remote_operation("pair", " password123 ")
|
||||
self.assertTrue(paired.paired)
|
||||
self.assertTrue(galaxy_access.REMOTE_URL.fullmatch(paired.url))
|
||||
@@ -172,11 +176,43 @@ class TestGalaxyConnection(unittest.TestCase):
|
||||
texts = [call.args[1] for call in draw.call_args_list]
|
||||
self.assertIn(url, texts)
|
||||
self.assertIn("No password is needed on this network.", texts)
|
||||
self.assertNotIn("http://galaxy.local/", texts)
|
||||
self.assertLess(texts.index("Choose a password, then pair your comma with Galaxy."), texts.index("Local network"))
|
||||
self.assertEqual((view._close.text, view._pair.text, view._unpair.text),
|
||||
("Close", "Set password & pair", "Unpair remote Galaxy"))
|
||||
self.assertEqual(owner.mock_calls, [])
|
||||
|
||||
def test_large_page_shows_this_commas_name_above_the_address(self):
|
||||
class Button(Widget):
|
||||
def __init__(self, text, callback, **kwargs):
|
||||
super().__init__()
|
||||
|
||||
def _render(self, rect):
|
||||
pass
|
||||
|
||||
flow = GalaxyAccessFlow(Mock(), lambda: True)
|
||||
url = "http://192.168.1.111:8082/#/"
|
||||
with patch("openpilot.system.ui.widgets.button.Button", Button), \
|
||||
patch.object(flow, "_url", return_value=url), \
|
||||
patch.object(flow, "update_remote", return_value=RemoteStatus(name="http://galaxy-2.local/")), \
|
||||
patch("openpilot.starpilot.ui.galaxy_access.make_texture", return_value=None) as qr, \
|
||||
patch("openpilot.starpilot.ui.galaxy_access.gui_app.font"), \
|
||||
patch.object(rl, "draw_rectangle_rec"), patch.object(rl, "draw_text_ex") as draw:
|
||||
view = GalaxyConnectionView(flow)
|
||||
view._update_state()
|
||||
view._render(rl.Rectangle(0, 0, 2160, 1080))
|
||||
qr.assert_called_once_with(url) # the QR stays on the IP, which every phone can open
|
||||
texts = [call.args[1] for call in draw.call_args_list]
|
||||
self.assertLess(texts.index("http://galaxy-2.local/"), texts.index(url))
|
||||
|
||||
def test_local_name_accepts_only_galaxy_names(self):
|
||||
for name, expected in (("http://galaxy.local/", True), ("http://galaxy-9.local:8082/", True), ("http://evil.local/", False),
|
||||
("http://galaxy.local/x", False), ("https://galaxy.local/", False)):
|
||||
with self.subTest(name=name), patch.object(galaxy_access, "_local_api", return_value=(200, {"name": name}, "")):
|
||||
self.assertEqual(galaxy_access._local_name("c", 0), name if expected else "")
|
||||
with patch.object(galaxy_access, "_local_api", side_effect=TimeoutError):
|
||||
self.assertEqual(galaxy_access._local_name("c", 0), "")
|
||||
|
||||
def test_compact_page_has_local_and_remote_views_without_credential_access(self):
|
||||
class Scroller:
|
||||
def __init__(self):
|
||||
@@ -207,10 +243,12 @@ class TestGalaxyConnection(unittest.TestCase):
|
||||
self.assertEqual(button.call_args_list[0].args, ("local Galaxy • no password", "connect to Wi-Fi"))
|
||||
self.assertEqual([call.args for call in button.call_args_list], [
|
||||
("local Galaxy • no password", "connect to Wi-Fi"),
|
||||
("this comma's name", ""),
|
||||
("remote Galaxy", "checking pairing"),
|
||||
("remote connection", "")])
|
||||
self.assertEqual(page._scroller.add_widgets.call_args.args[0],
|
||||
[page._pair, page._remote_qr, page._remote_address, page._remote_state, page._unpair, page._qr, page._address])
|
||||
[page._pair, page._remote_qr, page._remote_address, page._remote_state, page._unpair, page._name, page._qr, page._address])
|
||||
page._name.set_visible.assert_called_with(False)
|
||||
with patch("openpilot.starpilot.ui.galaxy_access.gui_app.push_widget") as pushed:
|
||||
page._enter_password()
|
||||
self.assertIs(prompt.call_args.kwargs["password_mode"], True)
|
||||
|
||||
Reference in New Issue
Block a user