41 lines
1.3 KiB
Python
41 lines
1.3 KiB
Python
"""نرمالسازی شماره موبایل ایرانی برای سرویسهای پیامک."""
|
|
from persiantools import digits
|
|
|
|
|
|
def _clean(raw):
|
|
if raw is None:
|
|
return ""
|
|
text = str(raw).strip()
|
|
if not text:
|
|
return ""
|
|
# تبدیل ارقام فارسی/عربی به انگلیسی و حذف هر کاراکتر غیررقمی (بهجز +).
|
|
text = digits.fa_to_en(digits.ar_to_fa(text))
|
|
return "".join(ch for ch in text if ch.isdigit() or ch == "+")
|
|
|
|
|
|
def normalize_mobile(raw):
|
|
"""شماره را به شکل یکنواخت ``+989xxxxxxxxx`` برمیگرداند؛ نامعتبر ⇒ رشته خالی."""
|
|
text = _clean(raw)
|
|
if not text:
|
|
return ""
|
|
if text.startswith("+"):
|
|
text = text[1:]
|
|
if text.startswith("0098"):
|
|
text = text[4:]
|
|
elif text.startswith("98") and len(text) == 12:
|
|
text = text[2:]
|
|
elif text.startswith("0"):
|
|
text = text[1:]
|
|
|
|
if len(text) != 10 or not text.startswith("9"):
|
|
return ""
|
|
return f"+98{text}"
|
|
|
|
|
|
def to_local(raw):
|
|
"""شماره را به شکل محلی ``09xxxxxxxxx`` برمیگرداند (لازمِ برخی وبسرویسها)."""
|
|
normalized = normalize_mobile(raw)
|
|
if not normalized:
|
|
return ""
|
|
return "0" + normalized[3:]
|