This commit is contained in:
Kekskurse 2019-07-07 14:01:07 +02:00
parent 4452020a29
commit f6f7b5bdba
4 changed files with 109 additions and 27 deletions

View file

@ -1,2 +1,3 @@
freenet-funk-api==0.1.4
Flask==1.1.0
APScheduler==3.6.0

106
server.py
View file

@ -10,14 +10,23 @@ import json
import time
import datetime
from dateutil.relativedelta import relativedelta
from apscheduler.schedulers.background import BackgroundScheduler
import os
import atexit
DATABASE = os.getenv("FUNK_DATABASE", 'database.db')
USERNAME = os.getenv("FUNK_USER", 'admin')
PASSWORD = os.getenv("FUNK_PASS", 'geheim')
ENABLED_AUTH = os.getenv("FUNK_AUTH", False)
plans = []
plans.append({"name": "Unlimit", "number": "8", "canBeBooked": True})
plans.append({"name": "1 GB", "number": "9", "canBeBooked": True})
plans.append({"name": "Break", "number": "42", "canBeBooked": True})
plans.append({"name": "Unlimit - First Day", "number": "40", "canBeBooked": False})
#Helper
def get_db():
db = getattr(g, '_database', None)
@ -50,14 +59,24 @@ def requires_auth(f):
return decorated
# Functions
def function_updateAccount(number):
def function_cron():
print("Run Cron")
with app.app_context():
function_updateAccountsAtFunk()
def function_updateAllAccounts():
accounts = function_getAccounts()
for account in accounts:
function_updateAccount(account["number"])
def function_updateAccount(number, api = None):
cur = get_db().cursor()
cur.execute("SELECT mail, password FROM accounts WHERE `number` = '%s'" % (number))
res = cur.fetchone()
api = FunkAPI(res[0], res[1])
plan = api.getCurrentPlan()["productServiceInfo"]["marketingInfo"]["name"]
if api == None:
cur.execute("SELECT mail, password FROM accounts WHERE `number` = '%s'" % (number))
res = cur.fetchone()
api = FunkAPI(res[0], res[1])
usage = api.getData()["data"]["me"]["customerProducts"][0]["mobileNumbers"][0]["usage"]["usedDataPercentage"]
plan = getCurrentPlan(api)["productServiceId"]
cur.execute("INSERT INTO updates VALUES (%s, %s, '%s', '%s')" % (
number,
@ -80,6 +99,21 @@ def function_speacialDays(number):
days.append(day)
return days
def getCurrentPlan(api, now = datetime.datetime.now(datetime.timezone.utc)):
currentPlan = None
for plan in api.getData(refresh=False)["data"]["me"]["customerProducts"][0]["tariffs"]:
planStart = datetime.datetime.strptime(plan["starts"], "%Y-%m-%dT%H:%M:%S.%f%z")
if planStart > now:
continue
currentPlan = plan
return currentPlan
def function_getPlanName(planNumber):
for plan in plans:
if plan["number"] == planNumber:
return plan
return False
def function_getAccounts(includePassword = False):
@ -95,8 +129,8 @@ def function_getAccounts(includePassword = False):
if includePassword:
account["password"] = accountData[2]
account["owner"] = accountData[3]
account["defaultPlan"] = accountData[4]
account["currentPlan"] = lastUpdate[1]
account["defaultPlan"] = function_getPlanName(accountData[4])
account["currentPlan"] = function_getPlanName(lastUpdate[1])
account["dataUsed"] = lastUpdate[2]
account["lastUpdate"] = lastUpdate[0]
accounts.append(account)
@ -114,8 +148,8 @@ def function_getAccount(number, includePassword = False):
if includePassword:
account["password"] = accountData[2]
account["owner"] = accountData[3]
account["defaultPlan"] = accountData[4]
account["currentPlan"] = lastUpdate[1]
account["defaultPlan"] = function_getPlanName(accountData[4])
account["currentPlan"] = function_getPlanName(lastUpdate[1])
account["dataUsed"] = lastUpdate[2]
account["lastUpdate"] = lastUpdate[0]
return account
@ -129,9 +163,35 @@ def function_getPlanForDay(number, year, month, day):
defaultPlan = cur.execute("SELECT defaultPlan FROM accounts WHERE number = %s" % (number)).fetchone()
return defaultPlan[0]
def function_updateAccountsAtFunk():
accounts = function_getAccounts(True)
tomorrow = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)
for account in accounts:
api = FunkAPI(account["mail"], account["password"])
function_updateAccount(account["number"], api) # We already have the API with the Data, so we can write them in the update table
planedPlan = function_getPlanForDay(account["number"], tomorrow.year, tomorrow.month, tomorrow.day)
plan = getCurrentPlan(api, tomorrow)
if(plan["productServiceId"] == planedPlan):
print("Nothing to Change, plan already set")
else:
print("Update")
if planedPlan == "8": #Change to unlimit
api.orderUnlimitedPlan()
print("Switch to Unlimit")
elif planedPlan == "9": #Change to 1GB
api.order1GBPlan()
print("Switch to 1GB")
elif planedPlan == "42": #Change to break
api.startPause()
print("Switch to break")
else:
print("Cant update plan!!! ERROR")
function_cron()
@app.route("/updateAll")
@requires_auth
def function_updateAccountsAtFunk():
def function_updateAccountsAtFunkOLD():
cur = get_db().cursor()
today = datetime.datetime.now()
done = cur.execute("SELECT count(*) FROM run_actions WHERE year = %s AND month = %s AND day = %s" % (today.year, today.month, today.day)).fetchone()
@ -201,7 +261,7 @@ def gui_account(number):
account = function_getAccount(number)
special_days = function_speacialDays(number)
return render_template("account.html", account=account, special_days=special_days, currentTime=int(time.time()))
return render_template("account.html", account=account, plans=plans, special_days=special_days, currentTime=int(time.time()))
@app.route("/account/<number>/special", methods=['POST'])
@requires_auth
@ -296,8 +356,13 @@ def addAccount():
response["msg"] = "Autherized failed, wrong mail/password?"
return json.dumps(response)
plan = api.getCurrentPlan()["productServiceInfo"]["marketingInfo"]["name"]
plan = getCurrentPlan(api)["productServiceId"]
name = personalData["firstName"]+" "+personalData["lastName"]
defaultPlan = 42
for plan in plans:
if plan["number"] == plan:
defaultPlan = plan
# getUsage
data = api.getData()
@ -310,7 +375,7 @@ def addAccount():
mail,
password,
name,
plan
defaultPlan
))
get_db().commit()
@ -328,5 +393,16 @@ def close_connection(exception):
if db is not None:
db.close()
atexit.register(lambda: scheduler.shutdown())
def print_date_time():
print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))
scheduler = BackgroundScheduler()
scheduler.add_job(func=function_cron, trigger="interval", seconds=(60*10))
scheduler.start()
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
app.run(debug=False,host='0.0.0.0')

