summaryrefslogtreecommitdiff
path: root/scripts/create-mcc-mnc-table.py
blob: c7afb56d7832ae2fecb77977e28df02a520586ce (plain)
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
#!/usr/bin/env python3

"""
Generates MTS_IO_MccMncTable.cpp file by pulling latest MCC/MNC values
from http://mcc-mnc.com or the csv file.

Original Source Idea: https://github.com/musalbas/mcc-mnc-table
"""

########################################################################################################################

import re
import urllib.request
import urllib.parse
import datetime
import csv
import argparse

from typing import Iterable, Generator, Optional, TextIO
from collections import namedtuple

########################################################################################################################

PREAMBLE_TEMPLATE = """\
/*
 * Copyright (C) 2015 by Multi-Tech Systems
 *
 * This file is part of libmts-io.
 *
 * libmts-io is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * libmts-io is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with libmts-io.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*!
 \\file MTS_IO_MccMncTable.cpp
 \\brief Auto-Generated MCC-MNC Lookup Table
 \\date {today}
 \\author sgodinez

 An Auto-Generated MCC-MNC Lookup Table
*/
"""

GENERAL_CODE = """\
#include <mts/MTS_IO_MccMncTable.h>
#include <mts/MTS_Logger.h>
#include <mts/MTS_Text.h>

using namespace MTS::IO;

MTS::AutoPtr<MTS::Lock> MccMncTable::m_apLock(new MTS::Lock());
MccMncTable* MccMncTable::m_pInstance = NULL;

MccMncTable* MccMncTable::getInstance() {
    if(m_pInstance == NULL) {
        m_apLock->lock();
        if (m_pInstance == NULL) {
            m_pInstance = new MccMncTable();
        }
        m_apLock->unlock();
    }
    return m_pInstance;
}

MccMncTable::MccMncTable() {
    createTable();
}

Json::Value MccMncTable::lookup(const std::string& sMcc, const std::string& sMnc) {
    uint32_t iMcc, iMnc;
    std::string sNormalizedMnc = sMnc;
    printTrace("[MCCMNC] MCCx[%s] MNCx[%s]", sMcc.c_str(), sMnc.c_str());
    if (sMnc.length() == 2) {
        sNormalizedMnc += 'f';
    }
    if (!MTS::Text::parseHex(iMcc, sMcc)) { return Json::Value::null; }
    if (!MTS::Text::parseHex(iMnc, sNormalizedMnc)) { return Json::Value::null; }
    printTrace("[MCCMNC] MCC0X[%d] MNC0X[%d]", iMcc, iMnc);
    if (m_mTable.count(iMcc)) {
        if(m_mTable[iMcc].count(iMnc)) {
            std::vector<std::string> vJson = MTS::Text::split(m_mTable[iMcc][iMnc], ',');
            Json::Value j;
            j["iso"] = vJson[0];
            j["country"] = vJson[1];
            j["code"] = vJson[2];
            j["carrier"] = vJson[3];
            j["carrierCode"] = vJson[4];
            return j;
        }
    }

    return Json::Value::null;
}
"""

########################################################################################################################

MccMncElement = namedtuple(
    'MccMncData',
    field_names=('mcc', 'mcc_int', 'mnc', 'mnc_int', 'iso', 'country', 'country_code', 'carrier', 'carrier_code')
)


########################################################################################################################

def init_argparse() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description='Generate MCC/MNC table file from Website or CSV')
    parser.add_argument('-w', '--website', action='store_true')
    parser.add_argument('-c', '--csv', type=str)
    parser.add_argument('-t', '--target', type=str, default='-')
    return parser


def print_cpp_preamble(*, target: Optional[TextIO] = None) -> None:
    print(PREAMBLE_TEMPLATE.format(today=datetime.date.today()), file=target)


def print_cpp_general_code(*, target: Optional[TextIO] = None) -> None:
    print(GENERAL_CODE, file=target)


