Skip to content

Commit bbd5e19

Browse files
committed
update for pymd3 async refactor
1 parent ee7f7e2 commit bbd5e19

File tree

4 files changed

+31
-28
lines changed

4 files changed

+31
-28
lines changed

src/devicemanagement/device_manager.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import traceback
2+
import asyncio
23
import plistlib
34
import time
45
from tempfile import TemporaryDirectory
@@ -111,7 +112,7 @@ def get_devices(self, settings: QSettings, show_alert=lambda x: None):
111112
self.pref_manager.settings = settings
112113
# handle errors when failing to get connected devices
113114
try:
114-
connected_devices = usbmux.list_devices()
115+
connected_devices = asyncio.run(usbmux.list_devices())
115116
except Exception:
116117
sysmsg = QCoreApplication.tr("If you are on Linux, make sure you have usbmuxd and libimobiledevice installed.")
117118
if os.name == 'nt':
@@ -125,7 +126,7 @@ def get_devices(self, settings: QSettings, show_alert=lambda x: None):
125126
for device in connected_devices:
126127
if self.pref_manager.apply_over_wifi or device.is_usb:
127128
try:
128-
ld = create_using_usbmux(serial=device.serial)
129+
ld = asyncio.run(create_using_usbmux(serial=device.serial))
129130
vals = ld.all_values
130131
model = vals['ProductType']
131132
hardware = vals['HardwareModel']
@@ -268,7 +269,7 @@ def current_device_books_container_uuid_callback(self, uuid: Optional[str]=None)
268269
self.pref_manager.settings.setValue(self.data_singleton.current_device.udid + "_books_container_uuid", uuid)
269270

270271
def get_app_hashes(self, bundle_ids: list[str]) -> dict:
271-
apps = InstallationProxyService(lockdown=self.data_singleton.current_device.ld).get_apps(application_type="Any", calculate_sizes=False)
272+
apps = asyncio.run(InstallationProxyService(lockdown=self.data_singleton.current_device.ld).get_apps(application_type="Any", calculate_sizes=False))
272273
results = {}
273274
for bundle_id in bundle_ids:
274275
app_info = apps[bundle_id]
@@ -280,7 +281,7 @@ def send_app_hashes_afc(self, hashes: dict) -> str:
280281
with TemporaryDirectory() as tmpdir:
281282
# get the bundle id of Pocket Poster
282283
bundle_id = "com.leemin.Pocket-Poster"
283-
apps = InstallationProxyService(lockdown=self.data_singleton.current_device.ld).get_apps(application_type="User", calculate_sizes=False)
284+
apps = asyncio.run(InstallationProxyService(lockdown=self.data_singleton.current_device.ld).get_apps(application_type="User", calculate_sizes=False))
284285
for app in apps.values():
285286
if app["CFBundleExecutable"] == "Pocket Poster":
286287
bundle_id = app["CFBundleIdentifier"]
@@ -295,7 +296,7 @@ def send_app_hashes_afc(self, hashes: dict) -> str:
295296
tmpf = os.path.join(tmpdir, fname)
296297
with open(tmpf, "w", encoding='UTF-8') as in_file:
297298
in_file.write(hashes[key])
298-
afc.push(tmpf, f"/Documents/{fname}")
299+
asyncio.run(afc.push(tmpf, f"/Documents/{fname}"))
299300

300301

