views.py
1 |
|
2 |
import requests # For direct communication with me |
3 |
from datetime import date |
4 |
from django.utils import timezone |
5 |
from django.shortcuts import get_object_or_404, render # This allows to render the template with the view here. It's pretty cool and important. |
6 |
from django.http import HttpResponseRedirect, HttpResponse # Why? |
7 |
from django.urls import reverse # Why? |
8 |
from django.utils.translation import gettext as _ |
9 |
from .models import * |
10 |
from .forms import MessageForm, ProductForm |
11 |
import ipware |
12 |
|
13 |
#ipw = ipware.IpWare() # Yea I know, they updated ipware and now you have to do this |
14 |
|
15 |
|
16 |
def get_age(): |
17 |
"""Returns my current age.""" |
18 |
today = date.today() |
19 |
birthday = date(1996, 8, 28) |
20 |
age = today - birthday |
21 |
years = str(int(age.days / 365)) |
22 |
return years |
23 |
|
24 |
def footer_description(): |
25 |
return _("Main pages of Maarten's website, a %(years)s year old Belgian programmer. Also an undergraduate student of Informatics @ UHasselt, and graduate student of Engineering Informatics at Ghent University.") % {'years': get_age()} |
26 |
|
27 |
def footer_links(): |
28 |
footer_links = [ |
29 |
[_("Contact me"), "mailto:maarten.vangeneugden@student.uhasselt.be"], |
30 |
[_("Hasselt University"), "https://www.uhasselt.be"], |
31 |
[_("Ghent University"), "https://www.ugent.be"], |
32 |
] |
33 |
return footer_links |
34 |
|
35 |
# TODO: Move this stuff to the template module. This is basically a description |
36 |
# of HOW to display data, but the view module is only responsible for WHAT data |
37 |
# to display. |
38 |
def standard_context(): |
39 |
context = { |
40 |
'navbar_backArrow': True, |
41 |
'footer_title': _("Home page"), |
42 |
'footer_description': footer_description(), |
43 |
'footer_links': footer_links(), |
44 |
'stylesheet_name': "home", |
45 |
} |
46 |
return context |
47 |
|
48 |
def get_current_status(dt = None): |
49 |
"""Returns a string specifying my current state (and sometimes location). |
50 |
|
51 |
This function is actually based on my weekly schedule. I'd normally hook it |
52 |
up to my iCal files, but that doesn't include things like sleeping. Not to |
53 |
mention my university has a hard time following standards like "Put the |
54 |
location in the location field, not in the title of the appointment". I |
55 |
figured a simple function would do the job just as well. |
56 |
|
57 |
Keyword arguments: |
58 |
dt -- The datetime object of the day to check (defaults to current local time) |
59 |
""" |
60 |
|
61 |
MONDAY = 0 |
62 |
TUESDAY = 1 |
63 |
WEDNESDAY = 2 |
64 |
THURSDAY = 3 |
65 |
FRIDAY = 4 |
66 |
SATURDAY = 5 |
67 |
SUNDAY = 6 |
68 |
|
69 |
if dt is None: |
70 |
timezone.activate("Europe/Brussels") |
71 |
dt = timezone.localtime(timezone.now()) |
72 |
|
73 |
day = dt.weekday() |
74 |
hour = dt.time().hour |
75 |
minute = dt.time().minute |
76 |
|
77 |
""" Note on usage of the range() function: |
78 |
range(x, y) returns a list, beginning from x, but excluding y. So if a |
79 |
course runs from 13:00 to 15:00, then y should still be 15. Why? Because |
80 |
that makes it so that 14:59 is included, but 15:00 is not. if y would be 16, |
81 |
then 15:30 would also be included. |
82 |
""" |
83 |
|
84 |
# If nothing's returned by now, return a general response |
85 |
return _("Probably chilling a bit. Feel free to talk! ❤") |
86 |
|
87 |
def send_message(name, ip, message): |
88 |
""" Sends a message to me if the visitor submits one on my website. """ |
89 |
# First task: Retrieve the token, which mustn't be in the tracker: |
90 |
with open("token.txt", 'r') as f: |
91 |
url = f.readline() |
92 |
url += name + " (" +str(ip)+ ") stuurt:\n" + message |
93 |
|
94 |
response = requests.get(url) |
95 |
return response.status_code == 200 |
96 |
|
97 |
def contains_hyperlink(string): |
98 |
return ("https://" in string.lower() or "http://" in string.lower()) |
99 |
|
100 |
|
101 |
def add_to_bots(request): |
102 |
# to get_client-ip(), god damn it... |
103 |
client_ip, is_routable = ipw.get_client_ip(request.META) |
104 |
if client_ip is not None: |
105 |
with open('blog/bot-ip-addresses.txt', 'a') as f: |
106 |
print("deny " + str(client_ip) + "; # Abused contact form.", file=f) |
107 |
|
108 |
|
109 |
# Views: |
110 |
|
111 |
def index(request): |
112 |
from django.utils.translation import gettext as _ |
113 |
context = standard_context() |
114 |
# First, handle possible contact |
115 |
if request.method == "POST": # Message received |
116 |
form = MessageForm(request.POST) |
117 |
if form.is_valid(): |
118 |
clean_message = form.cleaned_data |
119 |
# Bot test: |
120 |
if clean_message["provincio"].lower() not in [ |
121 |
"limburg", "limbourg", |
122 |
"antwerpen", "anvers", "antorf", "antorff", |
123 |
"vlaams-brabant", "brabant flamand", "flämisch-brabant", |
124 |
"oost-vlaanderen", "flandre-orientale", "ostflandern", |
125 |
"west-vlaanderen", "flandre-occidentale", "westflandern", |
126 |
"henegouwen", "hainaut", "hennegau", |
127 |
"luik", "liège", "lüttich", |
128 |
"luxemburg", "luxembourg", |
129 |
"namen", "namur", "namür", |
130 |
"waals-brabant", "brabant wallon", "wallonisch-brabant", |
131 |
"brussel", "bruxelles", "brüssel", |
132 |
]: |
133 |
context["contact_response"] = _("The province you entered (") + \ |
134 |
clean_message["provincio"] + _(") was a misspelling, or is not a Belgian province. Message discarded.") |
135 |
elif "henryquorp" in clean_message["name"].lower(): # Removed the hyperlink detector, since I'm allowing that now. |
136 |
add_to_bots(request) |
137 |
else: |
138 |
# Neutralize possible hyperlinks |
139 |
neutralized_message = clean_message["message"].replace(".", ". ") |
140 |
#ipw = ipware.IpWare() # Yea I know, they updated ipware and now you have to do this |
141 |
# to get_client-ip(), god damn it... |
142 |
client_ip, is_routable = ipware.get_client_ip(request.META) |
143 |
if send_message(clean_message["name"], str(client_ip), neutralized_message): |
144 |
from django.utils.translation import gettext as _ |
145 |
context["contact_response"] = _("Message sent!") |
146 |
else: |
147 |
from django.utils.translation import gettext as _ |
148 |
context["contact_response"] = _("An error occured while trying to send the message. Please try again later.") |
149 |
else: # The submitted form data was invalid |
150 |
from django.utils.translation import gettext as _ |
151 |
context["contact_response"] = _("The submitted form contained invalid data, and was discarded.") |
152 |
|
153 |
|
154 |
|
155 |
timezone.activate("Europe/Brussels") |
156 |
time_string = timezone.localtime(timezone.now()).strftime(" (%H:%M) ") |
157 |
#status = _("Current status/location:") + time_string + get_current_status() |
158 |
template = "about/index.djhtml" |
159 |
|
160 |
return render(request, template, context) |
161 |
|
162 |
def verlanglijst(request): |
163 |
context = dict() |
164 |
if request.method == "POST": # Handling a reply if one is sent |
165 |
form = ProductForm(request.POST) |
166 |
if form.is_valid(): |
167 |
product = Product.objects.get(id=form.cleaned_data["product_id"]) |
168 |
product.purchaser = request.META['REMOTE_ADDR'] |
169 |
context["comment_response"] = f"""{ product.name } wordt uit de lijst |
170 |
gehaald voor anderen, het kan vanaf nu enkel vanop dit IP-adres bekeken |
171 |
worden!""" |
172 |
product.save() |
173 |
else: |
174 |
context["comment_response"] = "Er is een fout opgetreden blijkbaar. Oeps." |
175 |
print(form.errors) |
176 |
|
177 |
template = "about/verlanglijst.djhtml" |
178 |
standard_context = { |
179 |
'js': |
180 |
Product.objects.filter(jonathan=True,maarten=False,purchaser=None).order_by("estimated_price"), |
181 |
'ms': |
182 |
Product.objects.filter(jonathan=False,maarten=True,purchaser=None).order_by("estimated_price"), |
183 |
'jms':Product.objects.filter(jonathan=True,maarten=True,purchaser=None).order_by("estimated_price"), |
184 |
'boughts': Product.objects.filter(purchaser=request.META['REMOTE_ADDR']), |
185 |
'address': request.META['REMOTE_ADDR'], |
186 |
} |
187 |
context.update(standard_context) |
188 |
return render(request, template, context) |
189 |
|
190 |
|
191 |
def myself(request): |
192 |
template = "about/about.djhtml" |
193 |
|
194 |
context = { |
195 |
'subject': _("Myself"), |
196 |
'navbar_title': _("Myself"), |
197 |
'age': get_age(), |
198 |
} |
199 |
context.update(standard_context()) |
200 |
return render(request, template, context) |
201 |
|
202 |
def project_archive(request): |
203 |
template = "about/project-archive.djhtml" |
204 |
context = standard_context() |
205 |
return render(request, template, context) |
206 |
|
207 |
def activism(request): |
208 |
template = "about/activism.djhtml" |
209 |
context = standard_context() |
210 |
return render(request, template, context) |
211 |
|
212 |