This repository was archived by the owner on May 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1868 lines (1592 loc) · 68.8 KB
/
Copy pathmain.py
File metadata and controls
1868 lines (1592 loc) · 68.8 KB
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import re
import subprocess
import traceback
from datetime import datetime
from urllib.parse import unquote, urlparse
import aiohttp
import asyncpg
import firebase_admin
import jinja2
import requests
import tornado.escape
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
from dotenv import load_dotenv
from firebase_admin import credentials, messaging
from tornado.web import Application, HTTPError, RequestHandler, url
cred = credentials.Certificate("hbni-audio-1c43f2c03734.json")
firebase_admin.initialize_app(cred)
load_dotenv()
loader = jinja2.FileSystemLoader("dist/html")
env = jinja2.Environment(loader=loader)
class Broadcast:
def __init__(
self,
host: str,
description: str,
password: str,
is_private: bool,
start_time: datetime,
):
self.host = host
self.description = description
self.password = password
self.is_private = is_private
self.start_time = start_time
active_broadcasts: dict[str, Broadcast] = {}
db_pool: asyncpg.Pool = None
error_messages = {
500: "Oooops! Internal Server Error. That is, something went terribly wrong.",
404: "Uh-oh! You seem to have ventured into the void. This page doesn't exist!",
403: "Hold up! You're trying to sneak into a restricted area. Access denied!",
400: "Yikes! The server couldn't understand your request. Try being clearer!",
401: "Hey, who goes there? You need proper credentials to enter!",
405: "Oops! You knocked on the wrong door with the wrong key. Method not allowed!",
408: "Well, this is awkward. Your request took too long. Let's try again?",
502: "Looks like the gateway had a hiccup. It's not you, it's us!",
503: "We're taking a quick nap. Please try again later!",
418: "I'm a teapot, not a coffee maker! Why would you ask me to do that?",
}
audio_archive_cache = {
"data": {},
"grouped_data": {},
"last_updated": datetime.min,
}
love_taps_cache = {
"data": {},
"last_updated": datetime.min,
}
active_broadcasts_chache = {
"data": {},
"active_broadcasts_count": 0,
"last_updated": datetime.min,
}
schedule_chache = {
"all_schedules": [],
"active_schedules": [],
"active_schedules_count": 0,
"last_updated": datetime.min,
}
trending_archives_cache = {"data": {}, "last_update": datetime.min}
recording_status_chache = {
"data": {},
"recording_status_count": 0,
"last_updated": datetime.min,
}
db_settings = {
"host": os.getenv("POSTGRES_HOST"),
"port": int(os.getenv("POSTGRES_PORT", 5434)),
"database": os.getenv("POSTGRES_DB"),
"user": os.getenv("POSTGRES_USER"),
"password": os.getenv("POSTGRES_PASSWORD"),
}
recording_files_share_hashes = {}
FILEBROWSER_URL = os.getenv("FILEBROWSER_URL")
FILEBROWSER_USERNAME = os.getenv("FILEBROWSER_USERNAME")
FILEBROWSER_PASSWORD = os.getenv("FILEBROWSER_PASSWORD")
FILEBROWSER_UPLOAD_PATH = os.getenv("FILEBROWSER_UPLOAD_PATH", "HBNI-Audio/Recordings")
# Global dict of filebrowser items {name: full_path}
FILEBROWSER_ITEMS = {}
async def get_filebrowser_token():
async with aiohttp.ClientSession() as session:
async with session.post(
f"{os.getenv('FILEBROWSER_URL')}/api/login",
json={
"username": os.getenv("FILEBROWSER_USERNAME"),
"password": os.getenv("FILEBROWSER_PASSWORD"),
},
) as response:
token = await response.text()
return token.strip()
async def get_public_share_url(file_relative_path: str, token: str) -> str:
headers = {"X-Auth": token.strip(), "accept": "*/*"}
async with aiohttp.ClientSession() as session:
async with session.post(
f"{FILEBROWSER_URL}/api/share/{file_relative_path}",
headers=headers,
json={"path": f"/{file_relative_path}"},
) as response:
if response.status != 200:
body = await response.text()
raise Exception(f"Failed to create share link: {response.status} - {body}")
data = await response.json()
return data["hash"]
async def list_filebrowser_items():
global FILEBROWSER_ITEMS
token = await get_filebrowser_token()
headers = {"X-Auth": token, "Accept": "application/json"}
async with aiohttp.ClientSession() as session:
async with session.get(
f"{FILEBROWSER_URL}/api/resources/{FILEBROWSER_UPLOAD_PATH}",
headers=headers,
) as response:
if response.status != 200:
body = await response.text()
raise Exception(f"Failed to list items: {response.status} - {body}")
data = await response.json()
items = data.get("items", [])
FILEBROWSER_ITEMS = {item["name"]: item["path"].lstrip("/") for item in items if not item["isDir"]}
def extract_filename_from_download_link(download_link: str) -> str:
path = urlparse(download_link).path
return unquote(os.path.basename(path)).replace("&", "&").replace("&Amp;", "&")
async def update_audio_hashes():
await list_filebrowser_items()
token = await get_filebrowser_token()
async with db_pool.acquire() as conn:
query = """
SELECT * FROM audioarchives
WHERE download_link LIKE '%play_recording%'
ORDER BY date DESC;
"""
rows = await conn.fetch(query)
for row in rows:
download_link = row["download_link"]
filename = extract_filename_from_download_link(download_link)
current_hash = row["share_hash"]
# if current_hash:
# print(f"✅ Already has share_hash: {filename} → {current_hash}")
# continue
filebrowser_path = FILEBROWSER_ITEMS.get(filename)
if not filebrowser_path:
print(f"⚠️ File not found in FileBrowser: {filename}")
continue
try:
share_hash = await get_public_share_url(filebrowser_path, token)
update_query = "UPDATE audioarchives SET share_hash = $1 WHERE download_link = $2;"
await conn.execute(update_query, share_hash, download_link)
print(f"✅ Added share_hash for: {filename} → {share_hash}")
except Exception as e:
print(f"❌ Failed to create share for {filename}: {str(e)}")
async def initialize_db_pool():
global db_pool
db_pool = await asyncpg.create_pool(
host=os.getenv("POSTGRES_HOST"),
port=os.getenv("POSTGRES_PORT"),
database=os.getenv("POSTGRES_DB"),
user=os.getenv("POSTGRES_USER"),
password=os.getenv("POSTGRES_PASSWORD"),
min_size=int(os.getenv("POSTGRES_MIN_SIZE", default=5)), # Minimum number of connections
max_size=int(os.getenv("POSTGRES_MAX_SIZE", default=10)), # Adjust based on expected load
)
async def fetch_audio_archives():
try:
async with db_pool.acquire() as conn:
rows = await conn.fetch("SELECT * FROM audioarchives")
return [dict(row) for row in rows]
except Exception as e:
print(f"Database fetch error: {e}")
return []
async def update_visit(file_name):
async with db_pool.acquire() as conn:
await conn.execute(
"""
UPDATE audioarchives
SET visit_count = COALESCE(visit_count, 0) + 1, latest_visit = $1
WHERE filename = $2
""",
datetime.now(),
file_name,
)
async def execute_query(query: str, *params):
async with db_pool.acquire() as conn:
return await conn.fetchrow(query, *params)
def format_length(length_in_minutes):
hours, minutes = divmod(int(length_in_minutes), 60)
hours_string = f"{hours} hour{'s' if hours > 1 else ''}" if hours > 0 else ""
minutes_string = f"{minutes} minute{'s' if minutes != 1 else ''}" if minutes > 0 else ""
if hours_string and minutes_string:
return f"{hours_string}, {minutes_string}"
elif not minutes_string:
return "Just Started"
return hours_string or minutes_string
def get_duration(stream_start: str) -> float:
start_time = datetime.strptime(stream_start, "%a, %d %b %Y %H:%M:%S %z")
current_time = datetime.now(start_time.tzinfo)
duration = current_time - start_time
return duration.total_seconds() / 60
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
now = datetime.now()
diff_days = (now.date() - obj.date()).days
base_str = obj.strftime("%B %d %A %Y %I:%M %p")
if diff_days == 0:
day_ago_str = "(Today)"
elif diff_days == 1:
day_ago_str = "(Yesterday)"
else:
day_ago_str = f"({diff_days} days ago)"
return f"{base_str} {day_ago_str}"
return super().default(obj)
def get_grouped_data(audio_data):
today = datetime.today()
groups = {
"Today": [],
"Yesterday": [],
"Two Days Ago": [],
"Three Days Ago": [],
"Sometime This Week": [],
"Last Week": [],
"Sometime This Month": [],
"Last Month": [],
"Two Months Ago": [],
"Three Months Ago": [],
"Sometime This Year": [],
"Last Year": [],
"Two Years Ago": [],
"Three Years Ago": [],
"Everything Else": [],
}
for row in audio_data:
item_data = dict(row)
item_data["formatted_length"] = format_length(item_data["length"])
item_data["static_url"] = url_for_static(item_data["filename"])
item_date = datetime.strptime(row["date"], "%B %d %A %Y %I_%M %p")
diff_days = (today.date() - item_date.date()).days
item_data["item_date_obj"] = item_date
if diff_days == 0:
item_data["uploaded_days_ago"] = "Today"
elif diff_days == 1:
item_data["uploaded_days_ago"] = "Yesterday"
else:
item_data["uploaded_days_ago"] = f"{diff_days} days ago"
if diff_days == 0:
groups["Today"].append(item_data)
continue
elif diff_days == 1:
groups["Yesterday"].append(item_data)
continue
elif diff_days == 2:
groups["Two Days Ago"].append(item_data)
continue
elif diff_days == 3:
groups["Three Days Ago"].append(item_data)
continue
elif diff_days <= 7:
groups["Sometime This Week"].append(item_data)
continue
elif diff_days <= 14:
groups["Last Week"].append(item_data)
continue
def month_diff(now: datetime, then: datetime) -> int:
return (now.year - then.year) * 12 + (now.month - then.month)
m_diff = month_diff(today, item_date)
if m_diff == 0:
groups["Sometime This Month"].append(item_data)
continue
elif m_diff == 1:
groups["Last Month"].append(item_data)
continue
elif m_diff == 2:
groups["Two Months Ago"].append(item_data)
continue
elif m_diff == 3:
groups["Three Months Ago"].append(item_data)
continue
y_diff = today.year - item_date.year
if y_diff == 0:
groups["Sometime This Year"].append(item_data)
elif y_diff == 1:
groups["Last Year"].append(item_data)
elif y_diff == 2:
groups["Two Years Ago"].append(item_data)
elif y_diff == 3:
groups["Three Years Ago"].append(item_data)
else:
groups["Everything Else"].append(item_data)
for group_name, items in groups.items():
items.sort(key=lambda x: x["item_date_obj"], reverse=True)
desired_order = [
"Today",
"Yesterday",
"Two Days Ago",
"Three Days Ago",
"Sometime This Week",
"Last Week",
"Sometime This Month",
"Last Month",
"Two Months Ago",
"Three Months Ago",
"Sometime This Year",
"Last Year",
"Two Years Ago",
"Three Years Ago",
"Everything Else",
]
# Build a final dict in that order, skipping empty groups
final_groups = {}
for key in desired_order:
if groups[key]: # Not empty
final_groups[key] = groups[key]
return final_groups
def is_broadcast_private(host: str) -> bool:
if (broadcast := active_broadcasts.get(host)) and broadcast.is_private:
return True
host_lc = host.lower()
return any(keyword in host_lc for keyword in ("priv", "prv", "private"))
def get_active_icecast_broadcasts() -> list[dict[str, str | int]] | None:
broadcast_data = []
icecast_urls = [
"https://hbniaudio.hbni.net",
]
for icecast_url in icecast_urls:
try:
response = requests.get(f"{icecast_url}/status-json.xsl", timeout=10)
if response.status_code == 200:
json_content = response.text.replace('"title": - ,', '"title": null,') # Some broadcasts are weird
json_data = json.loads(json_content)
else:
continue
except Exception as e:
print(e)
continue
# Extract relevant data for rendering
icestats = json_data.get("icestats", {})
sources = icestats.get("source", {})
# Prepare data for template rendering
if sources:
if isinstance(sources, dict):
sources = [sources]
for source in sources:
is_private_by_genre = source.get("genre", "various") == "private"
mount_point = source.get("listenurl", "/").split("/")[-1]
broadcast_data.append(
{
"admin": icestats.get("admin", "N/A"),
"location": icestats.get("location", "N/A"),
"server_name": source.get("server_name", "Unspecified name"),
"server_description": source.get("server_description", "Unspecified description"),
"genre": source.get("genre", "various"),
"listeners": source.get("listeners", 0),
"host": mount_point,
"colony": mount_point,
"mount_point": mount_point,
"listener_peak": source.get("listener_peak", 0),
"listen_url": source.get("listenurl", f"{icecast_url}/{mount_point}"),
"stream_start": source.get("stream_start", "N/A"),
"is_private": is_broadcast_private(mount_point) or is_private_by_genre,
"source_url": icecast_url,
"length": f"{format_length(get_duration(source.get('stream_start', 'N/A')))}",
}
)
return broadcast_data
async def get_recording_files_share_hashes():
global recording_files_share_hashes
token = await get_filebrowser_token()
headers = {"X-Auth": token.strip(), "accept": "*/*"}
async with aiohttp.ClientSession() as session:
async with session.get(
f"{os.getenv('FILEBROWSER_URL')}/api/shares",
headers=headers,
) as response:
if response.status != 200:
body = await response.text()
raise Exception(f"Failed to create share link: {response.status} - {body}")
data = await response.json()
for shared_file in data:
recording_files_share_hashes.update({shared_file["hash"]: shared_file["path"].split("/")[-1]})
def get_active_broadcast_count(broadcast_data) -> int:
active_broadcast_count = 0
for broadcast in broadcast_data:
if not broadcast.get("is_private", False):
active_broadcast_count += 1
return active_broadcast_count
class AnalyticsMixin:
async def track_visit(self):
try:
path = self.request.path
user_agent = self.request.headers.get("User-Agent", "Unknown")
ip_address = self.request.remote_ip
referrer = self.request.headers.get("Referer", "Direct")
async with db_pool.acquire() as conn:
await conn.execute(
"""
INSERT INTO page_analytics
(path, user_agent, ip_address, referrer)
VALUES ($1, $2, $3, $4)
""",
path,
user_agent,
ip_address,
referrer,
)
except Exception as e:
print(f"Error tracking analytics: {e}")
class BaseHandler(RequestHandler, AnalyticsMixin):
async def prepare(self):
await self.track_visit()
if broadcast_name := self._extract_broadcast_name():
for broadcast in active_broadcasts_chache["data"]:
if broadcast.get("host") == broadcast_name:
self.redirect(f"/play_live/{broadcast_name}")
self._finished = True
return
def write_error(self, status_code: int, **kwargs):
error_message = error_messages.get(status_code, "Something went majorly wrong.")
template = env.get_template("error.html")
rendered_template = template.render(error_code=status_code, error_message=error_message)
self.write(rendered_template)
def _extract_broadcast_name(self) -> str | None:
# Extracts the broadcast name from the URL if it looks like /play_live/<broadcast_name> or similar
path = self.request.path
match = re.search(r"/([a-zA-Z0-9_-]+)", path)
return match.group(1) if match else None
async def refresh_archive_data():
global audio_archive_cache, recording_files_share_hashes
try:
async with db_pool.acquire() as conn:
rows = await conn.fetch("""
SELECT * FROM audioarchives
WHERE download_link IS NOT NULL
AND download_link <> ''
AND NOT (
download_link LIKE '%mega.nz%' OR
download_link LIKE '%mega.co.nz%'
)
""")
updated_data = [dict(row) for row in rows]
audio_archive_cache["data"] = updated_data
audio_archive_cache["grouped_data"] = get_grouped_data(updated_data)
audio_archive_cache["last_updated"] = datetime.now()
except Exception as e:
print(f"Error refreshing archive data: {e}")
def refresh_active_broadcasts_data():
global active_broadcasts_chache
try:
updated_data = get_active_icecast_broadcasts()
if updated_data is None:
return
active_broadcasts_chache["data"] = updated_data
active_broadcasts_chache["active_broadcasts_count"] = get_active_broadcast_count(updated_data)
active_broadcasts_chache["last_updated"] = datetime.now()
except Exception as e:
print(f"Error refreshing active broadcasts data: {e}")
async def refresh_scedule_data():
global schedule_chache
try:
async with db_pool.acquire() as conn:
rows = await conn.fetch("""
SELECT id, host, description, duration, speakers, start_time
FROM scheduledbroadcasts
ORDER BY created_at DESC
""")
updated_data = {}
for row in rows:
parsed_time = datetime.strptime(row["start_time"], "%Y-%m-%d %H:%M")
formatted_time = parsed_time.strftime("%A, %B %d, %Y at %I:%M %p")
updated_data[row["id"]] = {
"id": row["id"],
"host": row["host"],
"description": row["description"],
"speakers": row["speakers"],
"duration": row["duration"],
"start_time": row["start_time"],
"formatted_time": formatted_time,
}
schedule_chache["all_schedules"] = updated_data
current_time = datetime.now() # Filter schedules where start_time is in the future or within the last 2 hours
filtered_schedules = []
for schedule_id, schedule in updated_data.items():
try:
start_time = datetime.strptime(schedule["start_time"], "%Y-%m-%d %H:%M")
time_diff = start_time - current_time
hours_diff = time_diff.total_seconds() / 3600
if hours_diff >= -2:
filtered_schedules.append((start_time, schedule_id, schedule))
except ValueError as e:
print(f"Error parsing date for schedule {schedule_id}: {e}")
continue
# Sort the filtered schedules by datetime
filtered_schedules.sort()
# Rebuild the active_schedules dict in sorted order
active_schedules = {schedule_id: schedule for _, schedule_id, schedule in filtered_schedules}
active_schedules_count = len(active_schedules)
schedule_chache["active_schedules"] = active_schedules
schedule_chache["active_schedules_count"] = active_schedules_count
schedule_chache["last_updated"] = datetime.now()
except Exception as e:
print(f"Error refreshing schedule data: {e}")
async def ensure_recording_status_table():
async with db_pool.acquire() as conn:
await conn.execute("""
CREATE TABLE IF NOT EXISTS recording_status (
host TEXT PRIMARY KEY,
link TEXT NOT NULL,
length TEXT NOT NULL,
description TEXT,
starting_time TEXT NOT NULL,
last_updated TIMESTAMPTZ DEFAULT NOW()
);
""")
async def refresh_recording_status_data():
global recording_status_chache
# await ensure_recording_status_table()
try:
async with db_pool.acquire() as conn:
rows = await conn.fetch("SELECT host, link, length, description, starting_time FROM recording_status")
updated_data = {
row["host"]: {
"link": row["link"],
"length": row["length"],
"description": row["description"],
"starting_time": row["starting_time"],
}
for row in rows
}
recording_status_chache["data"] = updated_data
recording_status_chache["recording_status_count"] = len(updated_data)
recording_status_chache["last_updated"] = datetime.now()
except Exception as e:
print(f"Error refreshing recording status data: {e}")
async def refresh_love_taps_cache():
global love_taps_cache
async with db_pool.acquire() as conn:
row = await conn.fetchrow("SELECT SUM(tap_count) as total_taps FROM love_taps")
total_taps = row["total_taps"] or 0
love_taps_cache["data"] = total_taps
love_taps_cache["last_updated"] = datetime.now()
async def refresh_trending_archives():
global trending_archives_cache
try:
async with db_pool.acquire() as conn:
# Get the most visited recording_stats pages from the last 24 hours
trending_recordings = await conn.fetch("""
SELECT
path,
COUNT(*) as visit_count
FROM page_analytics
WHERE
path LIKE '/recording_stats/%'
AND timestamp >= CURRENT_TIMESTAMP - INTERVAL '24 hours'
GROUP BY path
ORDER BY visit_count DESC
LIMIT 10
""")
trending_archives = []
for record in trending_recordings:
filename = record["path"].replace("/recording_stats/", "")
filename = tornado.escape.url_unescape(filename)
matching_archive = None
for archive in audio_archive_cache["data"]:
if archive["filename"] == filename:
item_date = datetime.strptime(archive["date"], "%B %d %A %Y %I_%M %p")
diff_days = (datetime.today().date() - item_date.date()).days
uploaded_days_ago = f"{diff_days} days ago"
if diff_days == 0:
uploaded_days_ago = "Today"
elif diff_days == 1:
uploaded_days_ago = "Yesterday"
matching_archive = {
**archive,
"analytic_visit_count": record["visit_count"],
"trending_rank": len(trending_archives) + 1,
"formatted_length": format_length(archive["length"]),
"uploaded_days_ago": uploaded_days_ago,
}
break
if matching_archive:
trending_archives.append(matching_archive)
trending_archives_cache["data"] = trending_archives
trending_archives_cache["last_updated"] = datetime.now()
except Exception as e:
print(f"Error refreshing trending archives: {e}")
class GetArchiveDataHandler(BaseHandler):
def get(self):
try:
self.set_header("Content-Type", "application/json")
self.write(json.dumps(audio_archive_cache["grouped_data"], cls=DateTimeEncoder))
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class GetScheduleDataHandler(BaseHandler):
def get(self):
try:
self.set_header("Content-Type", "application/json")
self.write(json.dumps(schedule_chache["all_schedules"], cls=DateTimeEncoder))
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class GetActiveSchedulesDataHandler(BaseHandler):
def get(self):
try:
self.set_header("Content-Type", "application/json")
self.write(json.dumps(schedule_chache["active_schedules"], cls=DateTimeEncoder))
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class GetEventCountHandler(BaseHandler):
def get(self):
self.set_header("Content-Type", "application/json")
self.write(
json.dumps(
{
"broadcast_count": active_broadcasts_chache["active_broadcasts_count"],
"scheduled_broadcast_count": schedule_chache["active_schedules_count"],
}
)
)
class LoveTapsUpdateHandler(tornado.web.RequestHandler):
async def post(self):
try:
data = json.loads(self.request.body)
count = data.get("count", 0)
if count > 0:
async with db_pool.acquire() as conn:
await conn.execute(
"""
INSERT INTO love_taps (tap_count, timestamp)
VALUES ($1, $2)
""",
count,
datetime.now(),
)
self.write({"status": "success"})
except Exception as e:
self.set_status(500)
self.write({"status": "error", "message": str(e)})
class LoveTapsFetchHandler(BaseHandler):
def get(self):
try:
self.write({"count": love_taps_cache["data"]})
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class SubscribeToTopicHandler(BaseHandler):
def post(self):
try:
data = json.loads(self.request.body)
token = data.get("token")
topic = data.get("topic", "broadcasts") # Default topic if not provided
if not token:
self.set_status(400)
self.write({"error": "Token is required"})
return
# Subscribe the token to the topic
response = messaging.subscribe_to_topic([token], topic)
# Extract relevant fields from the response
result = {
"success_count": response.success_count,
"failure_count": response.failure_count,
"errors": [str(error) for error in response.errors],
}
self.set_status(200)
self.write(
{
"success": True,
"message": f"Successfully subscribed to topic {topic}",
"response": result, # Include extracted information
}
)
except Exception as e:
self.set_status(500)
self.write({"error": f"An error occurred: {str(e)}"})
def send_notification_to_topic(topic, title, body):
try:
message = messaging.Message(
notification=messaging.Notification(
title=title,
body=body,
image="/static/icon.png",
),
data={
"link": "https://broadcasting.hbni.net/events",
},
topic=topic,
)
response = messaging.send(message)
print(f"Successfully sent message to topic {topic}: {response}")
except Exception as e:
print(f"Failed to send message: {e}")
class MainHandler(BaseHandler):
def get(self):
try:
template = env.get_template("index.html")
rendered_template = template.render()
self.set_header("Cache-Control", "max-age=3600")
self.set_header("Content-Type", "text/html")
self.write(rendered_template)
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class GoogleHandler(BaseHandler):
def get(self):
self.write("google-site-verification: google9d968a11b4bf61f7.html")
class SitemapHandler(BaseHandler):
def get(self):
with open("static/sitemap.xml", "r") as f:
self.set_header("Content-Type", "application/xml")
self.write(f.read())
class SystemInfoHandler(BaseHandler):
def get(self):
try:
self.set_header("Content-Type", "application/json")
system_info = {
"hostname": os.getenv("HOSTNAME"),
"port": os.getenv("PORT"),
"timezone": os.getenv("TZ"),
}
self.write(json.dumps(system_info, indent=4))
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class FaviconHandler(BaseHandler):
def get(self):
try:
self.set_header("Content-Type", "image/png")
self.write(open("static/icon.png", "rb").read())
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class FaqHandler(BaseHandler):
def get(self):
try:
template = env.get_template("faq.html")
rendered_template = template.render()
self.set_header("Cache-Control", "max-age=3600")
self.set_header("Content-Type", "text/html")
self.write(rendered_template)
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class BroadcastingGuideHandler(BaseHandler):
def get(self):
try:
template = env.get_template("broadcasting_guide.html")
rendered_template = template.render()
self.set_header("Cache-Control", "max-age=3600")
self.set_header("Content-Type", "text/html")
self.write(rendered_template)
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class PrivacyHandler(BaseHandler):
def get(self):
try:
template = env.get_template("privacy.html")
rendered_template = template.render()
self.set_header("Cache-Control", "max-age=3600")
self.set_header("Content-Type", "text/html")
self.write(rendered_template)
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class GetRecordingStatusHandler(BaseHandler):
def get(self):
try:
self.set_header("Content-Type", "application/json")
self.write(json.dumps(recording_status_chache["data"], indent=4))
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
class AudioArchivesHandler(BaseHandler):
def get(self):
try:
template = env.get_template("archives.html")
rendered_template = template.render(
url_for=url_for_static,
)
self.set_header("Cache-Control", "max-age=3600")
self.set_header("Content-Type", "text/html")
self.write(rendered_template)
except Exception as e:
self.set_status(500)
self.write_error(500, stack_trace=f"{str(e)} {traceback.print_exc()}")
def url_for_static(filename):
static_recordings_path = os.getenv("STATIC_RECORDINGS_PATH", "/app/static/Recordings")
return f"{static_recordings_path}/{filename}"
class RecordingStatsHandler(BaseHandler):
def get(self, file_name):
matching_archive = None
for archive in audio_archive_cache["data"]:
if archive["filename"] == file_name:
matching_archive = archive
break
self.set_header("Content-Type", "application/json")
if matching_archive:
self.write(
json.dumps(
{
"visit_count": matching_archive["visit_count"] or 0,
"latest_visit": matching_archive["latest_visit"].strftime("%B %d %A %Y %I:%M %p") if matching_archive["latest_visit"] else "N/A",
}
)
)
else:
self.write(json.dumps({"visit_count": 0, "latest_visit": "N/A"}))
class LoadRecordingHandler(BaseHandler):
async def get(self, hash):
url = f"{os.getenv('FILEBROWSER_URL')}/api/public/dl/{hash}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
if resp.status != 200:
self.set_status(resp.status)
self.finish(f"Failed to load recording: {resp.reason}")
return
content = await resp.read()
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Content-Type", resp.headers.get("Content-Type", "audio/mp3"))
self.set_header("Content-Length", str(len(content)))
self.set_header("Accept-Ranges", "bytes")
self.set_header("content-Range", f"bytes 0-{len(content)}/{len(content)}") # For resuming downloads
self.set_header(
"Content-Disposition",