[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [tor-dev] Anyone wanting to write some Weather-tight code?



Hello Norbert,

On 14/01/2014 15:22, Karsten Loesing wrote:
- Norbert, how about you start writing the daily script as a stand-alone
Python script that doesn't send out emails nor interact with a database
yet?  This first version of the script could simply print out which
relay operators should be offered a t-shirt.

I was working a version of this script which checks if a relay deserves a
tshirt. It was working fine before I started refactoring it. I never got
around to finishing the refactor, and I may not be able to contribute to
the weather rewrite.

The code might throw up an error in it's current state, but, I'm attaching
it anyway with the hope that you find it useful.

Please use the code in whichever way you please, if it's helpful at all.

--
Regards,
neena
# -*- coding: utf-8 -*-


from flask import Flask, render_template, request
app = Flask(__name__)

import requests

onionoo_endpoint = {
    "bandwidth": "https://onionoo.torproject.org/bandwidth";,
    "details": "https://onionoo.torproject.org/details";,
}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/eligibility/<fingerprint>')
def eligibility_by_keyword(fingerprint):
    return tshirt_eligibility(fingerprint)

@app.route('/eligibility')
def eligibility_by_param():
    fingerprint = request.args.get('fingerprint', '')
    return tshirt_eligibility(fingerprint)

def tshirt_eligibility(fingerprint):
    try:
        bandwidth_document = requests.get(ONIONOO_ENDPOINT["bandwidth"], params={"lookup": fingerprint}).json()
        details_document = requests.get(ONIONOO_ENDPOINT["details"], params={"lookup": fingerprint}).json()
    except requests.exceptions.RequestException, exc:
        app.logger.error(str(exc))
        return render_template("error.html", onionoo_down = True), 500
    
    if len(bandwidth_document["relays"]) == 0 or len(details_response["relays"]) == 0:
        return render_template("error.html", not_relay = True)
    
    write_history_3_months = bandwidth_document["relays"][0]["write_history"]["3_months"]
    months_3 = write_history_3_months["values"]
    interval = int(write_history_3_months["interval"])
    factor = int(write_history_3_months["factor"])
    excess_seconds = (len(months_3) * interval) - 5270400 # 2 months => 61 days => 61 * 24 * 60 * 60

    if excess_seconds >= 0:
        excess_values = excess_seconds / interval
        months_2 = [int(val) for val in filter(None, months_3[excess_values:])]
    else:
        return render_template("error.html", insufficient_data = True), 500
    average_bandwidth = (factor * sum(months_2))/len(months_2)

    if parse_exit80(details_document['relays'][0]['exit_policy_summary']):
        return render_template("eligibility.html", eligible = (average_bandwidth > 102400))
    else:
        return render_template("eligibility.html", eligible = (average_bandwidth > 512000))

def parse_exit_policy_entry(entry):
    """port or startport-endport"""
    if "-" in entry:
        return map(int, entry.split("-"))
    else:
        return int(entry)

def check_contains_80(item):
    if type(item) == list:
        return item[0] <= 80 <= item[1]
    else:
        return item == 80

def allow_exit80(exit_policy_summary):
    if "accept" in exit_policy_summary:
        key = "accept"
    elif "reject" in exit_policy_summary:
        key = "reject"

    return len([policy_item for policy_item in exit_policy_summary[key] if check_contains_80(parse_exit_policy_entry(policy_item))]) > 0

if __name__ == "__main__":
    app.run(debug = True)
_______________________________________________
tor-dev mailing list
tor-dev@xxxxxxxxxxxxxxxxxxxx
https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-dev