Files
op-packages/luci-app-wwand/tools/gen-mccmnc.py
T

86 lines
3.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""Regenerate htdocs/luci-static/resources/wwand/mccmnc.js.
Sources:
- https://raw.githubusercontent.com/musalbas/mcc-mnc-table/master/mcc-mnc-table.json
(ITU E.212 national assignments)
- https://en.wikipedia.org/wiki/Mobile_country_code (International operators:
MCC 901/902/991 -- the musalbas table only carries a handful of these)
Usage: gen-mccmnc.py <mcc-mnc-table.json> <mcc-wikipedia.html> > mccmnc.js
"""
import json, re, sys, html
table = json.load(open(sys.argv[1], encoding='utf-8'))
wiki = open(sys.argv[2], encoding='utf-8').read()
db = {} # mcc -> { '_c': country, mnc: name }
def put(mcc, mnc, name, country):
if not name:
return
m = db.setdefault(mcc, {})
if country and '_c' not in m:
m['_c'] = country
m.setdefault(mnc, name)
for e in table:
net = (e.get('network') or '').strip()
if e['mcc'] in ('901', '902', '991'):
continue # replaced wholesale by the Wikipedia international table
put(e['mcc'], e['mnc'], net, (e.get('country') or '').strip())
# international operators from the Wikipedia tables (brand preferred)
rows = re.findall(r'<tr>(.*?)</tr>', wiki, re.S)
strip = lambda c: html.unescape(re.sub(r'<[^>]+>', '', c)).strip()
for r in rows:
cells = re.findall(r'<t[dh][^>]*>(.*?)</t[dh]>', r, re.S)
if len(cells) < 4:
continue
mcc, mnc, brand, op = (strip(c) for c in cells[:4])
if mcc not in ('901', '902', '991') or not re.match(r'^[0-9]+$', mnc or ''):
continue
name = brand if brand else op
if brand and op and brand != op:
name = '%s (%s)' % (brand, op)
put(mcc, mnc, name, 'International')
# field knowledge: Telenor Maritime (ex MCP) is what cruise passengers see
if '12' in db.get('901', {}):
db['901']['12'] = 'Telenor Maritime / AIDA Cruises'
out = json.dumps(db, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
print("'use strict';")
print("'require baseclass';")
print()
print("/* MCC/MNC -> operator-name database. GENERATED by tools/gen-mccmnc.py")
print(" from the musalbas/mcc-mnc-table dump (ITU E.212) plus the Wikipedia")
print(" international-operators table (MCC 901/902/991). Do not edit by hand")
print(" -- rerun the generator. Layout: MCC -> { _c: country, MNC: name }. */")
print('var DB = %s;' % out)
print('''
return baseclass.extend({
/* operator name for an mcc/mnc (numbers or strings; 2- and 3-digit MNC
forms are both tried) -- null when unknown */
name: function(mcc, mnc) {
var m = DB['' + mcc];
if (!m || mnc == null) return null;
var s = '' + mnc;
var two = (s.length < 2) ? ('0' + s) : s;
return m[two] || m[s] || m['0' + s] || null;
},
/* country (or 'International') for an mcc -- null when unknown */
country: function(mcc) {
var m = DB['' + mcc];
return m ? (m._c || null) : null;
},
/* "name, country" one-liner, or null */
describe: function(mcc, mnc) {
var n = this.name(mcc, mnc), c = this.country(mcc);
if (!n) return null;
return (c && c != 'International') ? (n + ', ' + c) : n;
}
});''')