-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
237 lines (194 loc) · 8.47 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import logging
import warnings
import sys
import html
import os
from json import loads
import requests
from datetime import datetime
from seleniumrequests import Firefox
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulSoup
from calendar_adapter import CalendarAdapter
from facebook_adapter import FacebookAdapter, get_long_lived_token
from text_transforms import trim_list, get_list, render_unicode, render_whatsapp
from unilife_adapter import UnilifeAdapter
from utils import DEFAULT_TZ, ask_confirmation
headers = {
"Cache-Control": "no-cache",
"Pragma": "no-cache"
}
def get_events():
print("Getting events from website")
events_raw = requests.get("https://dsda.nl/wp-json/wp/v2/tribe_events?per_page=25", headers=headers).json()
events = [{'name': html.unescape(event['title']['rendered']), 'content': event['content']['rendered'],
'link': event['link'], 'slug': event['slug']} for event in events_raw]
return events
def get_event_info(event: dict) -> dict:
event_page = requests.get(event['link'], headers=headers)
soup = BeautifulSoup(event_page.text, 'html.parser')
start_date = soup.find("abbr", "tribe-events-start-date")['title']
end_date = soup.find("div", "tribe-events-start-time")['title']
times = soup.find("div", "tribe-events-start-time").text.strip()
times = times.split(' - ')
event['start_date'] = start_date
event['end_date'] = end_date
event['start_time'] = times[0]
event['end_time'] = times[1]
event['start'] = DEFAULT_TZ.localize(
datetime.strptime(f"{event['start_date']} {event['start_time']}", "%Y-%m-%d %H:%M"))
event['end'] = DEFAULT_TZ.localize(datetime.strptime(f"{event['end_date']} {event['end_time']}", "%Y-%m-%d %H:%M"))
try:
event['venue'] = soup.find("dd", "tribe-venue").text.strip()
except AttributeError:
event['venue'] = ''
if soup.find("span", "tribe-street-address") is not None:
try:
address = soup.find("span", "tribe-street-address").text.strip()
except AttributeError:
address = ''
try:
postal_code = soup.find("span", "tribe-postal-code").text.strip()
except AttributeError:
postal_code = ''
try:
locality = soup.find("span", "tribe-locality").text.strip()
except AttributeError:
locality = ''
event['address'] = f'{address}, {postal_code} {locality}'
else:
event['address'] = ''
try:
categories_wrapper = soup.find("dd", "tribe-events-event-categories")
categories = [cat.text for cat in categories_wrapper.find_all('a')]
except AttributeError:
categories = []
event['categories'] = categories
content_soup = BeautifulSoup(event['content'], 'html.parser')
content_text_list = trim_list(get_list(content_soup.children))
event['content-unicode'] = render_unicode(content_text_list)
event['content-whatsapp'] = render_whatsapp(content_text_list) + f"\n\nAll details:\n{event['link']}"
image_tag = soup.find("img", "wp-post-image")
if image_tag is not None:
image_url = image_tag['src']
r = requests.get(image_url, stream=True, headers=headers)
if r.status_code == 200:
extension = image_url.split(".")[-1].lower()
event['image_name'] = f'event-image.{extension}'
with open(event['image_name'], 'wb') as f:
import shutil
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
else:
warnings.warn("Could not download event image.")
else:
event['image_name'] = None
warnings.warn("Event does not have an image.")
return event
def create_driver():
ff_path = 'geckodriver.exe' # Same Directory as Python Program
service = Service(executable_path=ff_path)
options = Options()
options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe'
driver = Firefox(service=service, options=options)
driver.implicitly_wait(5)
return driver
def get_config() -> dict:
"""
Get the authentication data from either the credentials.json file, or environment variables.
:return: Authentication config
"""
try:
with open("credentials.json", "r", encoding="utf-8") as f:
conf = loads(f.read())
except FileNotFoundError as error:
print("Could not find credentials.json")
conf["FACEBOOK_ID"] = os.getenv("FACEBOOK_ID", conf.get("FACEBOOK_ID"))
conf["FACEBOOK_PASSWORD"] = os.getenv("FACEBOOK_PASSWORD", conf.get("FACEBOOK_PASSWORD"))
conf["FACEBOOK_TOTP"] = os.getenv("FACEBOOK_TOTP", conf.get("FACEBOOK_TOTP"))
conf["FACEBOOK_GRAPH_API_TOKEN"] = os.getenv("FACEBOOK_GRAPH_API_TOKEN", conf.get("FACEBOOK_GRAPH_API_TOKEN"))
conf["FACEBOOK_APP_ID"] = os.getenv("FACEBOOK_APP_ID", conf.get("FACEBOOK_APP_ID"))
conf["FACEBOOK_APP_SECRET"] = os.getenv("FACEBOOK_APP_SECRET", conf.get("FACEBOOK_APP_SECRET"))
conf["UNILIFE_ID"] = os.getenv("UNILIFE_ID", conf.get("UNILIFE_ID"))
conf["UNILIFE_PASSWORD"] = os.getenv("UNILIFE_PASSWORD", conf.get("UNILIFE_PASSWORD"))
assert conf["FACEBOOK_ID"] is not None
assert conf["FACEBOOK_PASSWORD"] is not None
assert conf["FACEBOOK_TOTP"] is not None
assert conf["FACEBOOK_GRAPH_API_TOKEN"] is not None
assert conf["UNILIFE_ID"] is not None
assert conf["UNILIFE_PASSWORD"] is not None
return conf
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
config = get_config()
print("Event publisher, at your service")
# get_long_lived_token(config) # Use when you need such a token. Obviously.
calendar = CalendarAdapter()
driver = None
unilife_adapter = None
facebook_adapter = None
quit_loop = False
bulk_mode = False
while not quit_loop:
events = get_events()
continue_loop = False
# Interfacing with user
# Select event or quit
print("\nSelect event to process:")
print(" Press q to quit, r to refresh, b to turn on bulk mode.")
for i, event in enumerate(events):
print(f" {i + 1}: {event['name']}")
pass
choice = -1
while choice <= 0 or choice > len(events):
_input = input("Pick: ")
if _input == 'b':
bulk_mode = not bulk_mode
print(f"Turned bulk mode {'on' if bulk_mode else 'off'}.")
continue
if _input == 'q':
quit_loop = True
break
if _input == 'r':
continue_loop = True
break
choice = int(_input)
if quit_loop:
print("Quitting")
break
if continue_loop:
continue
# Actual work with the event
event = events[choice - 1]
try:
event = get_event_info(event)
except Exception as e:
print("Error while getting event information")
logging.exception(e)
continue
print(f"Processing {event['name']} on {event['start_date']}")
if bulk_mode or ask_confirmation("Do you want to put this in the Google Calendar?"):
g_events = calendar.do_event(event)
# Unilife is, unfortunately, not used anymore by the TU Delft.
# if bulk_mode or ask_confirmation("Do you want to put this event on Unilife?"):
# if driver is None:
# driver = create_driver()
# if unilife_adapter is None:
# unilife_adapter = UnilifeAdapter(driver, config["UNILIFE_ID"], config["UNILIFE_PASSWORD"])
# unilife_success = unilife_adapter.do_event(event)
# Move based on what you want to bulk
if bulk_mode:
continue
if bulk_mode or ask_confirmation("Do you want to put this event on Facebook?"):
if driver is None:
driver = create_driver()
if facebook_adapter is None:
facebook_adapter = FacebookAdapter(driver, config["FACEBOOK_ID"], config["FACEBOOK_PASSWORD"],
config["FACEBOOK_TOTP"], config["FACEBOOK_GRAPH_API_TOKEN"])
facebook_adapter.do_event(event)
if bulk_mode or ask_confirmation("Do you want a WhatsApp share message?"):
print() # New line
print(event['content-whatsapp'])
if driver is not None:
driver.quit()