Repository navigation
Expand file tree
/
Copy pathmdac.py
More file actions
600 lines (513 loc) · 18.7 KB
/
Copy pathmdac.py
File metadata and controls
600 lines (513 loc) · 18.7 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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
import os
import random
import time
from enum import Enum
from dataclasses import dataclass
from datetime import datetime, timedelta
import httpx
from bs4 import BeautifulSoup
from pydantic import BaseModel, EmailStr, Field, field_validator, ConfigDict
class Country(Enum):
"""Common country codes for nationality and embarkation point."""
# ASEAN Countries
SINGAPORE = "SGP"
MALAYSIA = "MYS"
INDONESIA = "IDN"
THAILAND = "THA"
PHILIPPINES = "PHL"
VIETNAM = "VNM"
BRUNEI = "BRN"
MYANMAR = "MMR"
CAMBODIA = "KHM"
LAOS = "LAO"
# Major Travel Origins
CHINA = "CHN"
HONG_KONG = "HKG"
TAIWAN = "TWN"
JAPAN = "JPN"
SOUTH_KOREA = "KOR"
INDIA = "IND"
AUSTRALIA = "AUS"
NEW_ZEALAND = "NZL"
# Europe
UNITED_KINGDOM = "GBR"
GERMANY = "DGR"
FRANCE = "FRA"
ITALY = "ITA"
SPAIN = "ESP"
NETHERLANDS = "NLD"
SWITZERLAND = "CHE"
AUSTRIA = "AUT"
BELGIUM = "BEL"
DENMARK = "DNK"
SWEDEN = "SWE"
NORWAY = "NOR"
FINLAND = "FIN"
POLAND = "POL"
CZECH_REPUBLIC = "CZE"
# Middle East
SAUDI_ARABIA = "SAU"
UAE = "ARE"
QATAR = "QAT"
KUWAIT = "KWT"
BAHRAIN = "BHR"
OMAN = "OMN"
ISRAEL = "ISR"
TURKEY = "TUR"
IRAN = "IRN"
# Americas
USA = "USA"
CANADA = "CAN"
MEXICO = "MEX"
BRAZIL = "BRA"
ARGENTINA = "ARG"
# Africa
SOUTH_AFRICA = "ZAF"
EGYPT = "EGY"
NIGERIA = "NGA"
KENYA = "KEN"
# Others
RUSSIA = "RUS"
BANGLADESH = "BGD"
PAKISTAN = "PAK"
SRI_LANKA = "LKA"
NEPAL = "NPL"
class Gender(Enum):
MALE = "1"
FEMALE = "2"
class TravelMode(Enum):
AIR = "1"
LAND = "2"
SEA = "3"
class AccommodationType(Enum):
HOTEL = "01"
FRIENDS_RELATIVES = "02"
OTHERS = "99"
class State(Enum):
JOHOR = "01"
KEDAH = "02"
KELANTAN = "03"
MELAKA = "04"
NEGERI_SEMBILAN = "05"
PAHANG = "06"
PULAU_PINANG = "07"
PERAK = "08"
PERLIS = "09"
SELANGOR = "10"
TERENGGANU = "11"
SABAH = "12"
SARAWAK = "13"
WP_KUALA_LUMPUR = "14"
WP_LABUAN = "15"
WP_PUTRAJAYA = "16"
@dataclass(frozen=True)
class AccommodationData:
accommodation_type: AccommodationType
address1: str
state: State
postcode: str
city: str
class AccommodationPreset(Enum):
NETWORK_SCHOOL = AccommodationData(
accommodation_type=AccommodationType.HOTEL,
address1="FOREST CITY MARINA HOTEL",
state=State.JOHOR,
postcode="81550",
city="0113",
)
class Person(BaseModel):
name: str
passport_number: str
date_of_birth: str # DD/MM/YYYY
nationality: Country | str
gender: Gender
passport_expiry: str # DD/MM/YYYY
email: EmailStr
phone_region: str = "49"
phone_number: str
@field_validator("date_of_birth", "passport_expiry")
@classmethod
def validate_date_format(cls, v: str) -> str:
"""Validate date is in DD/MM/YYYY format."""
try:
datetime.strptime(v, "%d/%m/%Y")
return v
except ValueError:
raise ValueError(f"Date must be in DD/MM/YYYY format, got: {v}")
class Trip(BaseModel):
arrival_date: str | None = None # DD/MM/YYYY, if None uses today
length_of_stay_days: int = 30
embarkation_point: Country | str = Country.SINGAPORE
vessel_name: str = "BUS"
travel_mode: TravelMode = TravelMode.LAND
accommodation: AccommodationPreset = AccommodationPreset.NETWORK_SCHOOL
@field_validator("arrival_date")
@classmethod
def validate_date_format(cls, v: str | None) -> str | None:
"""Validate date is in DD/MM/YYYY format if provided."""
if v is None:
return v
try:
datetime.strptime(v, "%d/%m/%Y")
return v
except ValueError:
raise ValueError(f"Date must be in DD/MM/YYYY format, got: {v}")
class MdacRegistrationData(BaseModel):
"""Pydantic model for MDAC (Malaysia Digital Arrival Card) registration data."""
mdac_visa_country: str = Field(default="ALL", alias="mdacVisaCountry")
hd_curr_lang: str = Field(default="ms", alias="hdCurrLang")
name: str
pass_no: str = Field(alias="passNo")
dob: str # Format: DD/MM/YYYY
nationality: str
sex: str # "1" for male, "2" for female
pass_exp_dte: str = Field(alias="passExpDte") # Format: DD/MM/YYYY
email: EmailStr
confirm_email: EmailStr = Field(alias="confirmEmail")
region: str
mobile: str
arr_dt: str = Field(alias="arrDt") # Arrival date, format: DD/MM/YYYY
dep_dt: str = Field(alias="depDt") # Departure date, format: DD/MM/YYYY
vessel_nm: str = Field(alias="vesselNm")
trvl_mode: str = Field(alias="trvlMode") # Travel mode code
embark: str # Embarkation point code
accommodation_stay: str = Field(alias="accommodationStay")
accommodation_address1: str = Field(alias="accommodationAddress1")
accommodation_address2: str | None = Field(
default="", alias="accommodationAddress2"
)
accommodation_state: str = Field(alias="accommodationState")
accommodation_postcode: str = Field(alias="accommodationPostcode")
accommodation_city: str = Field(alias="accommodationCity")
submit_registration: str = Field(default="Submit", alias="submitRegistration")
source_page: str | None = Field(default=None, alias="_sourcePage")
fp: str | None = Field(default=None, alias="__fp")
g_recaptcha_response: str | None = Field(default=None, alias="g-recaptcha-response")
@field_validator("email", "confirm_email")
@classmethod
def emails_match(cls, v, info):
"""Ensure email and confirmEmail match if both are present."""
if info.field_name == "confirm_email":
email = info.data.get("email")
if email and v != email:
raise ValueError("Email addresses must match")
return v
def set_accommodation(self, preset: AccommodationPreset) -> None:
"""Set accommodation fields from a preset."""
data = preset.value
self.accommodation_stay = data.accommodation_type.value
self.accommodation_address1 = data.address1
self.accommodation_state = data.state.value
self.accommodation_postcode = data.postcode
self.accommodation_city = data.city
model_config = ConfigDict(populate_by_name=True)
class MdacSession:
"""Container for MDAC session data."""
def __init__(
self,
cookies: dict,
source_page: str,
fp: str,
recaptcha_sitekey: str | None = None,
):
self.cookies = cookies
self.source_page = source_page
self.fp = fp
self.recaptcha_sitekey = recaptcha_sitekey
def solve_recaptcha(
api_key: str, site_key: str, page_url: str, timeout: float = 120.0
) -> str:
"""Solve reCAPTCHA v2 using 2captcha service."""
with httpx.Client(timeout=timeout, verify=False) as client:
print("Submitting CAPTCHA to 2captcha...")
response = client.get(
"http://2captcha.com/in.php",
params={
"key": api_key,
"method": "userrecaptcha",
"googlekey": site_key,
"pageurl": page_url,
"json": 1,
},
)
result = response.json()
if result.get("status") != 1:
raise ValueError(f"Failed to submit CAPTCHA: {result.get('request')}")
captcha_id = result["request"]
print(f"CAPTCHA ID: {captcha_id}, waiting for solution...")
start_time = time.time()
while time.time() - start_time < timeout:
time.sleep(5)
response = client.get(
"http://2captcha.com/res.php",
params={"key": api_key, "action": "get", "id": captcha_id, "json": 1},
)
result = response.json()
if result.get("status") == 1:
print("✓ CAPTCHA solved!")
return result["request"]
elif result.get("request") != "CAPCHA_NOT_READY":
raise ValueError(f"CAPTCHA solving failed: {result.get('request')}")
raise ValueError(f"CAPTCHA solving timed out after {timeout} seconds")
def get_random_headers(for_form_submission: bool = False) -> dict[str, str]:
"""Generate randomized HTTP headers to avoid fingerprinting."""
chrome_versions = [
"120.0.0.0",
"121.0.0.0",
"122.0.0.0",
"130.0.0.0",
"142.0.0.0",
"143.0.0.0",
]
os_versions = ["10_15_7", "11_0_0", "12_0_0", "13_0_0", "14_0_0"]
languages = [
"en-US,en;q=0.9",
"en-GB,en;q=0.8",
"en-US,en;q=0.9,es;q=0.8",
"en-GB,en;q=0.7",
"en-US,en;q=0.8",
]
chrome_ver = random.choice(chrome_versions)
os_ver = random.choice(os_versions)
lang = random.choice(languages)
headers = {
"User-Agent": f"Mozilla/5.0 (Macintosh; Intel Mac OS X {os_ver}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{chrome_ver} Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": lang,
"Connection": "keep-alive",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none" if not for_form_submission else "same-origin",
"Sec-Fetch-User": "?1",
"Upgrade-Insecure-Requests": "1",
}
if for_form_submission:
chrome_major = chrome_ver.split(".")[0]
headers.update(
{
"Cache-Control": "max-age=0",
"Host": "imigresen-online.imi.gov.my",
"Referer": "https://imigresen-online.imi.gov.my/mdac/main?registerMain",
"Sec-CH-UA": f'"Chromium";v="{chrome_major}", "Brave";v="{chrome_major}", "Not_A Brand";v="99"',
"Sec-CH-UA-Mobile": "?0",
"Sec-CH-UA-Platform": '"macOS"',
"Sec-GPC": "1",
}
)
return headers
def get_mdac_session(timeout: float = 30.0) -> MdacSession:
"""
Fetch a fresh MDAC session by visiting the registration form page.
This extracts the required CSRF tokens (_sourcePage and __fp) and session cookies
that are needed for form submission.
Args:
timeout: Request timeout in seconds (default: 30.0)
Returns:
MdacSession object containing cookies and security tokens
Raises:
ValueError: If the tokens cannot be extracted from the form page
httpx.HTTPError: If the request fails
"""
form_url = "https://imigresen-online.imi.gov.my/mdac/main?registerMain"
headers = get_random_headers(for_form_submission=False)
with httpx.Client(timeout=timeout, follow_redirects=True, verify=False) as client:
response = client.get(form_url, headers=headers)
response.raise_for_status()
cookies = dict(response.cookies)
soup = BeautifulSoup(response.text, "html.parser")
source_page_input = soup.find("input", {"name": "_sourcePage"})
fp_input = soup.find("input", {"name": "__fp"})
if not source_page_input or not fp_input:
raise ValueError(
"Could not find required security tokens (_sourcePage or __fp) in form page"
)
source_page_value = str(source_page_input.get("value", ""))
fp_value = str(fp_input.get("value", ""))
if not source_page_value or not fp_value:
raise ValueError("Security tokens are empty")
recaptcha_element = soup.find("div", {"class": "g-recaptcha"})
recaptcha_sitekey = None
if recaptcha_element:
sitekey_value = recaptcha_element.get("data-sitekey")
if sitekey_value:
recaptcha_sitekey = str(sitekey_value)
print(f"⚠ reCAPTCHA detected! Site key: {recaptcha_sitekey}")
return MdacSession(
cookies=cookies,
source_page=source_page_value,
fp=fp_value,
recaptcha_sitekey=recaptcha_sitekey,
)
def submit_mdac_registration(
registration_data: MdacRegistrationData,
session: MdacSession | None = None,
timeout: float = 30.0,
auto_fetch_session: bool = True,
twocaptcha_api_key: str | None = None,
) -> httpx.Response:
"""
Submit MDAC registration to the Malaysian Immigration Department.
If session tokens (_sourcePage, __fp) are not provided in registration_data,
they will be automatically fetched by visiting the form page first (if auto_fetch_session=True).
Args:
registration_data: Pydantic model containing all registration fields
session: Optional MdacSession with cookies and tokens. If None and auto_fetch_session=True,
will be fetched automatically
timeout: Request timeout in seconds (default: 30.0)
auto_fetch_session: If True and tokens are missing, automatically fetch a fresh session
twocaptcha_api_key: Optional 2captcha API key for automatic CAPTCHA solving
Returns:
httpx.Response object containing the server response
Raises:
ValueError: If tokens are missing and auto_fetch_session=False
Example:
>>> # Automatic mode (recommended) - tokens fetched automatically
>>> data = MdacRegistrationData(
... name="JOHN DOE",
... passNo="A12345678",
... dob="01/01/1990",
... nationality="USA",
... sex="1",
... passExpDte="01/01/2030",
... email="john.doe@example.com",
... confirmEmail="john.doe@example.com",
... region="49",
... mobile="1234567890",
... arrDt="05/11/2025",
... depDt="15/11/2025",
... vesselNm="BUS",
... trvlMode="2",
... embark="SGP",
... accommodationStay="01",
... accommodationAddress1="SOME HOTEL",
... accommodationState="01",
... accommodationPostcode="81550",
... accommodationCity="0113",
... )
>>> response = submit_mdac_registration(data)
>>> print(response.status_code)
>>> # Manual mode - fetch session first, then submit
>>> session = get_mdac_session()
>>> data.source_page = session.source_page
>>> data.fp = session.fp
>>> response = submit_mdac_registration(data, session=session)
"""
url = "https://imigresen-online.imi.gov.my/mdac/register"
form_url = "https://imigresen-online.imi.gov.my/mdac/main?registerMain"
if not r
8000
egistration_data.source_page or not registration_data.fp:
if auto_fetch_session:
print("Fetching fresh session tokens...")
session = get_mdac_session(timeout=timeout)
registration_data.source_page = session.source_page
registration_data.fp = session.fp
else:
raise ValueError(
"Missing required tokens (_sourcePage or __fp). "
"Either provide them or set auto_fetch_session=True"
)
if (
session
and session.recaptcha_sitekey
and not registration_data.g_recaptcha_response
):
if twocaptcha_api_key:
registration_data.g_recaptcha_response = solve_recaptcha(
api_key=twocaptcha_api_key,
site_key=session.recaptcha_sitekey,
page_url=form_url,
timeout=timeout,
)
else:
print(
"⚠ Warning: reCAPTCHA detected but no API key provided. Submission may fail."
)
cookies = session.cookies if session else {}
form_data = registration_data.model_dump(by_alias=True, exclude_none=True)
headers = get_random_headers(for_form_submission=True)
with httpx.Client(timeout=timeout, follow_redirects=True, verify=False) as client:
response = client.post(
url,
data=form_data,
headers=headers,
cookies=cookies,
)
return response
def submit_mdac_simple(
person: Person,
trip: Trip,
timeout: float = 30.0,
) -> httpx.Response:
"""
Simplified wrapper for MDAC registration submission.
Automatically reads 2captcha API key from TWOC_API_KEY environment variable.
Args:
person: Person details (name, passport, email, etc.)
trip: Trip details (dates, accommodation, travel mode)
timeout: Request timeout in seconds (default: 30.0)
Returns:
httpx.Response object containing the server response
Raises:
ValueError: If TWOC_API_KEY environment variable is not set
Example:
>>> person = Person(
... name="JOHN DOE",
... passport_number="A12345678",
... date_of_birth="01/01/1990",
... nationality="USA",
... sex="1",
... passport_expiry="01/01/2030",
... email="john@example.com",
... phone_number="1234567890",
... )
>>> trip = Trip(length_of_stay_days=30)
>>> response = submit_mdac_simple(person, trip)
"""
twocaptcha_api_key = os.getenv("TWOC_API_KEY")
if not twocaptcha_api_key:
raise ValueError("TWOC_API_KEY environment variable is not set")
if trip.arrival_date:
arr_dt = datetime.strptime(trip.arrival_date, "%d/%m/%Y")
else:
arr_dt = datetime.now()
arr_date = arr_dt.strftime("%d/%m/%Y")
dep_dt = arr_dt + timedelta(days=trip.length_of_stay_days)
dep_date = dep_dt.strftime("%d/%m/%Y")
accom = trip.accommodation.value
nationality_code = (
person.nationality.value
if isinstance(person.nationality, Country)
else person.nationality
)
embark_code = (
trip.embarkation_point.value
if isinstance(trip.embarkation_point, Country)
else trip.embarkation_point
)
registration_data = MdacRegistrationData( # type: ignore
name=person.name,
pass_no=person.passport_number,
dob=person.date_of_birth,
nationality=nationality_code,
sex=person.gender.value,
pass_exp_dte=person.passport_expiry,
email=person.email,
confirm_email=person.email,
region=person.phone_region,
mobile=person.phone_number,
arr_dt=arr_date,
dep_dt=dep_date,
vessel_nm=trip.vessel_name,
trvl_mode=trip.travel_mode.value,
embark=embark_code,
accommodation_stay=accom.accommodation_type.value,
accommodation_address1=accom.address1,
accommodation_state=accom.state.value,
accommodation_postcode=accom.postcode,
accommodation_city=accom.city,
)
return submit_mdac_registration(
registration_data,
twocaptcha_api_key=twocaptcha_api_key,
timeout=timeout,
)