301302
def reset_device_pairing(self):
@@ -543,7 +544,7 @@ def start_restore(self, files_to_restore: list[FileToRestore], use_bookrestore:
543544
connected = False
544545
while not connected and max_timeout >= time.time():
545546
try:
546-
new_ld = create_using_usbmux(serial=self.get_current_device_udid(), pair_timeout=180)
547+
new_ld = asyncio.run(create_using_usbmux(serial=self.get_current_device_udid(), pair_timeout=180))
547548
connected = True
548549
except Exception:
549550
pass

src/restore/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from tempfile import TemporaryDirectory
22
from pathlib import Path
3+
import asyncio
34

45
from pymobiledevice3.lockdown import create_using_usbmux
56
from pymobiledevice3.services.mobilebackup2 import Mobilebackup2Service
@@ -13,7 +14,7 @@ def reboot_device(reboot: bool = False, lockdown_client: LockdownClient = None):
1314
if reboot and lockdown_client != None:
1415
print("Success! Rebooting your device...")
1516
with DiagnosticsService(lockdown_client) as diagnostics_service:
16-
diagnostics_service.restart()
17+
asyncio.run(diagnostics_service.restart())
1718
print("Remember to turn Find My back on!")
1819

1920
def perform_restore(backup: backup.Backup, reboot: bool = False, lockdown_client: LockdownClient = None, progress_callback = lambda x: None):
@@ -22,9 +23,9 @@ def perform_restore(backup: backup.Backup, reboot: bool = False, lockdown_client
2223
backup.write_to_directory(Path(backup_dir))
2324

2425
if lockdown_client == None:
25-
lockdown_client = create_using_usbmux()
26+
lockdown_client = asyncio.run(create_using_usbmux())
2627
with Mobilebackup2Service(lockdown_client) as mb:
27-
mb.restore(backup_dir, system=True, reboot=False, copy=False, source=".", progress_callback=progress_callback, skip_apps=True)
28+
asyncio.run(mb.restore(backup_dir, system=True, reboot=False, copy=False, source=".", progress_callback=progress_callback, skip_apps=True))
2829
# reboot the device
2930
reboot_device(reboot, lockdown_client)
3031
except PyMobileDevice3Exception as e:

src/restore/bookrestore.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
from pymobiledevice3.services.afc import AfcService
2525
from pymobiledevice3.services.amfi import AmfiService
2626
from pymobiledevice3.remote.remote_service_discovery import RemoteServiceDiscoveryService
27-
from pymobiledevice3.services.dvt.dvt_secure_socket_proxy import DvtSecureSocketProxyService
27+
from pymobiledevice3.services.dvt.instruments.dvt_provider import DvtProvider
2828
from pymobiledevice3.services.dvt.instruments.process_control import ProcessControl
2929
from pymobiledevice3.services.os_trace import OsTraceService
3030
from http.server import HTTPServer, SimpleHTTPRequestHandler
@@ -178,7 +178,7 @@ async def async_connection():
178178
loop = asyncio.get_running_loop()
179179

180180
def run_blocking_callback():
181-
with DvtSecureSocketProxyService(rsd) as dvt:
181+
with DvtProvider(rsd) as dvt:
182182
apply_bookrestore_files(files, rsd, dvt, current_device_uuid_callback, progress, transfer_mode, do_full_reboot)
183183

184184
await loop.run_in_executor(None, run_blocking_callback)
@@ -265,7 +265,7 @@ def generate_bldbmanager(files: list[FileToRestore], out_file: str, afc: AfcServ
265265
zassetpath = f'{file.restore_path}.zassetpath'
266266
media_folder = file_name#f'{nugget_media_folder}/{file_name}'
267267
zplistpath = f'/var/mobile/Media/{media_folder}'
268-
afc.set_file_contents(media_folder, file.contents)
268+
asyncio.run(afc.set_file_contents(media_folder, file.contents))
269269
else:
270270
zdownloadid = ""
271271
zassetpath = file.restore_path
@@ -283,7 +283,7 @@ def generate_bldbmanager(files: list[FileToRestore], out_file: str, afc: AfcServ
283283
# return the number of files in the thing
284284
return z_id
285285

286-
def apply_bookrestore_files(files: list[FileToRestore], lockdown_client: LockdownClient, dvt: DvtSecureSocketProxyService,
286+
def apply_bookrestore_files(files: list[FileToRestore], lockdown_client: LockdownClient, dvt: DvtProvider,
287287
current_device_uuid_callback = lambda x: None, progress_callback = lambda x: None,
288288
transfer_mode: BookRestoreFileTransferMethod = BookRestoreFileTransferMethod.LocalHost,
289289
do_full_reboot: bool = False):
@@ -369,13 +369,13 @@ def apply_bookrestore_files(files: list[FileToRestore], lockdown_client: Lockdow
369369
""")
370370
connection.commit()
371371

372-
procs = OsTraceService(lockdown=lockdown_client).get_pid_list().get("Payload")
372+
procs = asyncio.run(OsTraceService(lockdown=lockdown_client).get_pid_list()).get("Payload")
373373
pid_bookassetd = next((pid for pid, p in procs.items() if p['ProcessName'] == 'bookassetd'), None)
374374
pid_books = next((pid for pid, p in procs.items() if p['ProcessName'] == 'Books'), None)
375375
if pid_bookassetd:
376-
pc.signal(pid_bookassetd, 19)
376+
asyncio.run(pc.signal(pid_bookassetd, 19))
377377
if pid_books:
378-
pc.kill(pid_books)
378+
asyncio.run(pc.kill(pid_books))
379379

380380
progress_callback("Uploading files...")
381381

@@ -389,7 +389,7 @@ def apply_bookrestore_files(files: list[FileToRestore], lockdown_client: Lockdow
389389
_, file_name = os.path.split(file.restore_path)
390390
print(f"including {file.restore_path}")
391391
media_folder = file_name
392-
afc.set_file_contents(media_folder, file.contents)
392+
asyncio.run(afc.set_file_contents(media_folder, file.contents))
393393

394394
def fast_upload(local_path, remote_path):
395395
content = b''
@@ -399,7 +399,7 @@ def fast_upload(local_path, remote_path):
399399
content = f.read()
400400
except OSError:
401401
content = b''
402-
afc.set_file_contents(remote_path, content)
402+
asyncio.run(afc.set_file_contents(remote_path, content))
403403

404404
fast_upload(temp_db_path, "Downloads/downloads.28.sqlitedb")
405405
fast_upload(temp_db_path + "-shm", "Downloads/downloads.28.sqlitedb-shm")
@@ -418,10 +418,10 @@ def fast_upload(local_path, remote_path):
418418
except Exception:
419419
pass
420420

421-
procs = OsTraceService(lockdown=lockdown_client).get_pid_list().get("Payload")
421+
procs = asyncio.run(OsTraceService(lockdown=lockdown_client).get_pid_list()).get("Payload")
422422
pid_itunesstored = next((pid for pid, p in procs.items() if p['ProcessName'] == 'itunesstored'), None)
423423
if pid_itunesstored:
424-
pc.kill(pid_itunesstored)
424+
asyncio.run(pc.kill(pid_itunesstored))
425425

426426
timeout = time.time() + 120
427427
progress_callback("Waiting for itunesstored to finish download..." + "\n" + "(This might take a minute)")
@@ -435,12 +435,12 @@ def fast_upload(local_path, remote_path):
435435
pid_bookassetd = next((pid for pid, p in procs.items() if p['ProcessName'] == 'bookassetd'), None)
436436
pid_books = next((pid for pid, p in procs.items() if p['ProcessName'] == 'Books'), None)
437437
if pid_bookassetd:
438-
pc.kill(pid_bookassetd)
438+
asyncio.run(pc.kill(pid_bookassetd))
439439
if pid_books:
440-
pc.kill(pid_books)
440+
asyncio.run(pc.kill(pid_books))
441441

442442
try:
443-
pc.launch("com.apple.iBooks")
443+
asyncio.run(pc.launch("com.apple.iBooks"))
444444
except Exception as e:
445445
raise NuggetException("Error launching Books app", detailed_text=repr(e))
446446

@@ -461,7 +461,7 @@ def fast_upload(local_path, remote_path):
461461
# respring anyway even if it is not detected that all files overwrote
462462
break
463463
# raise Exception("Timed out waiting for file, please try again.")
464-
pc.kill(pid_bookassetd)
464+
asyncio.run(pc.kill(pid_bookassetd))
465465
if transfer_mode == BookRestoreFileTransferMethod.LocalHost:
466466
close_dl_connection()
467467
remove_db_files(temp_dl_manager)
@@ -471,9 +471,9 @@ def fast_upload(local_path, remote_path):
471471
reboot_device(True, lockdown_client=lockdown_client)
472472
else:
473473
progress_callback("Respringing")
474-
procs = OsTraceService(lockdown=lockdown_client).get_pid_list().get("Payload")
474+
procs = asyncio.run(OsTraceService(lockdown=lockdown_client).get_pid_list()).get("Payload")
475475
pid = next((pid for pid, p in procs.items() if p['ProcessName'] == 'backboardd'), None)
476-
pc.kill(pid)
476+
asyncio.run(pc.kill(pid))
477477

478478
def perform_bookrestore(files: list[FileToRestore], lockdown_client: LockdownClient,
479479
current_device_books_uuid_callback = lambda x: None, progress_callback = lambda x: None,
@@ -482,7 +482,7 @@ def perform_bookrestore(files: list[FileToRestore], lockdown_client: LockdownCli
482482
if not lockdown_client.developer_mode_status:
483483
# enable developer mode
484484
progress_callback("Enabling Developer Mode...")
485-
AmfiService(lockdown=lockdown_client).reveal_developer_mode_option_in_ui()
485+
asyncio.run(AmfiService(lockdown=lockdown_client).reveal_developer_mode_option_in_ui())
486486
raise NuggetException("You must enable developer mode on your device. You can do it in the Settings app.\n\nClick \"Show Details\" for more information.",
487487
detailed_text="BookRestore tweaks with the AFC method require developer mode to apply.\n\nYou can enable this at the bottom of Settings > Privacy & Security > Developer Mode on your iPhone or iPad.")
488488
if os.name == 'nt':

src/restore/restore.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import os
77
import plistlib
88
import ssl
9+
import asyncio
910

1011
class FileToRestore:
1112
def __init__(self,
@@ -167,7 +168,7 @@ def restore_files(files: list[FileToRestore], reboot: bool = False, lockdown_cli
167168
bundle_id = last_domain.removeprefix("AppDomain-")
168169
if not bundle_id in active_bundle_ids:
169170
if apps == None:
170-
apps = InstallationProxyService(lockdown=lockdown_client).get_apps(application_type="Any", calculate_sizes=False)
171+
apps = asyncio.run(InstallationProxyService(lockdown=lockdown_client).get_apps(application_type="Any", calculate_sizes=False))
171172
app_info = apps[bundle_id]
172173
active_bundle_ids.append(bundle_id)
173174
apps_list.append(backup.AppBundle(

0 commit comments

Comments
 (0)