pyxpo-network 0.1.0a1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyxpo_network-0.1.0a1/LICENSE +21 -0
- pyxpo_network-0.1.0a1/PKG-INFO +77 -0
- pyxpo_network-0.1.0a1/README.md +58 -0
- pyxpo_network-0.1.0a1/pyproject.toml +42 -0
- pyxpo_network-0.1.0a1/pyxpo_network/__init__.py +185 -0
- pyxpo_network-0.1.0a1/pyxpo_network/android/src/main/AndroidManifest.xml +3 -0
- pyxpo_network-0.1.0a1/pyxpo_network/android/src/main/java/dev/pyxpo/modules/network/NetworkModule.kt +100 -0
- pyxpo_network-0.1.0a1/pyxpo_network/ios/NetworkModule.swift +98 -0
- pyxpo_network-0.1.0a1/pyxpo_network/py.typed +0 -0
- pyxpo_network-0.1.0a1/pyxpo_network/pyxpo-module.json +14 -0
- pyxpo_network-0.1.0a1/pyxpo_network.egg-info/PKG-INFO +77 -0
- pyxpo_network-0.1.0a1/pyxpo_network.egg-info/SOURCES.txt +15 -0
- pyxpo_network-0.1.0a1/pyxpo_network.egg-info/dependency_links.txt +1 -0
- pyxpo_network-0.1.0a1/pyxpo_network.egg-info/entry_points.txt +2 -0
- pyxpo_network-0.1.0a1/pyxpo_network.egg-info/requires.txt +1 -0
- pyxpo_network-0.1.0a1/pyxpo_network.egg-info/top_level.txt +1 -0
- pyxpo_network-0.1.0a1/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vishal Chaubey
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyxpo-network
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Network state, IP address and connectivity changes: the expo-network API for pyxpo.
|
|
5
|
+
Author: Vishal Chaubey
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/pyxpo/pyxpo/tree/main/packages/network
|
|
8
|
+
Project-URL: Issues, https://github.com/pyxpo/pyxpo/issues
|
|
9
|
+
Keywords: pyxpo,pyxpo-module,mobile,android,ios
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: pyxpo<0.2,>=0.1.0a2
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# pyxpo-network
|
|
21
|
+
|
|
22
|
+
Network state, IP address and connectivity changes for [pyxpo](https://github.com/pyxpo/pyxpo) apps. The
|
|
23
|
+
API follows [expo-network](https://docs.expo.dev/versions/latest/sdk/network/).
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install pyxpo-network
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```toml
|
|
30
|
+
[tool.pyxpo]
|
|
31
|
+
modules = ["network"]
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import pyxpo_network as Network
|
|
36
|
+
|
|
37
|
+
state = await Network.get_network_state_async()
|
|
38
|
+
print(state.type, state.is_connected, state.is_internet_reachable) # NetworkStateType.WIFI True True
|
|
39
|
+
print(await Network.get_ip_address_async()) # 192.168.1.20
|
|
40
|
+
|
|
41
|
+
sub = Network.add_network_state_listener(lambda s: print("now", s.type))
|
|
42
|
+
sub.remove()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def OfflineBanner():
|
|
46
|
+
state = Network.use_network_state() # re-renders on every change
|
|
47
|
+
if state.is_connected is False:
|
|
48
|
+
return Text("You are offline")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Every name also has its expo-network spelling (`Network.getNetworkStateAsync`, `Network.useNetworkState`).
|
|
52
|
+
`NetworkState` accepts Expo's camelCase keys too (`state["isInternetReachable"]`), and `to_dict()` gives the
|
|
53
|
+
camelCase dict.
|
|
54
|
+
|
|
55
|
+
## Functions
|
|
56
|
+
|
|
57
|
+
| Function | Returns | Platforms |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| `get_network_state_async()` | `NetworkState` | all |
|
|
60
|
+
| `get_ip_address_async()` | `str`, the IPv4 address; `"0.0.0.0"` without a network | all |
|
|
61
|
+
| `is_airplane_mode_enabled_async()` | `bool` | Android |
|
|
62
|
+
| `add_network_state_listener(fn)` | `Subscription` with `.remove()`. `fn(state)` runs on every change, and once with the current state when the first listener starts. | iOS, Android |
|
|
63
|
+
| `use_network_state()` | `NetworkState`, updated on change | iOS, Android |
|
|
64
|
+
|
|
65
|
+
## `NetworkState`
|
|
66
|
+
|
|
67
|
+
| Field | Notes |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `type` | `NetworkStateType`: `NONE`, `UNKNOWN`, `CELLULAR`, `WIFI`, `BLUETOOTH`, `ETHERNET`, `WIMAX`, `VPN`, `OTHER`. |
|
|
70
|
+
| `is_connected` | There is an active network. |
|
|
71
|
+
| `is_internet_reachable` | Android: the system validated internet access. iOS: the path is satisfied. |
|
|
72
|
+
|
|
73
|
+
## Platforms
|
|
74
|
+
|
|
75
|
+
- iOS 15+: `NWPathMonitor` and `getifaddrs`.
|
|
76
|
+
- Android 7 (API 24)+: `ConnectivityManager`. Adds the `ACCESS_NETWORK_STATE` permission (granted at install).
|
|
77
|
+
- Desktop: `UNKNOWN` when the machine has a route out, else `NONE`. No change events.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# pyxpo-network
|
|
2
|
+
|
|
3
|
+
Network state, IP address and connectivity changes for [pyxpo](https://github.com/pyxpo/pyxpo) apps. The
|
|
4
|
+
API follows [expo-network](https://docs.expo.dev/versions/latest/sdk/network/).
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pip install pyxpo-network
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```toml
|
|
11
|
+
[tool.pyxpo]
|
|
12
|
+
modules = ["network"]
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import pyxpo_network as Network
|
|
17
|
+
|
|
18
|
+
state = await Network.get_network_state_async()
|
|
19
|
+
print(state.type, state.is_connected, state.is_internet_reachable) # NetworkStateType.WIFI True True
|
|
20
|
+
print(await Network.get_ip_address_async()) # 192.168.1.20
|
|
21
|
+
|
|
22
|
+
sub = Network.add_network_state_listener(lambda s: print("now", s.type))
|
|
23
|
+
sub.remove()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def OfflineBanner():
|
|
27
|
+
state = Network.use_network_state() # re-renders on every change
|
|
28
|
+
if state.is_connected is False:
|
|
29
|
+
return Text("You are offline")
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Every name also has its expo-network spelling (`Network.getNetworkStateAsync`, `Network.useNetworkState`).
|
|
33
|
+
`NetworkState` accepts Expo's camelCase keys too (`state["isInternetReachable"]`), and `to_dict()` gives the
|
|
34
|
+
camelCase dict.
|
|
35
|
+
|
|
36
|
+
## Functions
|
|
37
|
+
|
|
38
|
+
| Function | Returns | Platforms |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `get_network_state_async()` | `NetworkState` | all |
|
|
41
|
+
| `get_ip_address_async()` | `str`, the IPv4 address; `"0.0.0.0"` without a network | all |
|
|
42
|
+
| `is_airplane_mode_enabled_async()` | `bool` | Android |
|
|
43
|
+
| `add_network_state_listener(fn)` | `Subscription` with `.remove()`. `fn(state)` runs on every change, and once with the current state when the first listener starts. | iOS, Android |
|
|
44
|
+
| `use_network_state()` | `NetworkState`, updated on change | iOS, Android |
|
|
45
|
+
|
|
46
|
+
## `NetworkState`
|
|
47
|
+
|
|
48
|
+
| Field | Notes |
|
|
49
|
+
| --- | --- |
|
|
50
|
+
| `type` | `NetworkStateType`: `NONE`, `UNKNOWN`, `CELLULAR`, `WIFI`, `BLUETOOTH`, `ETHERNET`, `WIMAX`, `VPN`, `OTHER`. |
|
|
51
|
+
| `is_connected` | There is an active network. |
|
|
52
|
+
| `is_internet_reachable` | Android: the system validated internet access. iOS: the path is satisfied. |
|
|
53
|
+
|
|
54
|
+
## Platforms
|
|
55
|
+
|
|
56
|
+
- iOS 15+: `NWPathMonitor` and `getifaddrs`.
|
|
57
|
+
- Android 7 (API 24)+: `ConnectivityManager`. Adds the `ACCESS_NETWORK_STATE` permission (granted at install).
|
|
58
|
+
- Desktop: `UNKNOWN` when the machine has a route out, else `NONE`. No change events.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pyxpo-network"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Network state, IP address and connectivity changes: the expo-network API for pyxpo."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Vishal Chaubey" }]
|
|
13
|
+
keywords = ["pyxpo", "pyxpo-module", "mobile", "android", "ios"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Software Development :: User Interfaces",
|
|
19
|
+
]
|
|
20
|
+
requires-python = ">=3.9"
|
|
21
|
+
dependencies = ["pyxpo>=0.1.0a2,<0.2"]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/pyxpo/pyxpo/tree/main/packages/network"
|
|
25
|
+
Issues = "https://github.com/pyxpo/pyxpo/issues"
|
|
26
|
+
|
|
27
|
+
# How `pyxpo build` finds this module: the entry point name is the module name apps list in
|
|
28
|
+
# `[tool.pyxpo] modules`, its value the import package holding pyxpo-module.json.
|
|
29
|
+
[project.entry-points."pyxpo.modules"]
|
|
30
|
+
network = "pyxpo_network"
|
|
31
|
+
|
|
32
|
+
[tool.setuptools]
|
|
33
|
+
packages = ["pyxpo_network"]
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.dynamic]
|
|
36
|
+
version = { attr = "pyxpo_network.__version__" }
|
|
37
|
+
|
|
38
|
+
[tool.setuptools.package-data]
|
|
39
|
+
pyxpo_network = ["pyxpo-module.json", "py.typed", "ios/**/*", "android/**/*"]
|
|
40
|
+
|
|
41
|
+
[tool.setuptools.exclude-package-data]
|
|
42
|
+
"*" = ["__pycache__", "*.pyc", ".DS_Store"]
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Network state, IP address and connectivity changes: the expo-network API.
|
|
2
|
+
|
|
3
|
+
import pyxpo_network as Network
|
|
4
|
+
|
|
5
|
+
state = await Network.get_network_state_async() # or Network.getNetworkStateAsync()
|
|
6
|
+
state.type, state.is_connected, state.is_internet_reachable
|
|
7
|
+
ip = await Network.get_ip_address_async() # "192.168.1.20", or "0.0.0.0" without a network
|
|
8
|
+
|
|
9
|
+
sub = Network.add_network_state_listener(lambda s: print(s.type))
|
|
10
|
+
sub.remove()
|
|
11
|
+
|
|
12
|
+
def Status():
|
|
13
|
+
state = Network.use_network_state() # re-renders on every change
|
|
14
|
+
|
|
15
|
+
On the desktop the state is a best guess (`UNKNOWN` or `NONE`) from whether the machine has a route out.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import socket
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from enum import Enum
|
|
22
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
23
|
+
|
|
24
|
+
from pyxpo.module_api import NotSupportedError, call, on_event, platform, require_linked, require_supported
|
|
25
|
+
|
|
26
|
+
__version__ = "0.1.0a1"
|
|
27
|
+
|
|
28
|
+
_EVENT = "Network.state"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class NetworkStateType(str, Enum):
|
|
32
|
+
NONE = "NONE"
|
|
33
|
+
UNKNOWN = "UNKNOWN"
|
|
34
|
+
CELLULAR = "CELLULAR"
|
|
35
|
+
WIFI = "WIFI"
|
|
36
|
+
BLUETOOTH = "BLUETOOTH"
|
|
37
|
+
ETHERNET = "ETHERNET"
|
|
38
|
+
WIMAX = "WIMAX"
|
|
39
|
+
VPN = "VPN"
|
|
40
|
+
OTHER = "OTHER"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_CAMEL = {"type": "type", "isConnected": "is_connected", "isInternetReachable": "is_internet_reachable"}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class NetworkState:
|
|
48
|
+
"""`is_connected`: there is an active network. `is_internet_reachable`: the system checked that it reaches
|
|
49
|
+
the internet. Either is None when unknown."""
|
|
50
|
+
type: NetworkStateType = NetworkStateType.UNKNOWN
|
|
51
|
+
is_connected: Optional[bool] = None
|
|
52
|
+
is_internet_reachable: Optional[bool] = None
|
|
53
|
+
|
|
54
|
+
def __getitem__(self, key: str) -> Any:
|
|
55
|
+
if key not in _CAMEL:
|
|
56
|
+
raise KeyError(key)
|
|
57
|
+
return getattr(self, _CAMEL[key])
|
|
58
|
+
|
|
59
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
60
|
+
"""The state with Expo's camelCase keys; `type` is the plain string."""
|
|
61
|
+
return {"type": self.type.value, "isConnected": self.is_connected, "isInternetReachable": self.is_internet_reachable}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _state(raw: Dict[str, Any]) -> NetworkState:
|
|
65
|
+
t = raw.get("type")
|
|
66
|
+
kind = NetworkStateType(t) if t in NetworkStateType._value2member_map_ else NetworkStateType.UNKNOWN
|
|
67
|
+
return NetworkState(kind, raw.get("isConnected"), raw.get("isInternetReachable"))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _desktop_ip() -> Optional[str]:
|
|
71
|
+
# A UDP connect picks the outgoing interface without sending anything.
|
|
72
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
73
|
+
try:
|
|
74
|
+
s.connect(("192.0.2.1", 9))
|
|
75
|
+
ip = s.getsockname()[0]
|
|
76
|
+
return None if ip.startswith("0.") else ip
|
|
77
|
+
except OSError:
|
|
78
|
+
return None
|
|
79
|
+
finally:
|
|
80
|
+
s.close()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _native() -> bool:
|
|
84
|
+
if platform() == "desktop":
|
|
85
|
+
return False
|
|
86
|
+
require_linked("Network", "network", package="pyxpo-network")
|
|
87
|
+
return True
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
async def get_network_state_async() -> NetworkState:
|
|
91
|
+
"""The current network: its type, whether it is connected and whether the internet is reachable."""
|
|
92
|
+
if not _native():
|
|
93
|
+
up = _desktop_ip() is not None
|
|
94
|
+
return NetworkState(NetworkStateType.UNKNOWN if up else NetworkStateType.NONE, up, None if up else False)
|
|
95
|
+
return _state(await call("Network", "getState", reply=True) or {})
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
async def get_ip_address_async() -> str:
|
|
99
|
+
"""The device's IPv4 address on the active network, "0.0.0.0" when there is none."""
|
|
100
|
+
if not _native():
|
|
101
|
+
return _desktop_ip() or "0.0.0.0"
|
|
102
|
+
return str(await call("Network", "getIpAddress", reply=True) or "0.0.0.0")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
async def is_airplane_mode_enabled_async() -> bool:
|
|
106
|
+
"""Android: whether airplane mode is on. Raises `NotSupportedError` on iOS and the desktop."""
|
|
107
|
+
require_supported("is_airplane_mode_enabled_async", ios=False)
|
|
108
|
+
if not _native():
|
|
109
|
+
raise NotSupportedError("is_airplane_mode_enabled_async needs Android")
|
|
110
|
+
return bool(await call("Network", "isAirplaneModeEnabled", reply=True))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Subscription:
|
|
114
|
+
def __init__(self, fn: Callable[[NetworkState], Any]) -> None:
|
|
115
|
+
self._fn: Optional[Callable[[NetworkState], Any]] = fn
|
|
116
|
+
|
|
117
|
+
def remove(self) -> None:
|
|
118
|
+
"""Stops this listener. Safe to call twice."""
|
|
119
|
+
if self._fn is None:
|
|
120
|
+
return
|
|
121
|
+
_listeners.remove(self._fn)
|
|
122
|
+
self._fn = None
|
|
123
|
+
if not _listeners:
|
|
124
|
+
_stop()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
_listeners: List[Callable[[NetworkState], Any]] = []
|
|
128
|
+
_off: Optional[Callable[[], None]] = None
|
|
129
|
+
_last: Optional[NetworkState] = None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _on_state(raw: Any) -> None:
|
|
133
|
+
global _last
|
|
134
|
+
_last = _state(raw or {})
|
|
135
|
+
for fn in list(_listeners):
|
|
136
|
+
fn(_last)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _stop() -> None:
|
|
140
|
+
global _off, _last
|
|
141
|
+
if _off is not None:
|
|
142
|
+
_off()
|
|
143
|
+
_off = None
|
|
144
|
+
_last = None
|
|
145
|
+
call("Network", "stopObserving")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def add_network_state_listener(listener: Callable[[NetworkState], Any]) -> Subscription:
|
|
149
|
+
"""Calls `listener(state)` on every network change, and once with the current state after the first
|
|
150
|
+
listener starts. Returns a subscription; call `.remove()` to stop. No events on the desktop."""
|
|
151
|
+
global _off
|
|
152
|
+
_listeners.append(listener)
|
|
153
|
+
if _off is None and _native():
|
|
154
|
+
_off = on_event(_EVENT, _on_state)
|
|
155
|
+
call("Network", "startObserving")
|
|
156
|
+
return Subscription(listener)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def use_network_state() -> NetworkState:
|
|
160
|
+
"""The current network state; the component re-renders when it changes."""
|
|
161
|
+
from pyxpo import use_effect, use_state
|
|
162
|
+
state, set_state = use_state(lambda: _last or NetworkState())
|
|
163
|
+
|
|
164
|
+
def subscribe() -> Callable[[], None]:
|
|
165
|
+
sub = add_network_state_listener(set_state)
|
|
166
|
+
if _last is not None:
|
|
167
|
+
set_state(_last)
|
|
168
|
+
return sub.remove
|
|
169
|
+
|
|
170
|
+
use_effect(subscribe, [])
|
|
171
|
+
return state
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
getNetworkStateAsync = get_network_state_async
|
|
175
|
+
getIpAddressAsync = get_ip_address_async
|
|
176
|
+
isAirplaneModeEnabledAsync = is_airplane_mode_enabled_async
|
|
177
|
+
addNetworkStateListener = add_network_state_listener
|
|
178
|
+
useNetworkState = use_network_state
|
|
179
|
+
|
|
180
|
+
__all__ = [
|
|
181
|
+
"NetworkStateType", "NetworkState", "Subscription", "get_network_state_async", "get_ip_address_async",
|
|
182
|
+
"is_airplane_mode_enabled_async", "add_network_state_listener", "use_network_state",
|
|
183
|
+
"getNetworkStateAsync", "getIpAddressAsync", "isAirplaneModeEnabledAsync", "addNetworkStateListener",
|
|
184
|
+
"useNetworkState",
|
|
185
|
+
]
|
pyxpo_network-0.1.0a1/pyxpo_network/android/src/main/java/dev/pyxpo/modules/network/NetworkModule.kt
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
package dev.pyxpo.modules.network
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.net.ConnectivityManager
|
|
5
|
+
import android.net.LinkProperties
|
|
6
|
+
import android.net.Network
|
|
7
|
+
import android.net.NetworkCapabilities
|
|
8
|
+
import android.provider.Settings
|
|
9
|
+
import dev.pyxpo.moduleapi.PxModule
|
|
10
|
+
import dev.pyxpo.moduleapi.PxModuleContext
|
|
11
|
+
import dev.pyxpo.moduleapi.PxReply
|
|
12
|
+
import org.json.JSONArray
|
|
13
|
+
import java.net.Inet4Address
|
|
14
|
+
import java.net.NetworkInterface
|
|
15
|
+
|
|
16
|
+
/** expo-network on Android: `ConnectivityManager` state, the default network callback and airplane mode. */
|
|
17
|
+
class NetworkModule : PxModule() {
|
|
18
|
+
override val name = "Network"
|
|
19
|
+
|
|
20
|
+
private var callback: ConnectivityManager.NetworkCallback? = null
|
|
21
|
+
|
|
22
|
+
private fun cm(c: Context) = c.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
|
23
|
+
|
|
24
|
+
private fun state(caps: NetworkCapabilities?): Map<String, Any?> {
|
|
25
|
+
if (caps == null) return mapOf("type" to "NONE", "isConnected" to false, "isInternetReachable" to false)
|
|
26
|
+
val type = when {
|
|
27
|
+
caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> "VPN"
|
|
28
|
+
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "WIFI"
|
|
29
|
+
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "CELLULAR"
|
|
30
|
+
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ETHERNET"
|
|
31
|
+
caps.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> "BLUETOOTH"
|
|
32
|
+
else -> "UNKNOWN"
|
|
33
|
+
}
|
|
34
|
+
return mapOf(
|
|
35
|
+
"type" to type,
|
|
36
|
+
"isConnected" to caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET),
|
|
37
|
+
"isInternetReachable" to caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED),
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private fun current(c: Context): Map<String, Any?> {
|
|
42
|
+
val m = cm(c)
|
|
43
|
+
return state(m.activeNetwork?.let { m.getNetworkCapabilities(it) })
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private fun ipAddress(c: Context): String {
|
|
47
|
+
val m = cm(c)
|
|
48
|
+
m.activeNetwork?.let { m.getLinkProperties(it) }?.linkAddresses
|
|
49
|
+
?.map { it.address }?.firstOrNull { it is Inet4Address && !it.isLoopbackAddress }
|
|
50
|
+
?.let { return it.hostAddress ?: "0.0.0.0" }
|
|
51
|
+
return try {
|
|
52
|
+
NetworkInterface.getNetworkInterfaces().toList().filter { it.isUp && !it.isLoopback }
|
|
53
|
+
.flatMap { it.inetAddresses.toList() }.firstOrNull { it is Inet4Address }?.hostAddress ?: "0.0.0.0"
|
|
54
|
+
} catch (_: Exception) { "0.0.0.0" }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
override fun call(ctx: PxModuleContext, method: String, args: JSONArray, reply: PxReply) {
|
|
58
|
+
val c = ctx.activity.applicationContext
|
|
59
|
+
when (method) {
|
|
60
|
+
"getState" -> reply(current(c), null)
|
|
61
|
+
"getIpAddress" -> reply(ipAddress(c), null)
|
|
62
|
+
"isAirplaneModeEnabled" -> reply(Settings.Global.getInt(c.contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0) != 0, null)
|
|
63
|
+
"startObserving" -> { start(ctx, c); reply(null, null) }
|
|
64
|
+
"stopObserving" -> { stop(c); reply(null, null) }
|
|
65
|
+
else -> reply(null, "Network has no method '$method'")
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The default-network callback reports the current network right after it is registered. */
|
|
70
|
+
private fun start(ctx: PxModuleContext, c: Context) {
|
|
71
|
+
if (callback != null) {
|
|
72
|
+
ctx.emit("Network.state", current(c))
|
|
73
|
+
return
|
|
74
|
+
}
|
|
75
|
+
val cb = object : ConnectivityManager.NetworkCallback() {
|
|
76
|
+
override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) {
|
|
77
|
+
ctx.emit("Network.state", state(caps))
|
|
78
|
+
}
|
|
79
|
+
override fun onLost(network: Network) {
|
|
80
|
+
ctx.emit("Network.state", state(null))
|
|
81
|
+
}
|
|
82
|
+
override fun onUnavailable() {
|
|
83
|
+
ctx.emit("Network.state", state(null))
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
callback = cb
|
|
87
|
+
try {
|
|
88
|
+
cm(c).registerDefaultNetworkCallback(cb)
|
|
89
|
+
} catch (e: Exception) {
|
|
90
|
+
callback = null
|
|
91
|
+
ctx.emit("Network.state", current(c))
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private fun stop(c: Context) {
|
|
96
|
+
val cb = callback ?: return
|
|
97
|
+
callback = null
|
|
98
|
+
try { cm(c).unregisterNetworkCallback(cb) } catch (_: Exception) {}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Network
|
|
3
|
+
|
|
4
|
+
/// expo-network on iOS. One `NWPathMonitor` runs from the first call; all of its state lives on `queue`.
|
|
5
|
+
final class NetworkModule: PxModule {
|
|
6
|
+
static let moduleName = "Network"
|
|
7
|
+
|
|
8
|
+
private let queue = DispatchQueue(label: "dev.pyxpo.network")
|
|
9
|
+
private var monitor: NWPathMonitor?
|
|
10
|
+
private var path: NWPath?
|
|
11
|
+
private var waiting: [PxReply] = []
|
|
12
|
+
private weak var observer: PxModuleContext?
|
|
13
|
+
|
|
14
|
+
required init() {}
|
|
15
|
+
|
|
16
|
+
deinit { monitor?.cancel() }
|
|
17
|
+
|
|
18
|
+
private func start() {
|
|
19
|
+
guard monitor == nil else { return }
|
|
20
|
+
let m = NWPathMonitor()
|
|
21
|
+
m.pathUpdateHandler = { [weak self] p in self?.update(p) }
|
|
22
|
+
monitor = m
|
|
23
|
+
m.start(queue: queue)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/// On `queue`.
|
|
27
|
+
private func update(_ p: NWPath) {
|
|
28
|
+
path = p
|
|
29
|
+
let state = Self.state(p)
|
|
30
|
+
let replies = waiting
|
|
31
|
+
waiting = []
|
|
32
|
+
replies.forEach { $0(state, nil) }
|
|
33
|
+
observer?.emit("Network.state", state)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private static func state(_ p: NWPath) -> [String: Any] {
|
|
37
|
+
let up = p.status == .satisfied
|
|
38
|
+
let type: String
|
|
39
|
+
if !up { type = "NONE" }
|
|
40
|
+
else if p.usesInterfaceType(.wifi) { type = "WIFI" }
|
|
41
|
+
else if p.usesInterfaceType(.cellular) { type = "CELLULAR" }
|
|
42
|
+
else if p.usesInterfaceType(.wiredEthernet) { type = "ETHERNET" }
|
|
43
|
+
else if p.usesInterfaceType(.other) {
|
|
44
|
+
// Virtual interfaces: utun/ipsec/ppp are VPN tunnels.
|
|
45
|
+
let vpn = p.availableInterfaces.contains { i in
|
|
46
|
+
i.type == .other && ["utun", "ipsec", "ppp", "tap", "tun"].contains { i.name.hasPrefix($0) }
|
|
47
|
+
}
|
|
48
|
+
type = vpn ? "VPN" : "OTHER"
|
|
49
|
+
}
|
|
50
|
+
else { type = "UNKNOWN" }
|
|
51
|
+
return ["type": type, "isConnected": up, "isInternetReachable": up]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// The IPv4 address of the interface in use: Wi-Fi (en0) first, then cellular (pdp_ip0), then any other.
|
|
55
|
+
private static func ipAddress() -> String {
|
|
56
|
+
var found: [String: String] = [:]
|
|
57
|
+
var head: UnsafeMutablePointer<ifaddrs>?
|
|
58
|
+
guard getifaddrs(&head) == 0, let first = head else { return "0.0.0.0" }
|
|
59
|
+
defer { freeifaddrs(head) }
|
|
60
|
+
var cur: UnsafeMutablePointer<ifaddrs>? = first
|
|
61
|
+
while let ifa = cur {
|
|
62
|
+
defer { cur = ifa.pointee.ifa_next }
|
|
63
|
+
let flags = Int32(ifa.pointee.ifa_flags)
|
|
64
|
+
guard let addr = ifa.pointee.ifa_addr, addr.pointee.sa_family == UInt8(AF_INET),
|
|
65
|
+
flags & IFF_UP != 0, flags & IFF_LOOPBACK == 0 else { continue }
|
|
66
|
+
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
|
67
|
+
guard getnameinfo(addr, socklen_t(addr.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 else { continue }
|
|
68
|
+
let name = String(cString: ifa.pointee.ifa_name)
|
|
69
|
+
if found[name] == nil { found[name] = String(cString: host) }
|
|
70
|
+
}
|
|
71
|
+
if let ip = found["en0"] ?? found["pdp_ip0"] { return ip }
|
|
72
|
+
return found.sorted { $0.key < $1.key }.first?.value ?? "0.0.0.0"
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
func call(_ ctx: PxModuleContext, _ method: String, _ args: [Any], _ reply: @escaping PxReply) {
|
|
76
|
+
switch method {
|
|
77
|
+
case "getState":
|
|
78
|
+
start()
|
|
79
|
+
queue.async {
|
|
80
|
+
if let p = self.path { reply(Self.state(p), nil) } else { self.waiting.append(reply) }
|
|
81
|
+
}
|
|
82
|
+
case "getIpAddress":
|
|
83
|
+
DispatchQueue.global(qos: .userInitiated).async { reply(Self.ipAddress(), nil) }
|
|
84
|
+
case "startObserving":
|
|
85
|
+
start()
|
|
86
|
+
queue.async {
|
|
87
|
+
self.observer = ctx
|
|
88
|
+
if let p = self.path { ctx.emit("Network.state", Self.state(p)) }
|
|
89
|
+
}
|
|
90
|
+
reply(nil, nil)
|
|
91
|
+
case "stopObserving":
|
|
92
|
+
queue.async { self.observer = nil }
|
|
93
|
+
reply(nil, nil)
|
|
94
|
+
default:
|
|
95
|
+
reply(nil, "Network has no method '\(method)'")
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"nativeContract": 1,
|
|
4
|
+
"name": "network",
|
|
5
|
+
"native": "Network",
|
|
6
|
+
"ios": {
|
|
7
|
+
"classes": ["NetworkModule"]
|
|
8
|
+
},
|
|
9
|
+
"android": {
|
|
10
|
+
"namespace": "dev.pyxpo.modules.network",
|
|
11
|
+
"classes": ["dev.pyxpo.modules.network.NetworkModule"],
|
|
12
|
+
"minSdk": 24
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyxpo-network
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Network state, IP address and connectivity changes: the expo-network API for pyxpo.
|
|
5
|
+
Author: Vishal Chaubey
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/pyxpo/pyxpo/tree/main/packages/network
|
|
8
|
+
Project-URL: Issues, https://github.com/pyxpo/pyxpo/issues
|
|
9
|
+
Keywords: pyxpo,pyxpo-module,mobile,android,ios
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: pyxpo<0.2,>=0.1.0a2
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# pyxpo-network
|
|
21
|
+
|
|
22
|
+
Network state, IP address and connectivity changes for [pyxpo](https://github.com/pyxpo/pyxpo) apps. The
|
|
23
|
+
API follows [expo-network](https://docs.expo.dev/versions/latest/sdk/network/).
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pip install pyxpo-network
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```toml
|
|
30
|
+
[tool.pyxpo]
|
|
31
|
+
modules = ["network"]
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import pyxpo_network as Network
|
|
36
|
+
|
|
37
|
+
state = await Network.get_network_state_async()
|
|
38
|
+
print(state.type, state.is_connected, state.is_internet_reachable) # NetworkStateType.WIFI True True
|
|
39
|
+
print(await Network.get_ip_address_async()) # 192.168.1.20
|
|
40
|
+
|
|
41
|
+
sub = Network.add_network_state_listener(lambda s: print("now", s.type))
|
|
42
|
+
sub.remove()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def OfflineBanner():
|
|
46
|
+
state = Network.use_network_state() # re-renders on every change
|
|
47
|
+
if state.is_connected is False:
|
|
48
|
+
return Text("You are offline")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Every name also has its expo-network spelling (`Network.getNetworkStateAsync`, `Network.useNetworkState`).
|
|
52
|
+
`NetworkState` accepts Expo's camelCase keys too (`state["isInternetReachable"]`), and `to_dict()` gives the
|
|
53
|
+
camelCase dict.
|
|
54
|
+
|
|
55
|
+
## Functions
|
|
56
|
+
|
|
57
|
+
| Function | Returns | Platforms |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| `get_network_state_async()` | `NetworkState` | all |
|
|
60
|
+
| `get_ip_address_async()` | `str`, the IPv4 address; `"0.0.0.0"` without a network | all |
|
|
61
|
+
| `is_airplane_mode_enabled_async()` | `bool` | Android |
|
|
62
|
+
| `add_network_state_listener(fn)` | `Subscription` with `.remove()`. `fn(state)` runs on every change, and once with the current state when the first listener starts. | iOS, Android |
|
|
63
|
+
| `use_network_state()` | `NetworkState`, updated on change | iOS, Android |
|
|
64
|
+
|
|
65
|
+
## `NetworkState`
|
|
66
|
+
|
|
67
|
+
| Field | Notes |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `type` | `NetworkStateType`: `NONE`, `UNKNOWN`, `CELLULAR`, `WIFI`, `BLUETOOTH`, `ETHERNET`, `WIMAX`, `VPN`, `OTHER`. |
|
|
70
|
+
| `is_connected` | There is an active network. |
|
|
71
|
+
| `is_internet_reachable` | Android: the system validated internet access. iOS: the path is satisfied. |
|
|
72
|
+
|
|
73
|
+
## Platforms
|
|
74
|
+
|
|
75
|
+
- iOS 15+: `NWPathMonitor` and `getifaddrs`.
|
|
76
|
+
- Android 7 (API 24)+: `ConnectivityManager`. Adds the `ACCESS_NETWORK_STATE` permission (granted at install).
|
|
77
|
+
- Desktop: `UNKNOWN` when the machine has a route out, else `NONE`. No change events.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
pyxpo_network/__init__.py
|
|
5
|
+
pyxpo_network/py.typed
|
|
6
|
+
pyxpo_network/pyxpo-module.json
|
|
7
|
+
pyxpo_network.egg-info/PKG-INFO
|
|
8
|
+
pyxpo_network.egg-info/SOURCES.txt
|
|
9
|
+
pyxpo_network.egg-info/dependency_links.txt
|
|
10
|
+
pyxpo_network.egg-info/entry_points.txt
|
|
11
|
+
pyxpo_network.egg-info/requires.txt
|
|
12
|
+
pyxpo_network.egg-info/top_level.txt
|
|
13
|
+
pyxpo_network/android/src/main/AndroidManifest.xml
|
|
14
|
+
pyxpo_network/android/src/main/java/dev/pyxpo/modules/network/NetworkModule.kt
|
|
15
|
+
pyxpo_network/ios/NetworkModule.swift
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pyxpo<0.2,>=0.1.0a2
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pyxpo_network
|