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 freenet-funk-api==0.1.4
Flask==1.1.0 Flask==1.1.0
APScheduler==3.6.0

100
server.py
View file

@ -10,14 +10,23 @@ import json
import time import time
import datetime import datetime
from dateutil.relativedelta import relativedelta from dateutil.relativedelta import relativedelta
from apscheduler.schedulers.background import BackgroundScheduler
import os import os
import atexit
DATABASE = os.getenv("FUNK_DATABASE", 'database.db') DATABASE = os.getenv("FUNK_DATABASE", 'database.db')
USERNAME = os.getenv("FUNK_USER", 'admin') USERNAME = os.getenv("FUNK_USER", 'admin')
PASSWORD = os.getenv("FUNK_PASS", 'geheim') PASSWORD = os.getenv("FUNK_PASS", 'geheim')
ENABLED_AUTH = os.getenv("FUNK_AUTH", False) 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 #Helper
def get_db(): def get_db():
db = getattr(g, '_database', None) db = getattr(g, '_database', None)
@ -50,14 +59,24 @@ def requires_auth(f):
return decorated return decorated
# Functions # 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 = get_db().cursor()
if api == None:
cur.execute("SELECT mail, password FROM accounts WHERE `number` = '%s'" % (number)) cur.execute("SELECT mail, password FROM accounts WHERE `number` = '%s'" % (number))
res = cur.fetchone() res = cur.fetchone()
api = FunkAPI(res[0], res[1]) api = FunkAPI(res[0], res[1])
plan = api.getCurrentPlan()["productServiceInfo"]["marketingInfo"]["name"]
usage = api.getData()["data"]["me"]["customerProducts"][0]["mobileNumbers"][0]["usage"]["usedDataPercentage"] 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')" % ( cur.execute("INSERT INTO updates VALUES (%s, %s, '%s', '%s')" % (
number, number,
@ -80,6 +99,21 @@ def function_speacialDays(number):
days.append(day) days.append(day)
return days 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): def function_getAccounts(includePassword = False):
@ -95,8 +129,8 @@ def function_getAccounts(includePassword = False):
if includePassword: if includePassword:
account["password"] = accountData[2] account["password"] = accountData[2]
account["owner"] = accountData[3] account["owner"] = accountData[3]
account["defaultPlan"] = accountData[4] account["defaultPlan"] = function_getPlanName(accountData[4])
account["currentPlan"] = lastUpdate[1] account["currentPlan"] = function_getPlanName(lastUpdate[1])
account["dataUsed"] = lastUpdate[2] account["dataUsed"] = lastUpdate[2]
account["lastUpdate"] = lastUpdate[0] account["lastUpdate"] = lastUpdate[0]
accounts.append(account) accounts.append(account)
@ -114,8 +148,8 @@ def function_getAccount(number, includePassword = False):
if includePassword: if includePassword:
account["password"] = accountData[2] account["password"] = accountData[2]
account["owner"] = accountData[3] account["owner"] = accountData[3]
account["defaultPlan"] = accountData[4] account["defaultPlan"] = function_getPlanName(accountData[4])
account["currentPlan"] = lastUpdate[1] account["currentPlan"] = function_getPlanName(lastUpdate[1])
account["dataUsed"] = lastUpdate[2] account["dataUsed"] = lastUpdate[2]
account["lastUpdate"] = lastUpdate[0] account["lastUpdate"] = lastUpdate[0]
return account 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() defaultPlan = cur.execute("SELECT defaultPlan FROM accounts WHERE number = %s" % (number)).fetchone()
return defaultPlan[0] 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") @app.route("/updateAll")
@requires_auth @requires_auth
def function_updateAccountsAtFunk(): def function_updateAccountsAtFunkOLD():
cur = get_db().cursor() cur = get_db().cursor()
today = datetime.datetime.now() 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() 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) account = function_getAccount(number)
special_days = function_speacialDays(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']) @app.route("/account/<number>/special", methods=['POST'])
@requires_auth @requires_auth
@ -296,8 +356,13 @@ def addAccount():
response["msg"] = "Autherized failed, wrong mail/password?" response["msg"] = "Autherized failed, wrong mail/password?"
return json.dumps(response) return json.dumps(response)
plan = api.getCurrentPlan()["productServiceInfo"]["marketingInfo"]["name"] plan = getCurrentPlan(api)["productServiceId"]
name = personalData["firstName"]+" "+personalData["lastName"] name = personalData["firstName"]+" "+personalData["lastName"]
defaultPlan = 42
for plan in plans:
if plan["number"] == plan:
defaultPlan = plan
# getUsage # getUsage
data = api.getData() data = api.getData()
@ -310,7 +375,7 @@ def addAccount():
mail, mail,
password, password,
name, name,
plan defaultPlan
)) ))
get_db().commit() get_db().commit()
@ -328,5 +393,16 @@ def close_connection(exception):
if db is not None: if db is not None:
db.close() 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__': 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>
<tr> <tr>
<th>Current Plan</th> <th>Current Plan</th>
<td>{{ account["currentPlan"] }}</td> <td>{{ account["currentPlan"]["name"] }}</td>
</tr> </tr>
<tr> <tr>
<th>Default Plan</th> <th>Default Plan</th>
<td>{{ account["defaultPlan"] }}</td> <td>{{ account["defaultPlan"]["name"] }}</td>
</tr> </tr>
<tr> <tr>
<th>Updatet min ago</th> <th>Updatet min ago</th>
@ -39,9 +39,11 @@
<h4>Update Default Plan</h4> <h4>Update Default Plan</h4>
<p>The Default Plan will be set if no other Rule is enabled for the Day.</p> <p>The Default Plan will be set if no other Rule is enabled for the Day.</p>
<select class="form-control" id="defaultPlan"> <select class="form-control" id="defaultPlan">
<option value="1 GB" {% if account["defaultPlan"] == '1 GB' %}selected{% endif %}>1 GB</option> {% for plan in plans %}
<option value="unlimited" {% if account["defaultPlan"] == 'unlimited' %}selected{% endif %}>Unlimit</option> {% if plan["canBeBooked"] %}
<option value="Break" {% if account["defaultPlan"] == 'Break' %}selected{% endif %}>Break</option> <option value="{{ plan["number"] }}" {% if account["defaultPlan"]["number"] == plan["number"] %}selected{% endif %}>{{ plan["name"] }}</option>
{% endif %}
{% endfor %}
</select><br> </select><br>
<input type="button" class="btn btn-warning" value="Save" id="changeDefaultPlan"> <input type="button" class="btn btn-warning" value="Save" id="changeDefaultPlan">
@ -169,10 +171,13 @@
</div> </div>
<b>Plan</b> <b>Plan</b>
<select name="plan" class="form-control"> <select name="plan" class="form-control">
<option value="1 GB">1 GB</option>
<option value="Unlimit">Unlimit</option> {% for plan in plans %}
<option value="Break">Break</option> {% if plan["canBeBooked"] %}
<option value="Default">Default (Delet all specal days in this Period)</option> <option value="{{ plan["number"] }}" >{{ plan["name"] }}</option>
{% endif %}
{% endfor %}
</select><br> </select><br>
<input type="submit" class="btn btn-success" value="Save"> <input type="submit" class="btn btn-success" value="Save">
</form> </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 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> </div>
</td> </td>
<td> {{ account["currentPlan"] }}</td> <td> {{ account["currentPlan"]["name"] }}</td>
<td> {{ account["defaultPlan"] }}</td> <td> {{ account["defaultPlan"]["name"] }}</td>
<td> {{ ((currentTime - account["lastUpdate"]) /60)|round(1) }} min</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> <td> <a href="/account/{{ account["number"] }}" class="btn btn-sm btn-warning">Edit</a> </td>
</tr> </tr>