tox-weechat/misc/getnodes.py

89 lines
3.0 KiB
Python
Executable File

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Håvard Pettersson <mail@haavard.me>.
#
# This file is part of Tox-WeeChat.
#
# Tox-WeeChat is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Tox-WeeChat 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Tox-WeeChat. If not, see <http://www.gnu.org/licenses/>.
#
import re
import sys
import os
import json
import datetime
import textwrap
import urllib.request
def iMain(surl):
if os.path.exists(surl):
with open(surl, 'rt') as response:
data = json.load(response)
else:
with urllib.request.urlopen(surl) as response:
data = json.load(response)
# get online nodes that are defined by IP address
nodes = [node for node in data['nodes']
if (node['status_tcp'] or node['status_udp'])
and re.match(r'^\d+\.\d+\.\d+\.\d+$', node['ipv4'])]
# extract relevant values from node dictionaries
addresses = [node['ipv4'] for node in nodes]
ports = [node['port'] for node in nodes]
keys = [node['public_key'] for node in nodes]
comments = ['Maintainer: {}, location: {}'.format(
node['maintainer'], node['location']) for node in nodes]
# emit C code
print('/* bootstrap nodes generated by', __file__)
print(' * last generated', datetime.datetime.now().isoformat(), '*/')
print('static struct t_twc_bootstrap_node const twc_bootstrap_nodes[] = {')
for key, address, port, comment in zip(keys, addresses, ports, comments):
print(' /* {} */'.format(comment))
print(' {{"{}",'.format(key))
print(' "{}", {}}},'.format(address, port))
print('};')
# get online nodes that are defined by IP address
nodes = [node for node in data['nodes']
if (node['status_tcp'] and node['tcp_ports'])
and re.match(r'^\d+\.\d+\.\d+\.\d+$', node['ipv4'])]
print('static struct t_twc_bootstrap_node const twc_bootstrap_relays[] = {')
for node in nodes:
for port in node['tcp_ports']:
# extract relevant values from node dictionaries
address = node['ipv4']
key = node['public_key']
comment = 'Maintainer: {}, location: {}'.format(
node['maintainer'], node['location'])
print(' /* {} */'.format(comment))
print(' {{"{}",'.format(key))
print(' "{}", {}}},'.format(address, port))
print('};')
return 0
if __name__ == '__main__':
if len(sys.argv) > 1:
surl = sys.argv[1]
else:
surl = 'https://nodes.tox.chat/json'
sys.exit(iMain(surl))