#!/usr/bin/env python3 """ Restores the original data that was used to populate the 'MTS_IO_MccMncTable.cpp' file. Stores the result in a .csv file. """ ######################################################################################################################## import re import csv import argparse from typing import Dict, Iterable, Generator ######################################################################################################################## def init_argparse() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description='Generate MCC/MNC table file from Website or CSV') parser.add_argument('source', type=str) parser.add_argument('target', type=str) return parser def mcc_int_to_mcc(src: str) -> str: hash_ = int(src) return "{:03x}".format(hash_) def mnc_int_to_mnc(src: str) -> str: hash_ = int(src) hash_str = "{:03x}".format(hash_) if hash_ & 0xf != 0xf: return hash_str else: return hash_str[:-1] def parse_code_line(line: str) -> Dict[str, str]: left, right = line.split(' = ') mcc_int, mnc_int = re.findall(r'\[(\d+)\]', left) info = re.findall(r'"(.+)"', right)[0] iso, country, country_code, carrier = info.split(',') mcc = mcc_int_to_mcc(mcc_int) mnc = mnc_int_to_mnc(mnc_int) return { 'MCC': mcc, 'MNC': mnc, 'ISO': iso, 'Country': country, 'Country Code': country_code, 'Carrier': carrier } def parse_comment_line(line: str) -> Dict[str, str]: match = re.search( r'MCC\((.*)\) MNC\((.*)\) ISO\((.*)\) Country Code\((.*)\) Country\((.*)\) Carrier\((.*)\)', line ) # NOTE: The original file contains values of the "Code" and "Country" fields swapped. mcc, mnc, iso, country, country_code, carrier = match.groups() return { 'MCC': mcc, 'MNC': mnc, 'ISO': iso, 'Country': country, 'Country Code': country_code, 'Carrier': carrier } def mcc_mnc_from_cpp(src: str) -> Generator[Dict[str, str], None, None]: with open(src) as f: for line in f: if line.startswith(" //MCC"): yield parse_comment_line(line) elif line.startswith(" m_mTable["): yield parse_code_line(line) def write_mcc_mnc_to_scv(data: Iterable[Dict[str, str]], target: str) -> None: with open(target, 'w') as f: fieldnames = ['MCC', 'MNC', 'ISO', 'Country', 'Country Code', 'Carrier'] writer = csv.DictWriter(f, fieldnames, delimiter=',', quotechar='"', lineterminator='\n', quoting=csv.QUOTE_ALL) writer.writeheader() for d in data: writer.writerow(d) ######################################################################################################################## def main() -> int: parser = init_argparse() args = parser.parse_args() data = mcc_mnc_from_cpp(args.source) write_mcc_mnc_to_scv(data, args.target) return 0 ######################################################################################################################## if __name__ == "__main__": ret = main() exit(ret)