Skip to content

Find My iPhone

Bases: BaseService

The 'Find my iPhone' iCloud service

This connects to iCloud and return phone data including the near-realtime latitude and longitude.

Source code in pyicloud/services/findmyiphone.py
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
class FindMyiPhoneServiceManager(BaseService):
    """The 'Find my iPhone' iCloud service

    This connects to iCloud and return phone data including the near-realtime
    latitude and longitude.
    """

    def __init__(
        self,
        service_root: str,
        token_endpoint: str,
        session: PyiCloudSession,
        params: dict[str, Any],
        with_family: bool = False,
        refresh_interval: float | None = DEFAULT_REFRESH_INTERVAL,
        family_poll_delay: float = 0.5,
        family_poll_max_retries: int = 5,
        locate: bool = False,
    ) -> None:
        """Initialize the FindMyiPhoneServiceManager.

        ``refresh_interval=None`` disables the background monitor thread; a
        positive value (at least ``MIN_REFRESH_INTERVAL_SECONDS``) refreshes
        every that many seconds. ``locate`` controls whether the automatic
        refreshes (the construction fetch and every monitor refresh) ask the
        devices to report their location. Callers that want a fresh fix on
        demand should leave it off and call ``refresh(locate=True)``.
        """
        super().__init__(service_root, session, params)
        self._with_family: bool = with_family
        self._locate: bool = locate
        self._family_poll_delay = self._validate_poll_delay(family_poll_delay)
        self._family_poll_max_retries = self._validate_poll_retries(
            family_poll_max_retries
        )
        self._refresh_interval = self._validate_refresh_interval(refresh_interval)

        fmip_endpoint: str = f"{service_root}/fmipservice/client/web"
        self._fmip_init_url: str = f"{fmip_endpoint}/initClient"
        self._fmip_refresh_url: str = f"{fmip_endpoint}/refreshClient"
        self._fmip_sound_url: str = f"{fmip_endpoint}/playSound"
        self._fmip_message_url: str = f"{fmip_endpoint}/sendMessage"
        self._fmip_lost_url: str = f"{fmip_endpoint}/lostDevice"
        self._fmip_erase_url: str = f"{fmip_endpoint}/remoteWipeWithUserAuth"
        self._erase_token_url: str = f"{token_endpoint}/fmipWebAuthenticate"

        self._devices: dict[str, AppleDevice] = {}
        self._devices_names: list[str] = []
        self._server_ctx: dict[str, Any] | None = None
        self._user_info: dict[str, Any] | None = None
        self._monitor: threading.Thread | None = None
        self._initialized = False
        self.stop_event: threading.Event = threading.Event()
        # Serializes refreshes: the locating monitor and explicit refreshes
        # can overlap in flight, and an older response must not overwrite
        # newer server context or device state.
        self._refresh_lock: threading.Lock = threading.Lock()

        self._refresh_client_with_reauth(locate=locate)
        self._initialized = True

    def _refresh_client_with_reauth(self, locate: bool, retry: bool = False) -> None:
        """
        Refreshes the FindMyiPhoneService endpoint with re-authentication.
        This ensures that the location data is up-to-date.
        """
        # Refresh the client (own devices first)
        self.stop_event.set()
        try:
            self._refresh_client(locate=locate)
        except PyiCloudAuthRequiredException:
            if retry is True:
                raise

            _LOGGER.debug("Re-authenticating session")
            self._server_ctx = None
            # Reuse a valid saved session; authenticate falls back to a full
            # login itself when the cached token is missing or invalid.
            self.session.service.authenticate()
            try:
                self._refresh_client(locate=locate)
            except PyiCloudAuthRequiredException:
                # A token can validate but still be rejected by Find My.
                # Allow one forced login, then propagate any further rejection.
                _LOGGER.debug("Find My rejected session; forcing full login")
                self._server_ctx = None
                self.session.service.authenticate(force_refresh=True)
                self._refresh_client_with_reauth(locate=locate, retry=True)
                return

        # Initialize devices (including family devices if enabled)
        self._initialize_devices(locate=locate)
        if self._refresh_interval is not None:
            self._start_monitor_thread()

    @staticmethod
    def _validate_poll_delay(delay: float) -> float:
        """Validate family poll delay."""
        if isinstance(delay, bool) or not isinstance(delay, (int, float)):
            raise ValueError("family_poll_delay must be a non-negative number")
        if delay < 0:
            raise ValueError("family_poll_delay must be a non-negative number")
        return float(delay)

    @staticmethod
    def _validate_poll_retries(retries: int) -> int:
        """Validate family poll max retries."""
        if isinstance(retries, bool) or not isinstance(retries, int):
            raise ValueError("family_poll_max_retries must be a non-negative integer")
        if retries < 0:
            raise ValueError("family_poll_max_retries must be a non-negative integer")
        return retries

    @staticmethod
    def _validate_refresh_interval(refresh_interval: float | None) -> float | None:
        """Validate refresh interval; ``None`` disables the monitor thread."""
        if refresh_interval is None:
            return None
        if isinstance(refresh_interval, bool) or not isinstance(
            refresh_interval, (int, float)
        ):
            raise ValueError(
                "refresh_interval must be a positive number, or None to disable "
                "the monitor"
            )
        if not math.isfinite(refresh_interval):
            raise ValueError("refresh_interval must be a finite positive number")
        if refresh_interval < MIN_REFRESH_INTERVAL_SECONDS:
            raise ValueError(
                f"refresh_interval must be at least {MIN_REFRESH_INTERVAL_SECONDS:g}s "
                "or None to disable the monitor"
            )
        try:
            datetime.now() + timedelta(seconds=refresh_interval)
        except OverflowError as exc:
            raise ValueError(
                "refresh_interval is too large for a valid monitor deadline"
            ) from exc
        return float(refresh_interval)

    def _initialize_devices(self, locate: bool) -> None:
        """Initializes the devices for the FindMyiPhoneServiceManager."""

        # If family sharing is enabled, we may need to poll until all devices are ready.
        # This is indicated by the deviceFetchStatus being "LOADING".
        # Some members (e.g. Macs with location sharing disabled) remain permanently
        # LOADING and will never resolve. Track which members are LOADING between
        # retries and stop as soon as there is no progress, rather than always
        # exhausting family_poll_max_retries for stuck members.
        retries: int = 0
        prev_loading_keys: set[str] = set()
        while (
            self._with_family
            and self._user_info
            and self._user_info.get("hasMembers", False)
            and retries < self._family_poll_max_retries
        ):
            loading_keys = {
                k
                for k, v in self._user_info.get("membersInfo", {}).items()
                if v.get("deviceFetchStatus") == "LOADING"
            }
            if not loading_keys:
                break  # all family members ready
            if loading_keys == prev_loading_keys:
                _LOGGER.debug(
                    "No progress on LOADING family members after retry %d, stopping",
                    retries,
                )
                break  # no change since last retry — give up on permanently
                # stuck members
            prev_loading_keys = loading_keys
            time.sleep(self._family_poll_delay)
            self._refresh_client(locate=locate)
            retries += 1

        if not self._devices:
            raise PyiCloudNoDevicesException()

        _LOGGER.info("Number of devices found: %d", len(self._devices))

    def _start_monitor_thread(self) -> None:
        """Starts the monitor thread for the FindMyiPhoneServiceManager."""
        interval = self._refresh_interval
        if interval is None:
            return
        # The caller has already set stop_event; wait for any monitor still
        # finishing an in-flight refresh so the is_alive check below does not
        # skip starting its replacement.
        if self._monitor is not None and self._monitor.is_alive():
            self._monitor.join()
        if not self.is_alive:
            self._monitor = threading.Thread(
                target=_monitor_thread,
                kwargs={
                    "func": self._refresh_client,
                    "interval": interval,
                    "stop_event": self.stop_event,
                    "locate": self._locate,
                },
                daemon=True,
            )
            self.stop_event.clear()
            self._monitor.start()

    def _refresh_client(self, locate: bool) -> None:
        """
        Refreshes the FindMyiPhoneService endpoint, this ensures that the location data
        is up-to-date.
        """
        with self._refresh_lock:
            self._refresh_client_once(locate=locate)

    def _refresh_client_once(self, locate: bool) -> None:
        """Request one FMIP refresh and apply the response state."""
        req_json: dict[str, Any] = {
            "clientContext": {
                "appName": "iCloud Find (Web)",
                "appVersion": "2.0",
                "apiVersion": "3.0",
                "deviceListVersion": 1,
                "fmly": self._with_family,
                "timezone": _FMIP_CLIENT_CONTEXT_TIMEZONE,
                "inactiveTime": 0,
            },
        }

        if self._server_ctx:
            req_json["serverContext"] = self._server_ctx
            if locate:
                req_json["isUpdatingAllLocations"] = True
                req_json["clientContext"].update({
                    "shouldLocate": True,
                    "selectedDevice": "all",
                })

        req: Response = self.session.post(
            url=self._fmip_refresh_url if self._server_ctx else self._fmip_init_url,
            params=self.params,
            json=req_json,
        )
        resp: dict[str, Any] = req.json()

        self._server_ctx = resp.get("serverContext")
        if self._server_ctx and "theftLoss" in self._server_ctx:
            self._server_ctx["theftLoss"] = None

        self._user_info = resp.get("userInfo")

        if "content" not in resp:
            _LOGGER.debug("FMIP returned 0 devices")
            return

        _LOGGER.debug("FMIP returned %d devices", len(resp["content"]))
        for device_info in resp["content"]:
            device_id: str = device_info["id"]
            if device_id not in self._devices:
                self._devices[device_id] = AppleDevice(
                    device_info,
                    self.params,
                    manager=self,
                    sound_url=self._fmip_sound_url,
                    lost_url=self._fmip_lost_url,
                    message_url=self._fmip_message_url,
                    erase_url=self._fmip_erase_url,
                    erase_token_url=self._erase_token_url,
                )
            else:
                self._devices[device_id].update(device_info)

        self._devices_names = list(self._devices.keys())

    def refresh(self, locate: bool = True) -> None:
        """Public method to refresh the FindMyiPhoneService endpoint."""
        self._refresh_client_with_reauth(locate=locate)

    def __getitem__(self, key: str | int) -> "AppleDevice":
        """Gets a device by name or index."""
        if not self.is_alive:
            self._refresh_client_with_reauth(locate=True)

        if isinstance(key, int):
            key = self._devices_names[key]
        return self._devices[key]

    def __str__(self) -> str:
        """String representation of the devices."""
        return f"{self._devices}"

    def __repr__(self) -> str:
        """Representation of the device."""
        return f"{self}"

    def __iter__(self) -> Iterator["AppleDevice"]:
        """Iterates over the devices."""

        if not self.is_alive:
            self._refresh_client_with_reauth(locate=True)
        return iter(self._devices.values())

    def __len__(self) -> int:
        """Returns the number of devices."""
        if not self.is_alive:
            self._refresh_client_with_reauth(locate=True)
        return len(self._devices)

    @property
    def is_alive(self) -> bool:
        """Whether the manager can answer a read without refreshing.

        A manager built with ``refresh_interval=None`` serves the data from
        its construction refresh, so reads must not trigger a fresh refresh
        (and a locate) each time. A manager with a monitor is live while that
        thread runs, so a stopped monitor still refreshes on the next read.
        """
        if self._monitor is None:
            return self._initialized
        return self._monitor.is_alive()

    @property
    def devices(self) -> "MappingProxyType[str, AppleDevice]":
        """Returns the devices."""
        return MappingProxyType(self._devices)

    @property
    def user_info(self) -> MappingProxyType[str, Any] | None:
        """Returns the user info."""
        return MappingProxyType(self._user_info) if self._user_info else None

is_alive property

Whether the manager can answer a read without refreshing.

A manager built with refresh_interval=None serves the data from its construction refresh, so reads must not trigger a fresh refresh (and a locate) each time. A manager with a monitor is live while that thread runs, so a stopped monitor still refreshes on the next read.

devices property

Returns the devices.

user_info property

Returns the user info.

refresh(locate=True)

Public method to refresh the FindMyiPhoneService endpoint.

Source code in pyicloud/services/findmyiphone.py
319
320
321
def refresh(self, locate: bool = True) -> None:
    """Public method to refresh the FindMyiPhoneService endpoint."""
    self._refresh_client_with_reauth(locate=locate)