1#!/usr/bin/env python3 2# 3# Standalone signaling server for the Nextcloud Spreed app. 4# Copyright (C) 2019 struktur AG 5# 6# @author Joachim Bauch <bauch@struktur.de> 7# 8# @license GNU AGPL version 3 or any later version 9# 10# This program is free software: you can redistribute it and/or modify 11# it under the terms of the GNU Affero General Public License as published by 12# the Free Software Foundation, either version 3 of the License, or 13# (at your option) any later version. 14# 15# This program is distributed in the hope that it will be useful, 16# but WITHOUT ANY WARRANTY; without even the implied warranty of 17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18# GNU Affero General Public License for more details. 19# 20# You should have received a copy of the GNU Affero General Public License 21# along with this program. If not, see <http://www.gnu.org/licenses/>. 22# 23 24try: 25 # Fallback for Python2 26 from cStringIO import StringIO 27except ImportError: 28 from io import StringIO 29import json 30import subprocess 31import sys 32 33URL = 'https://datahub.io/JohnSnowLabs/country-and-continent-codes-list/r/country-and-continent-codes-list-csv.json' 34 35def tostr(s): 36 if isinstance(s, bytes) and not isinstance(s, str): 37 s = s.decode('utf-8') 38 return s 39 40try: 41 unicode 42except NameError: 43 # Python 3 files are returning bytes by default. 44 def opentextfile(filename, mode): 45 if 'b' in mode: 46 mode = mode.replace('b', '') 47 return open(filename, mode, encoding='utf-8') 48else: 49 def opentextfile(filename, mode): 50 return open(filename, mode) 51 52def generate_map(filename): 53 data = subprocess.check_output([ 54 'curl', 55 '-L', 56 URL, 57 ]) 58 data = json.loads(tostr(data)) 59 continents = {} 60 for entry in data: 61 country = entry['Two_Letter_Country_Code'] 62 continent = entry['Continent_Code'] 63 continents.setdefault(country, []).append(continent) 64 65 out = StringIO() 66 out.write('package signaling\n') 67 out.write('\n') 68 out.write('// This file has been automatically generated, do not modify.\n') 69 out.write('// Source: %s\n' % (URL)) 70 out.write('\n') 71 out.write('var (\n') 72 out.write('\tContinentMap map[string][]string = map[string][]string{\n') 73 for country, continents in sorted(continents.items()): 74 value = [] 75 for continent in continents: 76 value.append('"%s"' % (continent)) 77 out.write('\t\t"%s": []string{%s},\n' % (country, ', '.join(value))) 78 out.write('\t}\n') 79 out.write(')\n') 80 with opentextfile(filename, 'wb') as fp: 81 fp.write(out.getvalue()) 82 83def main(): 84 if len(sys.argv) != 2: 85 sys.stderr.write('USAGE: %s <filename>\n' % (sys.argv[0])) 86 sys.exit(1) 87 88 filename = sys.argv[1] 89 generate_map(filename) 90 91if __name__ == '__main__': 92 main() 93