View file

@ -17,11 +17,11 @@
</tr>
<tr>
<th>Current Plan</th>
<td>{{ account["currentPlan"] }}</td>
<td>{{ account["currentPlan"]["name"] }}</td>
</tr>
<tr>
<th>Default Plan</th>
<td>{{ account["defaultPlan"] }}</td>
<td>{{ account["defaultPlan"]["name"] }}</td>
</tr>
<tr>
<th>Updatet min ago</th>
@ -39,9 +39,11 @@
<h4>Update Default Plan</h4>
<p>The Default Plan will be set if no other Rule is enabled for the Day.</p>
<select class="form-control" id="defaultPlan">
<option value="1 GB" {% if account["defaultPlan"] == '1 GB' %}selected{% endif %}>1 GB</option>
<option value="unlimited" {% if account["defaultPlan"] == 'unlimited' %}selected{% endif %}>Unlimit</option>
<option value="Break" {% if account["defaultPlan"] == 'Break' %}selected{% endif %}>Break</option>
{% for plan in plans %}
{% if plan["canBeBooked"] %}
<option value="{{ plan["number"] }}" {% if account["defaultPlan"]["number"] == plan["number"] %}selected{% endif %}>{{ plan["name"] }}</option>
{% endif %}
{% endfor %}
</select><br>
<input type="button" class="btn btn-warning" value="Save" id="changeDefaultPlan">
@ -169,10 +171,13 @@
</div>
<b>Plan</b>
<select name="plan" class="form-control">
<option value="1 GB">1 GB</option>
<option value="Unlimit">Unlimit</option>
<option value="Break">Break</option>
<option value="Default">Default (Delet all specal days in this Period)</option>
{% for plan in plans %}
{% if plan["canBeBooked"] %}
<option value="{{ plan["number"] }}" >{{ plan["name"] }}</option>
{% endif %}
{% endfor %}
</select><br>
<input type="submit" class="btn btn-success" value="Save">
</form>

View file

@ -18,8 +18,8 @@
<div class="progress-bar" role="progressbar" style="width: {{ account["dataUsed"]|round(2) }}%;" aria-valuenow="{{ account["dataUsed"]|round(2) }}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</td>
<td> {{ account["currentPlan"] }}</td>
<td> {{ account["defaultPlan"] }}</td>
<td> {{ account["currentPlan"]["name"] }}</td>
<td> {{ account["defaultPlan"]["name"] }}</td>
<td> {{ ((currentTime - account["lastUpdate"]) /60)|round(1) }} min</td>
<td> <a href="/account/{{ account["number"] }}" class="btn btn-sm btn-warning">Edit</a> </td>
</tr>