-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.js
More file actions
441 lines (384 loc) · 14.3 KB
/
App.js
File metadata and controls
441 lines (384 loc) · 14.3 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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import { useEffect, useState } from 'react';
import { Alert, StyleSheet, Text, View, Button, TextInput, StatusBar, TouchableOpacity, Linking, Switch, Image, TouchableWithoutFeedback, Keyboard } from 'react-native';
import { addEventListener } from "@react-native-community/netinfo";
// import * as BackgroundFetch from 'expo-background-fetch';
import * as BackgroundTask from 'expo-background-task';
import * as TaskManager from 'expo-task-manager';
import { MaterialCommunityIcons, AntDesign } from '@expo/vector-icons';
import { useAsyncStorage } from '@react-native-async-storage/async-storage';
import axios from 'axios';
import ToastManager, { Toast } from 'toastify-react-native'
import { SafeAreaView } from 'react-native-safe-area-context';
const APP_VERSION = "1.2.0";
const BACKGROUND_TASK_IDENTIFIER = 'background-fetch';
TaskManager.defineTask(BACKGROUND_TASK_IDENTIFIER, async () => {
try {
await logToStorage("Background fetch task running");
const l = await forceLogin(true);
if (l == 0) {
await logToStorage("Background fetch task completed");
return BackgroundTask.BackgroundTaskResult.Success;
} else {
await logToStorage(`Background fetch task failed ${l}`);
return BackgroundTask.BackgroundTaskResult.Failed;
}
} catch (error) {
await logToStorage(`Background fetch task error: ${error}`);
return BackgroundTask.BackgroundTaskResult.Failed;
}
});
async function registerBackgroundFetchAsync() {
return BackgroundTask.registerTaskAsync(BACKGROUND_TASK_IDENTIFIER, {
minimumInterval: 31 * 60, //half an hour DEV
stopOnTerminate: false, // android only,
startOnBoot: true, // android only
});
}
async function unregisterBackgroundFetchAsync() {
return BackgroundTask.unregisterTaskAsync(BACKGROUND_TASK_IDENTIFIER);
}
const logToStorage = async (message) => {
const { getItem, setItem } = useAsyncStorage('logs');
let logs = JSON.parse(await getItem()) || [];
const timestamp = new Date().toLocaleString('en-GB', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });
logs.unshift({ timestamp, message: `${timestamp}: ${message}` });
if (logs.length > 20) logs = logs.slice(0, 10);
await setItem(JSON.stringify(logs));
};
export default function App() {
const [user, setUserValue] = useState(null);
const [pass, setPassValue] = useState(null);
const [toggle, setToggleValue] = useState(true);
const { getItem: getUser, setItem: setUser } = useAsyncStorage("username");
const { getItem: getPass, setItem: setPass } = useAsyncStorage("password");
const { getItem: getToggle, setItem: setToggle } = useAsyncStorage("toggle");
const { getItem: getLast, setItem: setLast } = useAsyncStorage('last');
const [lastLogin, setLastLogin] = useState(new Date(0));
let listener = undefined;
const [showPass, setShowPass] = useState(false);
const toggleShowPassword = () => {
setShowPass(!showPass);
};
const forceLogout = async () => {
const logoutFetched = await fetch("http://172.16.222.1:1000/logout?0307020009020400", {
"headers": {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"accept-language": "en-US,en",
"sec-gpc": "1",
"upgrade-insecure-requests": "1",
"Referer": "http://172.16.222.1:1000/keepalive?0307020009020400",
"Referrer-Policy": "strict-origin-when-cross-origin"
},
"body": null,
"method": "GET"
}).catch(() => { });
return;
// console.log(logoutFetched);
}
let trial = 0;
const forceLogin = async (bg = false) => {
console.log("logging in")
const loginUser = await getUser();
const loginPass = await getPass();
trial++;
try {
// GET Url
const loginURL = await detectCaptivePortalUrl() ?? "http://172.16.222.1:1000/login?0330598d1f22608a";
await logToStorage("GETTING magic")
const fetched = await axios.get(loginURL).catch(async (e) => {
console.log(e)
return await logToStorage(`Error fetching magic: ${e?.code}`);
})
if (!fetched || fetched?.status !== 200) {
logToStorage("Failed to get magic");
Toast.error("Not connected to IIIT Kottayam");
return 1;
}
const magic = fetched.data.match(/magic" value="([a-zA-Z0-9]+)"/i)[1];
await logToStorage("POSTING login");
// Extract base URL from loginURL
const baseUrl = loginURL.replace(/\/[^\/]*$/, '/');
const r2 = await axios.post(
baseUrl,
`magic=${magic}&username=${encodeURIComponent(loginUser)}&password=${encodeURIComponent(loginPass)}`
).catch(async e => {
console.log(e);
await logToStorage(`ERR Posting: ${e?.message}`);
return null;
});
await logToStorage(`Posted login`);
if (!r2) {
if (trial < 3) {
await logToStorage(`Failed login on try ${trial}`);
Toast.error("Failed login. Trying again in 5s");
await new Promise(resolve => setTimeout(resolve, 5000));
return await forceLogin(bg);
} else {
await logToStorage(`Failed login on all trials | ${e}`);
trial = 0;
return 2;
}
}else if(r2.data.includes("failed")){
await logToStorage(`Failed login ${loginUser} | ${loginPass[0]}`);
if (!bg) Toast.error("Incorrect Credentials");
return 3;
}
await logToStorage("Success");
console.log('connected now')
Toast.success("Connected");
await updateLast();
trial = 0;
return 0;
} catch (e) {
// if (!bg) Toast.error("Error occured!");
// console.error(e);
// await logToStorage(`Uncaught Error: ${e}`);
// return e;
}
}
const verifyInfo = async () => {
if (pass == null) {
Toast.error("Invalid username or password");
return false;
}
if (user.length != 11 || !(/^202[1-9](bc[a-z]|bec)[0-9]{4}$/gi.test(user))) {
Toast.error("Invalid Username");
return false;
}
return true;
}
const readAll = async () => {
setUserValue(await getUser() ?? "");
setPassValue(await getPass() ?? "");
setToggleValue((await getToggle()) == "true" ? true : false);
setLastLogin(new Date(parseInt(await getLast())) ?? new Date(0));
}
const updateLast = async () => {
setLastLogin(new Date());
await setLast(Date.now().toString());
}
const writeInfo = async () => {
await setUser(user);
await setPass(pass);
}
const writeToggle = async () => {
setToggleValue(!toggle);
await setToggle(!toggle ? "true" : "false");
}
const tapToggle = () => {
if (!toggle) {
registerBackgroundFetchAsync();
listener = (addEventListener(state => {
if (state.type == "wifi" && ((lastLogin.getTime() + 1 * 60 * 60 * 1000) <= Date.now())) {
forceLogin(true);
} else {
console.log(`last logged in ${(Date.now() - lastLogin.getTime()) / 1000}`)
}
}))
} else {
unregisterBackgroundFetchAsync();
if (listener !== undefined) listener();
}
writeToggle();
}
const detectCaptivePortalUrl = async () => {
try {
// Google's connectivity check URL
const testUrl = "http://connectivitycheck.gstatic.com/generate_202";
const response = await fetch(testUrl, {
method: "GET",
redirect: "manual",
});
// If status is 204, no captive portal
if (response.status === 204) {
await logToStorage("No captive portal detected.");
return null;
}
// If redirected, get the Location header (captive portal URL)
if (response.status >= 300 && response.status < 400) {
const portalUrl = response.headers.get("Location");
await logToStorage(`Captive portal detected: ${portalUrl}`);
return portalUrl;
}
// Some captive portals return 200 with HTML content
if (response.status === 200) {
const text = await response.text();
// Try to extract a URL from the HTML (very basic)
// Try to extract a URL from window.location assignment in HTML
const match = text.match(/window\.location\s*=\s*["']([^"']+)["']/i);
if (match && match[1]) {
await logToStorage(`Captive portal JS redirect: ${match[1]}`);
return match[1];
}
// Fallback: Try meta refresh
const metaMatch = text.match(/<meta[^>]+url=['"]?([^'">]+)/i);
if (metaMatch && metaMatch[1]) {
await logToStorage(`Captive portal meta redirect: ${metaMatch[1]}`);
return metaMatch[1];
}
await logToStorage("Captive portal detected, but URL not found in HTML.");
return null;
}
await logToStorage(`Unexpected response: ${response.status}`);
return null;
} catch (error) {
await logToStorage(`Error detecting captive portal: ${error}`);
return null;
}
};
const submitted = async () => {
if (await verifyInfo()) {
writeInfo();
forceLogout();
forceLogin(false);
}
}
const viewLogs = async () => {
const { getItem } = useAsyncStorage('logs');
const logs = JSON.parse(await getItem()) || [];
Alert.alert("Logs", logs.map(log => log.message).join('\n\n'));
}
useEffect(() => {
readAll();
if (toggle) {
listener = (addEventListener(state => {
if (state.type == "wifi" && ((lastLogin.getTime() + 1 * 60 * 60 * 1000) <= Date.now())) {
forceLogin(true);
} else {
logToStorage(`Stopped. Recently logged in;`);
}
}));
}
registerBackgroundFetchAsync().catch(async error => {
await logToStorage(`Failed to register background fetch task: ${error}`);
});
}, []);
const triggerTask = async () => {
await BackgroundTask.triggerTaskWorkerForTestingAsync();
};
return (
<>
<SafeAreaView style={{ flex: 1 }}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}
accessible={false}>
<View style={styles.container}>
<View style={{ display: "flex", flexDirection: "row", justifyContent: "space-between", width: "100%", paddingLeft: 15, paddingRight: 15, paddingTop: 15, alignItems: "center" }}>
<Text style={{ color: "#878787", fontSize: 18, paddingLeft: 5 }} onPress={viewLogs}>{toggle ? "WiFixing" : "Not WiFixing"} {lastLogin.toLocaleString('en-GB', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })}</Text>
<Switch trackColor={{ false: '#ddd', true: '#fff' }}
thumbColor={toggle ? '#2e8bc0' : '#0c2d48'}
ios_backgroundColor="#3e3e3e"
onValueChange={tapToggle}
value={toggle} style={styles.switch} />
</View>
<Image source={require("./assets/mainIcon.png")} style={styles.icon} />
<View style={styles.form}>
<Text style={{ color: "#fff", marginBottom: 5, fontSize: 16 }}>Username</Text>
<TextInput
style={styles.input}
onChangeText={setUserValue}
defaultValue={user}
/>
<Text style={{ color: "#fff", marginBottom: 5, fontSize: 16 }}>Password</Text>
<View style={styles.passContainer}>
<TextInput
// placeholder='_________________'
onChangeText={setPassValue}
secureTextEntry={!showPass}
defaultValue={pass}
style={{ color: "#fff", width: "80%", fontSize: 15 }}
/>
<MaterialCommunityIcons
name={showPass ? 'eye-off' : 'eye'}
size={24}
color="#aaa"
style={styles.icon}
onPress={toggleShowPassword}
/>
</View>
<Button title="Connect" onPress={submitted} style={styles.sub} color="#2e8bc0" />
<Text style={{color: "#878787", paddingTop: "6", alignSelf: "center"}}><AntDesign name="infocirlceo" size={15} color="#878787" /> Lock the app in recent tasks</Text>
</View>
<View style={styles.footer}>
<TouchableOpacity onPress={() => Linking.openURL("https://www.linkedin.com/in/mathewmanachery/")}>
<Text style={styles.footerText}>Developed by Mathew Manachery</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => Linking.openURL("https://www.linkedin.com/in/muhammed-basil-5b1144326/")}>
<Text style={styles.footerText}>Logo by Muhammed Basil</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => Linking.openURL("https://github.com/mathew2103/wifix")} style={{ justifyContent: "center", display: "flex", alignItems: "center", flexDirection: "row" }}>
<Text style={styles.footerText}>Version {APP_VERSION}</Text>
<AntDesign color="white" size={16} name='github' style={{ alignContent: "center", alignSelf: "center", paddingLeft: 5 }} />
</TouchableOpacity>
</View>
<StatusBar backgroundColor='#000' barStyle='light-content' />
</View>
</TouchableWithoutFeedback>
<ToastManager theme='dark' duration={2500} topOffset={55}/>
</SafeAreaView>
</>
);
}
const styles = StyleSheet.create({
icon: {
borderRadius: 5,
maxHeight: 150,
resizeMode: "contain",
maxWidth: 150,
},
footer: {
flex: 0.2,
justifyContent: "center",
},
footerText: {
color: "#fff",
alignSelf: "center",
marginBottom: 2,
textAlign: "center",
paddingTop: 1
},
form: {
flex: 0.6
},
lastRun: {
flex: 0.4,
justifyContent: "center"
},
sub: {
margin: 50
},
container: {
backgroundColor: '#000',
alignItems: 'center',
justifyContent: "space-between",
flex: 1
},
input: {
backgroundColor: '#000',
color: "#fff",
borderRadius: 8,
paddingHorizontal: 14,
width: 200,
height: 50,
marginBottom: 25,
shadowColor: "#2e8bc0",
elevation: 10,
borderWidth: 0.9,
borderColor: "#2e8bc0", fontSize: 15
},
passContainer: {
marginBottom: 50,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
backgroundColor: '#000',
color: "#fff",
borderRadius: 8,
paddingHorizontal: 10,
width: 200,
height: 50,
shadowColor: "#2e8bc0",
elevation: 10,
borderWidth: 0.9,
borderColor: "#2e8bc0", fontSize: 16
}
});