Files
@ 47d07b5cb8db
Branch filter:
Location: FVDE/ennstatus/ennstatus/api/model.py
47d07b5cb8db
7.4 KiB
text/x-python
Added flags
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 | # Ënnstatus
# Copyright (C) 2015 Dennis Fink
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
import ipaddress
import json
import functools
import statistics
from pathlib import Path
from datetime import datetime
import jsonschema
import strict_rfc3339
from flask import current_app
from pkg_resources import resource_filename
from onion_py.manager import Manager
from onion_py.caching import OnionSimpleCache
from ..utils import check_ip
schema = json.load(
open(
resource_filename('ennstatus.api', 'schema/server.json'),
encoding='utf-8'
)
)
validate = functools.partial(
jsonschema.validate,
schema=schema,
format_checker=jsonschema.FormatChecker()
)
manager = Manager(OnionSimpleCache())
def calculate_weight(data):
obj = {}
for subkey in ('1_week', '1_month', '3_months', '1_year', '5_years'):
try:
subdata = data[subkey]
except KeyError:
continue
factor = subdata.factor
values = [x * factor for x in subdata.values if x is not None]
if values:
obj[subkey] = statistics.mean(values) * 100
else:
obj[subkey] = None
return obj
class ServerEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (ipaddress.IPv4Address, ipaddress.IPv6Address)):
return str(obj)
if isinstance(obj, datetime):
return strict_rfc3339.timestamp_to_rfc3339_utcoffset(
obj.timestamp()
)
return json.JSONEncoder.default(self, obj)
class ServerDecoder(json.JSONDecoder):
def decode(self, json_string):
default_obj = super().decode(json_string)
for key in ('ip', 'ip6'):
if key in default_obj:
current_app.logger.debug('{}: {}'.format(
key, default_obj[key]
)
)
default_obj[key] = ipaddress.ip_address(default_obj[key])
current_app.logger.debug('Loading last_updated')
default_obj['last_updated'] = datetime.fromtimestamp(
strict_rfc3339.rfc3339_to_timestamp(default_obj['last_updated'])
)
return default_obj
class Server:
def __init__(self, *args, **kwargs):
self.name = kwargs['name']
self.type = kwargs['type']
self.status = kwargs.get('status')
self.fingerprint = kwargs['fingerprint']
self.last_updated = kwargs['last_updated']
self.country = kwargs['country']
self.bandwidth = kwargs.get('bandwidth')
self.flags = kwargs.get('flags')
if self.type == 'bridge':
self.obfs = kwargs.get('obfs')
self.fteproxy = kwargs.get('fteproxy')
self.flashproxy = kwargs.get('flashproxy')
self.meek = kwargs.get('meek')
else:
self.ip = kwargs['ip']
if 'ip6' in kwargs:
self.ip6 = kwargs['ip6']
default_weights = {
'1_week': None,
'1_month': None,
'3_months': None,
'1_year': None,
'5_years': None
}
self.mean_consensus_weight = kwargs.get(
'mean_consensus_weight',
default_weights
)
self.mean_guard_probability = kwargs.get(
'mean_guard_probability',
default_weights
)
self.mean_exit_probability = kwargs.get(
'mean_exit_probability',
default_weights
)
self.mean_consensus_weight_fraction = kwargs.get(
'mean_consensus_weight_fraction',
default_weights
)
self.mean_middle_probability = kwargs.get(
'mean_middle_probability',
default_weights
)
@classmethod
def from_file_by_name(cls, name):
filepath = Path('data') / (name.lower() + '.json')
current_app.logger.info('Loading {}'.format(str(filepath)))
if filepath.exists() and filepath.is_file():
try:
with filepath.open(encoding='utf-8') as f:
data = json.load(f, cls=ServerDecoder)
except (IOError, ValueError):
current_app.logger.error('IOError or ValueError')
return False
else:
return cls(**data)
else:
current_app.logger.error('File error!')
return False
@classmethod
def from_json(cls, server):
try:
if cls.check_json_format(json.loads(server)):
decoded = json.loads(server, cls=ServerDecoder)
return cls(**decoded)
except (jsonschema.ValidationError, ValueError) as e:
raise e
@classmethod
def from_dict(cls, server):
return cls.from_json(json.dumps(server))
def json(self):
return json.dumps(self.__dict__, cls=ServerEncoder)
@staticmethod
def check_json_format(server):
try:
validate(server)
except jsonschema.ValidationError as e:
raise e
for key in ('ip', 'ip6'):
if key in server:
address = ipaddress.ip_address(server[key])
if not check_ip(address):
raise ValueError('{} is not accepted!\n'.format(key))
return True
def save(self):
filepath = Path('data') / (self.name.lower() + '.json')
try:
with filepath.open(mode='w', encoding='utf-8') as f:
json.dump(self.__dict__, f, cls=ServerEncoder)
except Exception as e:
raise e
def update_weights(self):
if self.type not in ('exit', 'relay'):
raise NotImplementedError
try:
data = manager.query('weights', lookup=self.fingerprint)
except:
raise NotImplementedError
if data is not None:
data = data.relays[0]
self.mean_consensus_weight = calculate_weight(data.consensus_weight)
self.mean_exit_probability = calculate_weight(data.exit_probability)
self.mean_guard_probability = calculate_weight(
data.guard_probability
)
self.mean_middle_probability = calculate_weight(
data.middle_probability
)
self.mean_consensus_weight_fraction = calculate_weight(
data.consensus_weight_fraction
)
def update_flags(self):
try:
data = manager.query('details', lookup=self.fingerprint)
except:
raise NotImplementedError
self.flags = data.relays[0].flags
def check_status(self):
now = datetime.utcnow()
delta = now - self.last_updated
if delta.seconds >= 3600:
self.status = False
elif delta.seconds >= 600:
self.status = None
|