Skip to content

Commit 3f513de

Browse files
Merge pull request #59 from WeatherGod3218/weather-dev
fix: Wikithoughts auth being lost during runtime
2 parents 9f63b49 + 5e4fb07 commit 3f513de

7 files changed

Lines changed: 62 additions & 16 deletions

File tree

‎Dockerfile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,4 @@ RUN addgroup -g 2000 jumpgroup && adduser -S -u 1001 -G jumpgroup jumpstart && \
2121

2222
USER jumpstart
2323

24-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--log-config", "/jumpstart/logging_config.yaml", "--proxy-headers"]
24+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--log-config", "/jumpstart/logging_config.yaml", "--proxy-headers","--forwarded-allow-ips","*"]

‎docker-compose.yml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,3 @@ services:
2020
- WIKIBOT_USER=${WIKIBOT_USER}
2121
- WIKIBOT_PASSWORD=${WIKIBOT_PASSWORD}
2222
- WIKI_CATEGORY=${WIKI_CATEGORY}
23-

‎src/api/endpoints.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,23 +60,30 @@ async def slack_events(request: Request) -> JSONResponse:
6060
logger.info("Received Slack event!")
6161

6262
body: dict = await request.json()
63-
63+
logger.info(body)
64+
logger.info("\n")
6465
if request.headers.get("content-type") == "application/json":
6566
if body.get("type") == "url_verification":
67+
logger.info("SLACK EVENT: Was a challenge!")
6668
return JSONResponse({"challenge": body.get("challenge")})
6769

6870
if not body:
71+
logger.info("SLACK EVENT: Was a challenge, with no body")
6972
return JSONResponse({"challenge": body.get("challenge")})
7073

7174
event: dict = body.get("event", {})
7275
cleaned_text: str = slack.clean_text(event.get("text", ""))
7376

7477
if event.get("subtype", None) is not None:
78+
logger.info("SLACK EVENT: Had no subtype, ignoring it")
7579
return JSONResponse({"status": "ignored"})
7680

77-
if event not in WATCHED_CHANNELS:
81+
if event.get("channel", None) not in WATCHED_CHANNELS:
82+
logger.info("SLACK EVENT: Message was not in a Watched Channel, returning!")
83+
logger.info(WATCHED_CHANNELS)
7884
return JSONResponse({"status": "ignored"})
7985

86+
logger.info("SLACK EVENT: Requesting upload via dm!")
8087
await slack.request_upload_via_dm(event.get("user", ""), cleaned_text)
8188
except Exception as e:
8289
logger.error(f"Error handling Slack event: {e}")

‎src/core/wikithoughts.py‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,17 @@
88
import random
99
import re
1010

11-
CYCLE_DEBOUNCE_TIME = 12 # How long it takes to resfresh wiki titles
11+
CYCLE_DEBOUNCE_TIME: int = 12 # How long it takes to resfresh wiki titles
1212
BATCH_SIZE: int = 50 # max titles per request
13+
REAUTHENTICATE_ATTEMPTS: int = (
14+
3 # The amount of times it will attempt to re-authenticare
15+
)
1316

1417
HEADERS: dict[str, str] = {"User-Agent": "JumpstartFetcher/1.0"}
1518
AUTH: tuple[str] = (WIKIBOT_USER, WIKIBOT_PASSWORD)
1619

1720
client: httpx.AsyncClient = httpx.AsyncClient(headers=HEADERS, auth=AUTH)
21+
1822
logger: logging.Logger = logging.getLogger(__name__)
1923

2024
bot_authenticated: bool = False
@@ -39,7 +43,7 @@
3943
RE_IMAGE: Pattern[str] = re.compile(r"\[\[Image:[^\]]*\]\]", re.IGNORECASE)
4044
RE_PAGE_TEXT: Pattern[str] = re.compile(r"\[\[[^\|\]]*\|([^\]]+)\]\]")
4145
RE_PAGE: Pattern[str] = re.compile(r"\[\[([^\]]+)\]\]")
42-
RE_CSH: Pattern[str] = re.compile(r"\^\^([^\]]+)\^\^")
46+
RE_CSH: Pattern[str] = re.compile(r"\^\^([^^]+)\^\^")
4347
RE_TEMPLATE: Pattern[str] = re.compile(r"\{\{.*?\}\}", re.DOTALL)
4448
RE_HTML: Pattern[str] = re.compile(r"<[^>]+>")
4549
RE_BOLD_ITALIC: Pattern[str] = re.compile(r"''+")
@@ -89,6 +93,9 @@ def batch_iterable(iterable: list, size: int):
8993
Generator function for splitting up lists into smaller lists
9094
To be frank, found this online when researching about the MediaWiki API
9195
96+
Args:
97+
iterable (list): The iterable to be split up for batches
98+
size (int): the size of the batches
9299
Yields:
93100
A batch split by the requested size
94101
"""
@@ -130,6 +137,7 @@ async def auth_bot() -> None:
130137
bot_authenticated = True
131138
logger.info("Bot was authenticated successfully!")
132139
else:
140+
bot_authenticated = False
133141
logger.warning("Bot was unable to authenticate!")
134142

135143

@@ -172,7 +180,7 @@ def needs_category_refresh(update_time: datetime) -> bool:
172180
update_time (datetime): The datetime to be compared against the cache
173181
174182
Returns:
175-
boolean: if the cache needs to be refreshed
183+
bool: if the cache needs to be refreshed
176184
"""
177185

