Permalink
Browse files

Remove credit logic

Refs #395
  • Loading branch information...
lukasjuhrich authored and Georgeto committed Jan 22, 2019
1 parent 6dd311a commit 53f0201218993113221801b1d8f260d9262286a0
@@ -181,7 +181,9 @@ def logout():


@bp_generic.app_template_filter('traffic_color')
def traffic_color(amount, daily_credit):
def traffic_color(amount):
# TODO think about other thresholds replacing `User.daily_credit`
daily_credit = 10 * 1024 * 1024
return ("" if amount < daily_credit
else "bg-warning" if amount < 2 * daily_credit
else "bg-danger")
@@ -257,13 +259,12 @@ def traffic_api():
} for x in reversed(user.traffic_history))

trafficdata = {
'quota': user.credit,
# `next` gets the first entry (“today”)
'traffic': next(traffic_history),
'history': list(traffic_history),
}

return jsonify(version=2, **trafficdata)
return jsonify(version=3, **trafficdata)


@bp_generic.route('/contact', methods=['GET', 'POST'])
@@ -17,14 +17,11 @@
from sipa.defaults import DEFAULT_CONFIG
from sipa.flatpages import CategorizedFlatPages
from sipa.model import build_backends_ext
from sipa.model.misc import query_gauge_data
from sipa.session import SeparateLocaleCookieSessionInterface
from sipa.utils import replace_empty_handler_callables, url_self
from sipa.utils.babel_utils import get_weekday
from sipa.utils.git_utils import init_repo, update_repo
from sipa.utils.graph_utils import (generate_credit_chart,
generate_traffic_chart,
provide_render_function)
from sipa.utils.graph_utils import generate_traffic_chart, provide_render_function

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler()) # for before logging is configured
@@ -74,13 +71,11 @@ def init_app(app, **kwargs):
form_input_width = 7
app.jinja_env.globals.update(
cf_pages=cf_pages,
gauge_data=query_gauge_data,
get_locale=get_locale,
get_weekday=get_weekday,
possible_locales=possible_locales,
get_attribute_endpoint=get_attribute_endpoint,
traffic_chart=provide_render_function(generate_traffic_chart),
credit_chart=provide_render_function(generate_credit_chart),
current_datasource=backends.current_datasource,
form_label_width_class="col-sm-{}".format(form_label_width),
form_input_width_class="col-sm-{}".format(form_input_width),
@@ -138,14 +138,8 @@ class TrafficQuota(db.Model):
__bind_key__ = 'hss'

id = Column(Integer, primary_key=True)
daily_credit = Column(BigInteger, nullable=False, default=0)
max_credit = Column(BigInteger, nullable=False, default=0)
description = Column(String(255), nullable=False)
accounts = relationship('Account', backref='traffic_quota')

def __repr__(self):
return ("<{cls} #{obj.id} daily={obj.daily_credit} max={obj.max_credit} "
"'{obj.description}'>".format(
cls=type(self).__name__,
obj=self,
))
return f"<{type(self).__name__} #{self.id} '{self.description}'>"
@@ -122,16 +122,7 @@ def change_password(self, old, new):

@property
def traffic_history(self):
"""Return the current credit and the traffic history as a dict.
The history should cover one week. The assumed unit is KiB.
The dict syntax is as follows:
return {'credit': 0,
'history': [(day, <in>, <out>, <credit>)
for day in range(7)]}
"""See `model.User.traffic_history`
"""
history = []

@@ -147,64 +138,18 @@ def traffic_history(self):
'input': 0,
'output': 0,
'throughput': 0,
'credit': 0,
})
else:
history.append({
'day': expected_date.weekday(),
'input': log.bytes_in / 1024,
'output': log.bytes_out / 1024,
'throughput': (log.bytes_in + log.bytes_out) / 1024,
'credit': 0,
})
# get the history from the expected_date

return self.reconstruct_credit(history, self.credit)

def reconstruct_credit(self, old_history, last_credit):
history = old_history.copy()
history[-1]['credit'] = last_credit - history[-1]['throughput']

for i, entry in enumerate(reversed(history)):
try:
# previous means *chronologically* previous (we
# iterate over `reversed`) ⇒ use [i+1]
previous_entry = list(reversed(history))[i+1]
except IndexError:
pass
else:
# Throughput: gets *subtracted* after the day → `+` for before
# Credit: gets *added* after the day → `-` for before
previous_entry['credit'] = (
entry['credit'] + previous_entry['throughput'] - self.daily_credit
# 3 → 3 KiB
# 3 * 1024 → 3 MiB
# 3 * 1024**2 → 3 GiB
)

return history

@property
def credit(self):
"""Return the current credit in KiB"""
return self._pg_account.traffic_balance / 1024

@property
def max_credit(self):
"""Return the current credit in KiB"""
try:
return self._pg_trafficquota.max_credit / 1024
except NoResultFound:
return 210 * 1024 ** 2

@property
def daily_credit(self):
"""Return the current credit in KiB"""
try:
return self._pg_trafficquota.daily_credit / 1024
except NoResultFound:
return 10 * 1024 ** 2

@active_prop
def ips(self):
return ", ".join(ip.ip for ip in self._pg_account.ips)
@@ -1,26 +1,6 @@
from collections import namedtuple

from flask import request
from flask_login import current_user
from sqlalchemy.exc import OperationalError

from sipa.backends.extension import backends

TransactionTuple = namedtuple('Transaction', ['datum', 'value'])

PaymentDetails = namedtuple('PaymentDetails', 'recipient bank iban bic purpose')


def query_gauge_data():
credit = {'data': None, 'error': False, 'foreign_user': False}
try:
if current_user.is_authenticated and current_user.has_connection:
user = current_user
else:
user = backends.user_from_ip(request.remote_addr)
credit['data'] = user.credit
except OperationalError:
credit['error'] = True
except AttributeError:
credit['foreign_user'] = True
return credit
@@ -79,16 +79,8 @@ def traffic_history(self):
'input': to_kib(entry.ingress),
'output': to_kib(entry.egress),
'throughput': to_kib(entry.ingress + entry.egress),
'credit': to_kib(entry.balance),
} for entry in self.user_data.traffic_history]

@property
def credit(self):
return to_kib(self.user_data.traffic_balance)

max_credit = 210 * 1024 * 1024
daily_credit = 5 * 1024 * 1024

@active_prop
def realname(self):
return self.user_data.realname
@@ -119,16 +119,8 @@ def rand():
'output': o,
'throughput': i + o,
})(rand(), rand()*0.04),
'credit': random() * 1024**2 * 210,
} for day in range(7)]

@property
def credit(self):
return random() * 1024**2 * 210

max_credit = 210 * 1024 * 1024
daily_credit = 10 * 1024 * 1024

@active_prop
def realname(self):
return self._realname
@@ -133,7 +133,7 @@ def change_password(self, old, new):
@property
@abstractmethod
def traffic_history(self):
"""Return the current credit and the traffic history as a dict.
"""Return the current traffic history as a dict.
The history should cover one week. The assumed unit is KiB.
@@ -144,7 +144,6 @@ def traffic_history(self):
'input': in,
'output': out,
'throughput': in + out,
'credit': credit,
}, …]
The traffic values shall be in KiB, as usual.
@@ -154,15 +153,6 @@ def traffic_history(self):
"""
pass

@property
@abstractmethod
def credit(self):
"""**[Abstract]** The current credit in KiB
:rtype: int/float
"""
pass

def generate_rows(self, description_dict):
for key, val in description_dict.items():
yield Row(description=val, property=getattr(self, key))
Oops, something went wrong.

0 comments on commit 53f0201

Please sign in to comment.