joeni

Add PingPing module file to tracker

Author
Maarten 'Vngngdn' Vangeneugden
Date
Nov. 14, 2017, 8:53 p.m.
Hash
c3f5bcfa37c056eeee3908d148ff037aec95e1fc
Parent
1e65844b20cb230538a004c3c1229bca1df5eea4
Modified file
pingping.py

pingping.py

61 additions and 0 deletions.

View changes Hide changes
+
1
PingPing module for Joeni. Provides and implements the functionality required to
+
2
interact with PingPing.
+
3
"""
+
4
import requests
+
5
from .models import user
+
6
from django.core.cache import caches
+
7
+
8
def balance(user_id):
+
9
    """ Returns the current balance associated with the given account.
+
10
    The returned value may be a cached value, so if you top up your balance and
+
11
    check immediately, be advised it may not be the correct result, but it will
+
12
    be updated.
+
13
    Future idea: If the balance is below a certain treshold (for example €2), I
+
14
    can hardwire the function so that it ignores the cache. Most people will not
+
15
    top up their balance until it's below a certain point.
+
16
    While logging the times the result is higher than the cached result is
+
17
    handy, caches are deleted after a certain time, so the info is lost. I'll
+
18
    see what I can do in the future. Possibly collect all the times an account
+
19
    is topped up, and take the median of those results to see what is the most
+
20
    likely amount that somebody will top up their balance.
+
21
    """
+
22
    # Check cache first
+
23
    cache = cashes['pingping']
+
24
    cached = cache.get(user_id)
+
25
    if cached is not None:
+
26
        return cached
+
27
    else:
+
28
        result = update_balance(user_id)
+
29
        # Updating cache
+
30
        cache.set(user_id, result, timeout=3600)  # Cached for 1 hour
+
31
        cache.close()
+
32
        return result
+
33
+
34
def update_balance(user_id):
+
35
    """ Connects to the PingPing website and looks for the current budget. """
+
36
    user_data = user.objects.get(id=user_id)
+
37
    username = user_data.name
+
38
    password = user_data.password
+
39
+
40
    link = "https://uhasselt-pxl.mynetpay.be/Account/Login"
+
41
    # Get CSRF protection token
+
42
    first_call = requests.get(link)
+
43
    text = first_call.text
+
44
    begin = text.find('__RequestVerificationToken')
+
45
    begin = text.find('value="', begin)
+
46
    end = text.find('" ', begin)
+
47
    token = text[begin+len('value="'):end]
+
48
    cookies = first_call.cookies
+
49
+
50
    response = requests.post(link, data={
+
51
        'Username':username,
+
52
        'LoginType':'Student',
+
53
        'Password':password,
+
54
        '__RequestVerificationToken':token,
+
55
        }, cookies=cookies)
+
56
+
57
    html_response = response.text
+
58
    start = html_response.find(": € ")
+
59
    offset = len(": € ")
+
60
    return  html_response[start+offset:start+offset+4]
+
61