178186
if not bot_authenticated:
@@ -186,17 +194,16 @@ def needs_category_refresh(update_time: datetime) -> bool:
186194
)
187195

188196

189-
def process_category_page(response: httpx.Response) -> tuple[list[str], bool | str]:
197+
def process_category_page(r_json: dict[str, str]) -> tuple[list[str], bool | str]:
190198
"""
191199
Processes a wikithoughts response into a list of title pages
192200
193201
Args:
194-
respone (httpx.Response): The response from the wiki to be processed
202+
r_json (dict[str,str]): The JSON from the wiki to be processed
195203
196204
Returns:
197205
tuple[list[str], bool | str]: The list of titles from the request, along with a possible continutation if needed
198206
"""
199-
r_json: dict[str, str] = response.json()
200207
titles: list[str] = []
201208
if "query" in r_json:
202209
for page in r_json["query"]["categorymembers"]:
@@ -239,6 +246,9 @@ async def refresh_category_pages() -> list[str]:
239246

240247
headers: dict[str, str] = headers_formatting()
241248
# This needs to loop due to mediawiki limitations
249+
250+
failed_authentication_attempts: int = 0
251+
242252
while True:
243253
response: httpx.Response = await client.get(
244254
WIKI_API, params=params, headers=headers
@@ -250,7 +260,30 @@ async def refresh_category_pages() -> list[str]:
250260

251261
elif response.status_code == 200:
252262
headers_formatting(etag, last_modifed)
253-
added, repeat_req = process_category_page(response=response)
263+
r_json: dict[str, str] = response.json()
264+
265+
if "error" in r_json and r_json["error"].get("code") in (
266+
"readapidenied",
267+
"notloggedin",
268+
):
269+
if failed_authentication_attempts > REAUTHENTICATE_ATTEMPTS:
270+
logger.warning(
271+
"Reauthenticating the wikithought bot failed, sending empty response"
272+
)
273+
return []
274+
275+
logger.info(f"Both was unauthenticated, attempting to reauthenticate!")
276+
await auth_bot()
277+
if not (bot_authenticated):
278+
logger.warning(
279+
"Failed to reauthenticate the bot! Attempt: "
280+
+ failed_authentication_attempts
281+
)
282+
283+
failed_authentication_attempts += 1
284+
continue
285+
286+
added, repeat_req = process_category_page(r_json)
254287
titles += added
255288

256289
if repeat_req not in (None, False, ""):

‎src/static/css/style.css‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
body{
22
background-image: url('/static/img/darkmodeF.png');
3+
overflow: hidden;
4+
}
5+
6+
.scroll-container::-webkit-scrollbar {
7+
display: none;
8+
width: 0; /* Ensures no width is reserved for the scrollbar */
9+
height: 0; /* Ensures no height is reserved for the horizontal scrollbar */
310
}
411

512
.panel-primary{
@@ -45,6 +52,7 @@ body{
4552
border: 8px #34495e solid;
4653
border-radius: 10px;
4754
background-color: #34495e;
55+
margin-bottom: 1.5%;
4856
}
4957

5058
.datadog{
@@ -56,15 +64,15 @@ body{
5664
width: 760px;
5765
height: 580px;
5866
float: right;
59-
margin-bottom: 3%;
67+
margin-bottom: 0.5%;
6068
}
6169

6270
.announcements{
6371
float: left;
6472
width: 50%;
6573
padding-top: 22%;
6674
padding-left: 1%;
67-
min-height: 840px;
75+
min-height: 670px;
6876
overflow: hidden;
6977
word-wrap: break-word;
7078
}

‎src/static/js/main.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,4 @@ longUpdate();
8383

8484
setInterval(longUpdate, 60000);
8585
setInterval(mediumUpdate, 22000);
86-
setInterval(() => { if (window.__weatherwidget_init) window.__weatherwidget_init(); }, 1800000);
86+
setInterval(() => { if (globalThis.__weatherwidget_init) globalThis.__weatherwidget_init(); }, 1800000);

‎src/templates/index.html‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
</div>
1515
</div>
1616
<div class="row justify-content-around">
17-
<div class="col-md-10" align="left">
17+
<div class="col-md-10">
1818
<iframe class="datadog" id="datadog" scrolling="no" frameborder="0" src="https://p.datadoghq.com/sb/44f16805b-4c2038873e353ef6fbb5cd49d9d2b1ac?theme=light&tv_mode=true&live=true?"></iframe>
1919
<div class="announcements mt-3">
2020
<div class="panel panel-primary">
@@ -73,5 +73,4 @@
7373
</div>
7474
</div>
7575
<script src="https://weatherwidget.io/js/widget.min.js" integrity="sha384-z1SrZstAkfpo40+eVsXy73T2tzbGOviy6svjVLsoiZvGhs2mgIMzFdWh1YSuoH9D" crossorigin="anonymous"></script>
76-
<script src="{{ url_for('static', path='js/main.js') }}"></script>
7776
{% endblock %}

0 commit comments

Comments
 (0)