-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
271 lines (238 loc) Β· 11.6 KB
/
App.tsx
File metadata and controls
271 lines (238 loc) Β· 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
import { useState, useEffect, useRef } from 'react';
import {
View,
Button,
Text,
ActivityIndicator,
Linking,
Platform,
PermissionsAndroid,
StyleSheet,
SafeAreaView,
TouchableOpacity,
ScrollView
} from 'react-native';
import { Softphone } from 'react-native-softphone-sdk';
const FREJUN_CREDENTIALS = {
clientId: '<Client-Id>',
clientSecret: '<Client-Secret>',
};
const App = () => {
const [softphone, setSoftphone] = useState<Softphone | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [connectionStatus, setConnectionStatus] = useState<'Disconnected' | 'Connecting' | 'Connected'>('Disconnected');
const [callStatus, setCallStatus] = useState<'Idle' | 'Incoming' | 'Dialing' | 'Ringing' | 'Active'>('Idle');
const [remoteContact, setRemoteContact] = useState('');
const activeSession = useRef<any>(null);
useEffect(() => {
const initializeSdk = async () => {
console.log('[App] π Starting Initialization...');
try {
const restoredSoftphone = await Softphone.initialize(FREJUN_CREDENTIALS);
if (restoredSoftphone) {
setSoftphone(restoredSoftphone);
}
} catch (error) {
console.error('[App] β Initialization failed:', error);
} finally {
setIsLoading(false);
}
};
initializeSdk();
const deepLinkSub = Linking.addEventListener('url', async (event) => {
if (event.url.includes('?code=')) {
setIsLoading(true);
try {
const newSoftphone = await Softphone.handleRedirect(event.url);
console.log('[App] π Login successful!');
setSoftphone(newSoftphone);
} catch (error) {
console.error('[App] β Login failed:', error);
} finally {
setIsLoading(false);
}
}
});
return () => deepLinkSub.remove();
}, []);
useEffect(() => {
if (softphone) {
const listeners = {
onConnectionStateChange: (type: any, state: any, isError: boolean, error: any) => {
console.log(`[App] π‘ Status: ${state}`);
console.log(`[App] π‘ Type: ${type}`);
console.log(`[App] π‘ Error: ${error}`);
console.log(`[App] π‘ IsError: ${isError}`);
if (state === 'Registered' || state === 'Connected') {
setConnectionStatus('Connected');
} else if (state === 'Unregistered' || state === 'Disconnected') {
setConnectionStatus('Disconnected');
} else {
setConnectionStatus('Connecting');
}
},
onCallCreated: (type: any, session: any, details: any) => {
console.log(`[App] π Call Created. Type: ${type}`);
// Logic to handle multiple incoming invites for the same call
if (type === 'Incoming' && callStatus === 'Incoming') {
console.log('[App] β οΈ Duplicate Invite received. Updating session reference.');
// We update the ref to the latest session invite, as that's likely the one we will answer
activeSession.current = session;
return;
}
activeSession.current = session;
const candidate = details?.candidate || 'Unknown';
setRemoteContact(candidate);
if (type === 'Incoming') {
setCallStatus('Incoming');
} else {
setCallStatus('Dialing');
}
},
onCallRinging: (session: any) => {
console.log('[App] π Ringing', session);
setCallStatus('Ringing');
},
onCallAnswered: (session: any) => {
console.log('[App] π£οΈ Answered');
setCallStatus('Active');
activeSession.current = session;
},
// *** CRITICAL FIX HERE ***
onCallHangup: (session: any) => {
console.log('[App] π΅ Hangup received');
// Check if the session hanging up is the one we are currently using
if (activeSession.current && activeSession.current !== session) {
console.log('[App] π‘οΈ Ignoring hangup for a session that is not active (Duplicate Invite Cancellation)');
return;
}
console.log('[App] β
Valid Hangup. Resetting UI.');
setCallStatus('Idle');
setRemoteContact('');
activeSession.current = null;
}
};
setConnectionStatus('Connecting');
softphone.start(listeners).catch(err => {
console.error("[App] β Start failed:", err);
setConnectionStatus('Disconnected');
});
}
}, [softphone, callStatus]); // Added callStatus to dependency array so we can check it inside listeners
const handleLogin = async () => {
if (Platform.OS === 'android') {
await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO);
}
await Softphone.login();
};
const handleMakeCall = async () => {
if (!softphone) return;
await softphone.makeCall('+916361710745', '+918065428342');
};
const handleAnswer = async () => {
if (activeSession.current) {
console.log('[App] Answering call...');
try {
await activeSession.current.answer();
} catch (e) { console.error(e); }
} else {
console.warn('[App] No active session to answer!');
}
};
const handleHangup = async () => {
if (activeSession.current) {
console.log('[App] Hanging up...');
try {
await activeSession.current.hangup();
} catch (e) { console.error(e); }
}
};
const handleLogout = async () => {
if (softphone) {
await softphone.logout();
setSoftphone(null);
setConnectionStatus('Disconnected');
}
}
if (isLoading) return <ActivityIndicator size="large" style={styles.loader} />;
return (
<SafeAreaView style={styles.container}>
<ScrollView contentContainerStyle={styles.content}>
<Text style={styles.header}>Softphone</Text>
{!softphone ? (
<Button title="Login with FreJun" onPress={handleLogin} />
) : (
<View style={styles.dashboard}>
<View style={[
styles.badge,
{ backgroundColor: connectionStatus === 'Connected' ? '#4CAF50' : '#F44336' }
]}>
<Text style={styles.badgeText}>{connectionStatus.toUpperCase()}</Text>
</View>
{callStatus === 'Incoming' && (
<View style={[styles.card, styles.incomingCard]}>
<Text style={styles.incomingTitle}>π Incoming Call</Text>
<Text style={styles.contactName}>{remoteContact}</Text>
<View style={styles.row}>
<TouchableOpacity style={[styles.btn, styles.btnReject]} onPress={handleHangup}>
<Text style={styles.btnText}>Reject</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.btn, styles.btnAnswer]} onPress={handleAnswer}>
<Text style={styles.btnText}>Answer</Text>
</TouchableOpacity>
</View>
</View>
)}
{callStatus === 'Active' && (
<View style={styles.card}>
<Text style={styles.activeTitle}>On Call</Text>
<Text style={styles.contactName}>{remoteContact}</Text>
<Text style={{ color: 'green', marginBottom: 20 }}>00:00</Text>
<TouchableOpacity style={[styles.btn, styles.btnReject, { width: '80%' }]} onPress={handleHangup}>
<Text style={styles.btnText}>End Call</Text>
</TouchableOpacity>
</View>
)}
{(callStatus === 'Dialing' || callStatus === 'Ringing') && (
<View style={styles.card}>
<Text style={styles.activeTitle}>Calling...</Text>
<Text style={styles.contactName}>{remoteContact}</Text>
<ActivityIndicator size="small" color="#0000ff" style={{ marginBottom: 10 }} />
<Button title="Cancel" color="red" onPress={handleHangup} />
</View>
)}
{callStatus === 'Idle' && connectionStatus === 'Connected' && (
<View style={styles.card}>
<Text style={{ marginBottom: 10 }}>Ready to make calls</Text>
<Button title="Call Test Number" onPress={handleMakeCall} />
</View>
)}
<View style={{ marginTop: 50 }}>
<Button title="Logout" color="gray" onPress={handleLogout} />
</View>
</View>
)}
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#f0f0f0' },
loader: { flex: 1, justifyContent: 'center' },
content: { padding: 20, alignItems: 'center' },
header: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, color: '#333' },
dashboard: { width: '100%', alignItems: 'center' },
badge: { paddingHorizontal: 15, paddingVertical: 5, borderRadius: 20, marginBottom: 20 },
badgeText: { color: '#fff', fontWeight: 'bold', fontSize: 12 },
card: { width: '100%', backgroundColor: '#fff', borderRadius: 15, padding: 20, alignItems: 'center', elevation: 5, shadowColor: '#000', shadowOpacity: 0.1, shadowRadius: 5, marginBottom: 20 },
incomingCard: { backgroundColor: '#E3F2FD', borderColor: '#2196F3', borderWidth: 1 },
incomingTitle: { fontSize: 18, fontWeight: 'bold', marginBottom: 5, color: '#000' },
contactName: { fontSize: 20, marginBottom: 20, color: '#333' },
row: { flexDirection: 'row', justifyContent: 'space-around', width: '100%' },
btn: { paddingVertical: 12, paddingHorizontal: 20, borderRadius: 30, minWidth: 100, alignItems: 'center' },
btnAnswer: { backgroundColor: '#4CAF50' },
btnReject: { backgroundColor: '#F44336' },
btnText: { color: 'white', fontWeight: 'bold' },
activeTitle: { fontSize: 16, color: '#666' },
});
export default App;