waitForInChat function
Waits up to two minutes for the chat screen. One check at a time -- a slow check is never overlapped by the next one -- and a single page reload at 70s, after which WPP is injected again with the same version and config and the listeners are re-attached.
Implementation
Future<bool> waitForInChat(
WpClientInterface wpClient, {
String? wppVersion,
String? wppJsContent,
Map<String, dynamic>? wppConfig,
bool autoTakeover = true,
}) async {
final wppAuth = WppAuth(wpClient);
var readyEvent = false;
void onReady(dynamic _) => readyEvent = true;
// Fast-track if already ready
if (await wppAuth.isMainReady()) return true;
await wpClient.on(WhatsappEvent.connmainready, onReady);
var startTime = DateTime.now();
bool reloaded = false;
try {
while (true) {
if (readyEvent) return true;
final seconds = DateTime.now().difference(startTime).inSeconds;
if (seconds >= 120) return false;
try {
if (await wppAuth.isMainReady()) return true;
final isLoaded = await wppAuth.isMainLoaded();
final isSynced = await wppAuth.isSynced();
// Loaded and synced, or loaded for long enough
if (isLoaded && (isSynced || seconds > 10)) {
WhatsappLogger.log(
"Main identity ready (Early via Loaded: $isLoaded, Synced: $isSynced)");
return true;
}
if (seconds > 70 && !reloaded) {
WhatsappLogger.log(
"Connection seems stuck. Attempting a page reload for recovery...");
reloaded = true;
await wpClient.reload();
await Future.delayed(const Duration(seconds: 5));
await WppConnect.init(
wpClient,
wppVersion: wppVersion,
wppJsContent: wppJsContent,
config: wppConfig,
autoTakeover: autoTakeover,
);
await wpClient.restoreListeners();
startTime = DateTime.now();
continue;
}
if (seconds > 0 && seconds % 10 == 0) {
final isAuth = await wppAuth.isAuthenticated();
if (!isAuth) {
WhatsappLogger.log("Authentication lost while waiting for main.");
return false;
}
WhatsappLogger.log(
"Waiting for main ready... (Auth: OK, Loaded: $isLoaded, Synced: $isSynced, Time: $seconds/120s)");
}
} catch (e) {
WhatsappLogger.log("waitForInChat check failed: $e");
}
await Future.delayed(const Duration(seconds: 1));
}
} finally {
try {
await wpClient.off(WhatsappEvent.connmainready, onReady);
} catch (_) {}
}
}