def format_mcc_mnc_line(el: MccMncElement) -> str:
    if el.mnc.upper() != "N/A":
        return '    m_mTable[{mcc_int}][{mnc_int}] = "{iso},{country},{country_code},{carrier},{carrier_code}";'.format(
            mcc_int=el.mcc_int,
            mnc_int=el.mnc_int,
            iso=el.iso,
            country=el.country,
            country_code=el.country_code,
            carrier=el.carrier,
            carrier_code=el.carrier_code
        )
    else:
        # TODO: The Country and Country Code values were swapped in the original implementation due to a bug.
        # Left as is for compatibility reasons.
        return '    //MCC({mcc}) MNC(N/A) ISO({iso}) Country Code({country}) Country({country_code}) Carrier({carrier}) Carrier Code({carrier_code})'.format(
            mcc=el.mcc,
            iso=el.iso,
            country=el.country,
            country_code=el.country_code,
            carrier=el.carrier,
            carrier_code=el.carrier_code
        )


def print_cpp_mcc_mnc_create_table(source: Iterable[MccMncElement], *, target: Optional[TextIO] = None) -> None:
    print("void MccMncTable::createTable() {", file=target)
    print("    std::string sData;", file=target)

    for el in source:
        print(format_mcc_mnc_line(el), file=target)

    print("}", file=target)
    print("", file=target)


def print_cpp(source: Iterable[MccMncElement], *, target: Optional[TextIO] = None) -> None:
    print_cpp_preamble(target=target)
    print_cpp_general_code(target=target)
    print_cpp_mcc_mnc_create_table(source, target=target)


def mcc_to_mcc_int(src: str) -> str:
    if src.upper() == "N/A":
        return src

    hash_ = int(src, 16)
    return "{:d}".format(hash_)


def mnc_to_mnc_int(src: str) -> str:
    if src.upper() == "N/A":
        return src

    src_norm = src
    if len(src) == 2:
        src_norm += 'f'

    hash_ = int(src_norm, 16)
    return "{:d}".format(hash_)


def mcc_mnc_from_website(url: str) -> Generator[MccMncElement, None, None]:
    td_re = re.compile('<td>([^<]*)</td>' * 6)
    html_bytes = urllib.request.urlopen(url).read()  # type: bytes
    html = html_bytes.decode(encoding='utf-8')

    tbody_start = False

    for line in html.split('\n'):
        if '<tbody>' in line:
            tbody_start = True
        elif '</tbody>' in line:
            break
        elif tbody_start:
            td_search = td_re.search(line)
            mcc = td_search.group(1).strip().replace(',', '')
            mnc = td_search.group(2).strip().replace(',', '')
            iso = td_search.group(3).strip().replace(',', '')
            country = td_search.group(4).strip().replace(',', '')
            country_code = td_search.group(5).strip().replace(',', '')
            carrier = td_search.group(6).strip().replace(',', '')

            mcc_int = mcc_to_mcc_int(mcc)
            mnc_int = mnc_to_mnc_int(mnc)

            yield MccMncElement(
                mcc=mcc,
                mcc_int=mcc_int,
                mnc=mnc,
                mnc_int=mnc_int,
                iso=iso,
                country=country,
                country_code=country_code,
                carrier=carrier,
                carrier_code=""  # Multitech-specific, not populated from this source
            )


def mcc_mnc_from_csv(path: str) -> Generator[MccMncElement, None, None]:
    with open(path) as f:
        csv_reader = csv.DictReader(f)
        for row in csv_reader:
            mcc = row['MCC']
            mnc = row['MNC']
            iso = row['ISO']
            country = row['Country']
            country_code = row['Country Code']
            carrier = row['Carrier']
            carrier_code = row['Carrier Code']

            mcc_int = mcc_to_mcc_int(mcc)
            mnc_int = mnc_to_mnc_int(mnc)

            yield MccMncElement(
                mcc=mcc,
                mcc_int=mcc_int,
                mnc=mnc,
                mnc_int=mnc_int,
                iso=iso,
                country=country,
                country_code=country_code,
                carrier=carrier,
                carrier_code=carrier_code
            )


########################################################################################################################

def main() -> int:
    parser = init_argparse()
    args = parser.parse_args()

    if (args.csv is not None) and args.website:
        parser.error('Only one source can be used at a time.')
        return 1

    if args.csv is None:
        source = mcc_mnc_from_website('http://mcc-mnc.com/')
    else:
        source = mcc_mnc_from_csv(args.csv)

    if args.target == '-':
        # Print to stdout
        print_cpp(source, target=None)
    else:
        # Print to file
        with open(args.target, 'w') as f:
            print_cpp(source, target=f)

    return 0


########################################################################################################################

if __name__ == "__main__":
    ret = main()
    exit(ret)