-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
2937 lines (2724 loc) · 101 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
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
# Standard library imports
from copy import deepcopy, copy
import os
import time
import random
import logging
import subprocess
import sqlite3
from datetime import datetime, timedelta, timezone
from pathlib import Path
from string import ascii_letters, digits
from typing import Optional, Tuple, List
from urllib import parse
from urllib.parse import parse_qs
from json import load, dump, loads, dumps
from http.cookiejar import MozillaCookieJar
# Third-party library imports
import yagmail
import cronitor
import yt_dlp
import dns.resolver
import dns.reversename
import scrapetube
from requests import get as GET
from requests import get
from bs4 import BeautifulSoup
from flask import (
Flask,
request,
render_template,
redirect,
url_for,
send_file,
session,
jsonify,
send_from_directory
)
from flask_cors import CORS
from flask_login import LoginManager, UserMixin, login_user, login_required, current_user, logout_user
from flask_sitemap import Sitemap
from discord_webhook import DiscordWebhook, DiscordEmbed
from chat_downloader.sites import YouTubeChatDownloader
from chat_downloader import ChatDownloader
# Local imports
from helper.util import *
from helper.Clip import Clip, time_since
from helper.UserSettings import UserSettings
# we are in /var/www/streamsnip
import os
try:
os.chdir("/var/www/streamsnip")
except FileNotFoundError:
print("Running locally as we couldn't find the folder")
local = True
# we are working locally
pass
else:
local = False
if not local:
logging.basicConfig(
filename="./record.log",
level=logging.ERROR,
format=f"%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s",
)
try:
config = load(open("config.json", "r"))
except FileNotFoundError:
print("Config file not found")
exit(1)
try:
cronitor.api_key = config["cronitor_api_key"]
except FileNotFoundError:
cronitor.api_key = None
if not local:
monitor = cronitor.Monitor.put(key="Streamsnip-Clips-Performance", type="job")
else:
monitor = None
app = Flask(__name__)
app.secret_key = os.environ.get("WSGISecretKey", "supersecretkey") # if we are running on apache we have a WSGISecretKey, its not really secret.
CORS(app)
ext = Sitemap(app=app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
global download_lock
download_lock = True
global DEFAULT_SETTINGS
DEFAULT_SETTINGS = UserSettings()
conn = sqlite3.connect("queries.db", check_same_thread=False)
# cur = db.cursor() # this is not thread safe. we will create a new cursor for each thread
owner_icon = "👑"
mod_icon = "🔧"
regular_icon = "🧑🌾"
subscriber_icon = "⭐"
allowed_ip = [
"127.0.0.1",
"10.20.0.2"
] # store the nightbot ips here. or your own ip for testing purpose
# add local ip just to make sure we go through if we are testing locally
allowed_ip.append(get("https://api.ipify.org/").text)
show_fake_error = False # for blacklisted channel show fake error message or not
requested_myself = (
False # on startup we request ourself so that apache build the cache.
)
base_domain = (
"https://streamsnip.com" # just for the sake of it. store the base domain here
)
chat_id_video = {} # store chat_id: vid. to optimize clip command
downloader_base_url = "https://azure-internal-verse.glitch.me"
project_name = "StreamSnip"
project_logo = base_domain + "/static/logo.png"
project_repo_link = "https://github.com/SurajBhari/streamsnip"
project_logo_discord = "https://raw.githubusercontent.com/SurajBhari/streamsnip/main/static/256_discord_ss.png" # link to logo that is used in discord
sub_based_sort = True # sort the channels on home page based on sub count
jar = None
if "cookies.txt" in os.listdir("./helper"):
cookies = "./helper/cookies.txt"
jar = MozillaCookieJar(Path(cookies))
else:
cookies = None
if "youtubeemoji.json" in os.listdir("./helper"):
with open("./helper/youtubeemoji.json", "r", encoding="utf-8") as f:
emoji_lookup_table = load(f)
else:
emoji_lookup_table = {}
def is_it_expired(t:int): # we add some randomness so that not all of the cache get invalidated and added back at same time.
if local:
return False # we don't need to expire the cache we have for testing purposes
three_days_ago = int(time.time()) - 3 * 24 * 60 * 60
last_time = three_days_ago + random.randint(0, 48) * 60 * 60
if t < last_time:
return True
return False
def get_creds():
try:
with open("config.json", "r", encoding="utf-8") as f:
jcreds = load(f)
creds = jcreds['creds']
creds['password'] = jcreds['password']
creds['admin'] = jcreds['password'] # for admin password relation. make it easy to work with
except (FileNotFoundError, KeyError):
creds = {}
return creds
def write_creds(new_creds:dict):
if not new_creds:
return
# load the config as whole and then update the creds
with open("config.json", "r", encoding="utf-8") as f:
config = load(f)
config['creds'] = new_creds
with open("config.json", "w", encoding="utf-8") as f:
dump(config, f, indent=4)
return True
if not project_logo_discord:
project_logo_discord = project_logo
with conn:
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS QUERIES(channel_id VARCHAR(40), message_id VARCHAR(40), clip_desc VARCHAR(40), time int, time_in_seconds int, user_id VARCHAR(40), user_name VARCHAR(40), stream_link VARCHAR(40), webhook VARCHAR(40), delay int, userlevel VARCHAR(40), ss_id VARCHAR(40), ss_link VARCHAR(40), private VARCHAR(40), message_level int)"
)
conn.commit()
cur.execute("PRAGMA table_info(QUERIES)")
data = cur.fetchall()
colums = [xp[1] for xp in data]
if "webhook" not in colums:
cur.execute("ALTER TABLE QUERIES ADD COLUMN webhook VARCHAR(40)")
conn.commit()
print("Added webhook column to QUERIES table")
if "delay" not in colums:
cur.execute("ALTER TABLE QUERIES ADD COLUMN delay INT")
conn.commit()
print("Added delay column to QUERIES table")
if "userlevel" not in colums:
cur.execute("ALTER TABLE QUERIES ADD COLUMN userlevel VARCHAR(40)")
conn.commit()
print("Added userlevel column to QUERIES table")
if "ss_id" not in colums:
cur.execute("ALTER TABLE QUERIES ADD COLUMN ss_id VARCHAR(40)")
conn.commit()
print("Added ss_id column to QUERIES table")
if "ss_link" not in colums:
cur.execute("ALTER TABLE QUERIES ADD COLUMN ss_link VARCHAR(40)")
conn.commit()
print("Added ss_link column to QUERIES table")
if "private" not in colums:
cur.execute("ALTER TABLE QUERIES ADD COLUMN private VARCHAR(40)")
conn.commit()
print("Added private column to QUERIES table")
if "message_level" not in colums:
cur.execute(
"ALTER TABLE QUERIES ADD COLUMN message_level INT"
) # we store this for the sole purpose of rebuilding the message on !edit
conn.commit()
print("Added message_level column to QUERIES table")
with conn:
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS SETTINGS (
channel_id VARCHAR(40) UNIQUE,
showlink VARCHAR(40) DEFAULT 'True',
screenshot VARCHAR(40) DEFAULT 'False',
delay INT DEFAULT 0,
forcedesc VARCHAR(40) DEFAULT 'False',
silent INT DEFAULT 2,
private VARCHAR(40) DEFAULT 'False',
webhook VARCHAR(128) DEFAULT 'None',
messagelevel INT DEFAULT 0,
takedelays INT DEFAULT 'False'
)""")
conn.commit()
class User(UserMixin):
def __init__(self, user_id, username, password, image=None):
self.id = user_id
if self.id == "admin":
username = "Admin"
image = "https://images.freeimages.com/fic/images/icons/2526/bloggers/256/admin.png?fmt=webp&h=350"
self.username = username
self.name = username
self.password = password
self.image = image
self.admin = True if username.lower() == 'admin' else False
def get_id(self):
return self.id
@staticmethod
def get(user_id):
# load the config file
creds = get_creds()
if not creds:
print("No creds found")
return None
if user_id not in creds:
print(f"User {user_id} not found in creds")
return None
username, image = get_channel_name_image(user_id)
return User(user_id, username, creds[user_id], image)
def get_channel_settings(user_id) -> UserSettings:
with conn:
cur = conn.cursor()
cur.execute("SELECT * FROM SETTINGS WHERE channel_id=?", (user_id,))
data = cur.fetchone()
if not data:
x = UserSettings()
x.channel_id = user_id
add_default_settings(x.channel_id)
return x
return UserSettings(list(data))
# if there is no folder named clips then make one
if not os.path.exists("clips"):
os.makedirs("clips")
print("Created clips folder")
try:
creds = config['creds']
except KeyError:
creds = {}
config['creds'] = creds
def is_blacklisted(channel_id):
try:
with open("blacklisted.json", "r", encoding="utf-8") as f:
data = load(f)
except FileNotFoundError:
data = []
return channel_id in data
def get_clip(clip_id, channel=None) -> Optional[Clip]:
try:
with conn:
cur = conn.cursor()
if channel:
cur.execute(
"SELECT * FROM QUERIES WHERE channel_id=? AND message_id LIKE ? AND time_in_seconds >= ? AND time_in_seconds < ?",
(
channel,
f"%{clip_id[:3]}",
int(clip_id[3:]) - 1,
int(clip_id[3:]) + 1,
),
)
else:
cur.execute(
"SELECT * FROM QUERIES WHERE message_id LIKE ? AND time_in_seconds >= ? AND time_in_seconds < ?",
(f"%{clip_id[:3]}", int(clip_id[3:]) - 1, int(clip_id[3:]) + 1),
)
data = cur.fetchall()
except Exception as e:
data = None
if not data:
return None
x = Clip(data[0])
return x
def get_video_clips(video_id) -> List[Optional[Clip]]:
with conn:
cur = conn.cursor()
cur.execute(
"SELECT * FROM QUERIES WHERE stream_link like ?", (f"%{video_id}%",)
)
data = cur.fetchall()
if not data:
return []
l = []
for y in data:
x = Clip(y)
l.append(x)
return l
def get_channel_clips(channel_id=None) -> List[Clip]:
with conn:
cur = conn.cursor()
if channel_id:
cur.execute(f"select * from QUERIES where channel_id=?", (channel_id,))
else:
cur.execute(f"select * from QUERIES ORDER BY time ASC")
data = cur.fetchall()
l = []
for y in data:
x = Clip(y)
l.append(x)
l.reverse()
return l
def create_simplified(clips: list) -> str:
known_vid_id = []
string = ""
for clip in clips:
if clip["stream_id"] not in known_vid_id:
string += f"https://youtu.be/{clip['stream_id']}\n"
string += f"{clip['author']['name']} -> {clip['message']} -> {clip['hms']}\n"
string += f"Link: {clip['link']}\n\n\n"
known_vid_id.append(clip["stream_id"])
return string
def get_channel_name_image(channel_id: str, force_refresh=False) -> Tuple[str, str]:
if channel_id in channel_info and not force_refresh: # if its a force refresh we don't want to use the cache
if "last_updated" not in channel_info[channel_id]:
channel_info[channel_id]["last_updated"] = 0 # forcing to outdate the value so that it gets updated
if "sub_count" not in channel_info[channel_id]:
channel_info[channel_id]["last_updated"] = 0 # forcing to outdate the value so that it gets updated
if is_it_expired(channel_info[channel_id]["last_updated"]):
return get_channel_name_image(channel_id, force_refresh=True)
try:
return channel_info[channel_id]["name"], channel_info[channel_id]["image"]
except Exception as e:
logging.log(logging.ERROR, e)
channel_link = f"https://youtube.com/channel/{channel_id}"
response = get(channel_link)
if response.status_code != 200:
# don't store anything. just for this instance return the default values. can be youtube side issue too
return "<deleted channel>", "https://yt3.googleusercontent.com/a/default-user=s100-c-k-c0x00ffffff-no-rj"
html_data = response.text
# with open("youtube.html", "w", encoding="utf-8") as f:
# f.write(html_data)
yt_initial_data = loads(
get_json_from_html(html_data, "var ytInitialData = ", 0, "};") + "}"
)
# put this in a local file for test purposes
# with open("yt_initial_data.json", "w", encoding="utf-8") as f:
# dump(yt_initial_data, f, indent=4)
soup = BeautifulSoup(html_data, "html.parser")
try:
channel_image = soup.find("meta", property="og:image")["content"]
channel_name = soup.find("meta", property="og:title")["content"]
try:
sub_count = yt_initial_data['header']['pageHeaderRenderer']['content']['pageHeaderViewModel']['metadata']['contentMetadataViewModel']['metadataRows'][1]['metadataParts'][0]['text']['content']
sub_count = convert_sub_count(sub_count)
except:
sub_count = 0
try:
channel_username = yt_initial_data['metadata']['channelMetadataRenderer']['vanityChannelUrl'].split("/")[-1]
except KeyError:
return channel_name, channel_image # stop caring abot channel username and putting it to cache
except TypeError: # in case the channel is deleted or not found
channel_image = "https://yt3.googleusercontent.com/a/default-user=s100-c-k-c0x00ffffff-no-rj"
channel_name = "<deleted channel>"
channel_username = "@deleted"
sub_count = 0
last_updated = int(time.time())
channel_info[channel_id] = {
"name": channel_name,
"image": channel_image,
"username": channel_username,
"last_updated": last_updated,
"sub_count": sub_count
}
# write channel_info to channel_cache.json
write_channel_cache(channel_info)
return channel_name, channel_image
def convert_sub_count(sub_count:str) -> int:
sub_count = sub_count.split(" ")[0]
sub_count = sub_count.upper()
if "K" in sub_count:
sub_count = sub_count.replace("K", "")
sub_count = float(sub_count) * 1000
elif "M" in sub_count:
sub_count = sub_count.replace("M", "")
sub_count = float(sub_count) * 1000000
elif "B" in sub_count: # lmao like this is ever gonna happen xd
sub_count = sub_count.replace("B", "")
sub_count = float(sub_count) * 1000000000
else:
sub_count = int(sub_count)
return int(sub_count)
def take_screenshot(video_url: str, seconds: int) -> str:
# Get the video URL using yt-dlp
params = {
'forceurl': True,
'format': 'bestvideo',
'noprogress': True,
'quiet': True,
'simulate': True,
}
if cookies:
params['cookiefile'] = cookies
with yt_dlp.YoutubeDL(params) as ydl:
video_info = ydl.extract_info(video_url, download=False)
# Remove leading/trailing whitespace and newline characters from the video URL
video_url = video_info['url']
file_name = "ss.jpg"
r = GET(video_url, cookies=jar) # this uses Jar because it can't parse a txt file with cookies
if r.status_code != 200:
return None
index = 'index.m3u8'
with open(index, "wb") as f:
f.write(r.content)
# Think Think
# FFmpeg command
ffmpeg_command = [
"ffmpeg",
"-protocol_whitelist",
"file,http,https,tcp,tls,crypto", # Protocol whitelist
"-y", # say yes to prompts
"-ss",
str(seconds), # Start time
"-i",
index, # Input video URL
"-vframes",
"1", # Number of frames to extract (1)
"-q:v",
"2", # Video quality (2)
"-hide_banner", # Hide banner
"-loglevel",
"error", # Hide logs
file_name, # Output image file
]
try:
subprocess.run(ffmpeg_command, check=True)
except subprocess.CalledProcessError as e:
print("Error:", e)
exit(1)
return file_name
def get_clip_with_desc(clip_desc: str, channel_id: str) -> Optional[Clip]:
clips = get_channel_clips(channel_id)
for clip in clips:
if clip_desc.lower() in clip.desc.lower():
return clip
return None
def download_and_store(clip_id, format:str = None) -> str:
with conn:
cur = conn.cursor()
data = cur.execute(
"SELECT * FROM QUERIES WHERE message_id LIKE ? AND time_in_seconds >= ? AND time_in_seconds < ?",
(f"%{clip_id[:3]}", int(clip_id[3:]) - 1, int(clip_id[3:]) + 1),
)
data = cur.fetchall()
if not data:
return None
clip = Clip(data[0])
video_url = clip.stream_link
timestamp = clip.time_in_seconds
output_filename = f"./clips/{clip_id}"
# if there is a file that start with that clip in current directory then don't download it
for file in os.listdir("./clips"):
if format:
if file.startswith(clip_id) and file.endswith(format):
return file
else:
if file.startswith(clip_id):
return file
# real thing happened at 50. but we stored timestamp with delay. take back that delay
delay = clip.delay
timestamp += -1 * delay
if not delay:
delay = -60
l = [timestamp, timestamp + delay]
start_time = min(l)
end_time = max(l)
params = {
"cookiefile": cookies,
"download_ranges": yt_dlp.utils.download_range_func(
[], [[start_time, end_time]]
),
"match_filter": yt_dlp.utils.match_filter_func(
"!is_live & live_status!=is_upcoming & availability=public"
),
"no_warnings": True,
"noprogress": True,
"outtmpl": {"default": output_filename},
"overwrites": True,
"silent": True,
}
if format:
params["final_ext"] = format
params['postprocessors'] = [{'key': 'FFmpegVideoConvertor', 'preferedformat': 'mp4'}]
with yt_dlp.YoutubeDL(params) as ydl:
try:
ydl.download([video_url])
except yt_dlp.utils.DownloadError as e:
print(e)
return # this video is still live. we can't download it
files = [
os.path.join("clips", x) for x in os.listdir("./clips") if x.startswith(clip_id)
]
if files:
return files[0]
def mini_stats():
today = datetime.strptime(
datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d"
).timestamp()
with conn:
cur = conn.cursor()
todays_clips = cur.execute("SELECT * FROM QUERIES WHERE time >= ? AND private is not '1'", (today,))
todays_clips = todays_clips.fetchall()
today_count = len(todays_clips)
last_clip = None
if today_count:
last_clip = Clip(todays_clips[-1]).json()
return dict(today_count=today_count, last_clip=last_clip)
@app.before_request
def before_request():
"""
# if its a http request. redirect the same to https
if not local:
if not request.is_secure:
return redirect(".", code=302)
"""
# if request is for /clip or /delete or /edit then check if its from real
if "/clip" in request.path or "/delete" in request.path or "/edit" in request.path:
if "/extension/" in request.path: # make an exception for all the /extension routes
return
ip = request.remote_addr
if ip in allowed_ip:
# print(f"Request from {ip} is allowed, known ip")
return
addrs = dns.reversename.from_address(ip)
try:
if not str(dns.resolver.resolve(addrs, "PTR")[0]).endswith(
".nightbot.net."
):
raise ValueError("Not a nightbot request")
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, ValueError, dns.resolver.LifetimeTimeout, dns.resolver.NoNameservers):
return f"You are not Nightbot. are you ?, your ip {ip}"
else:
# print(f"Request from {ip} is allowed")
allowed_ip.append(ip)
else:
pass
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@app.route("/cache")
def cache():
return dumps(channel_info, indent=4)
@app.route("/mini_stats")
def mini_stats_r():
if request.args.get("home") == "true":
ms = mini_stats()
ms['data'] = generate_home_data()
return dict(ms)
return mini_stats()
# this function exists just because google chrome assumes that the favicon is at /favicon.ico
@app.route("/favicon.ico")
def favicon():
return send_file("static/logo.svg")
@app.route("/robots.txt")
def robots():
return send_file("static/robots.txt")
def generate_home_data():
with conn:
cur = conn.cursor()
cur.execute(f"SELECT *, COUNT(*) AS channel_count, MIN(time) AS first_clip_time FROM QUERIES WHERE private is not '1' GROUP BY channel_id ORDER BY MAX(time) DESC;")
data = cur.fetchall()
returning = []
for clip in data:
ch = {}
channel_name, channel_image = get_channel_name_image(clip[0])
ch["image"] = channel_image
ch["name"] = channel_name
try:
ch['sub_count'] = channel_info[clip[0]]['sub_count']
except KeyError:
ch['sub_count'] = 0
ch["id"] = clip[0]
ch["image"] = channel_image.replace(
"s900-c-k-c0x00ffffff-no-rj", "s300-c-k-c0x00ffffff-no-rj"
)
ch["last_clip"] = Clip(clip).json()
if request.is_secure:
htt = "https://"
else:
htt = "http://"
ch["link"] = f"{htt}{request.host}{url_for('exports', channel_id=get_channel_at(clip[0]))}"
ch['clip_count'] = clip[-2]
ch['first_clip_time'] = clip[-1]
ch['first_clip_timesince'] = time_since(datetime.fromtimestamp(clip[-1], tz=timezone.utc))
ch['deleted'] = True if "deleted channel" in channel_name else False
if ch['deleted']:
ch['link'] = f"{htt}{request.host}{url_for('exports', channel_id=get_channel_id_any(clip[0]))}" # we can't get channel @ as its a deleted channel
#ch["last_clip"] = get_channel_clips(ch_id[0])[0].json()
returning.append(ch)
return returning
@app.route("/channels")
def channels():
returning = generate_home_data()
return render_template("channels.html", data=returning)
@app.route("/")
def slash():
returning = generate_home_data()
return render_template("home.html", data=returning, sub_based_sort=not current_user.is_authenticated)
@app.route("/")
@app.route("/data")
def data():
return "Disabled"
clips = get_channel_clips()
clips = [x.json() for x in clips]
return clips
@app.route("/session", methods=["GET"])
def session_data():
if session:
return dumps(session, indent=4)
else:
return "No session data"
@app.route("/user")
@login_required
def _user():
return dumps(current_user.__dict__, indent=4)
@app.route("/login", methods=["POST", "GET"])
def login():
if request.method == "POST":
remember = request.form.get("remember") == "remember"
print(remember)
# set cookies to this password
creds = get_creds()
for cred in creds:
if creds[cred] == request.form["password"]:
if cred == "password":
session['id'] = "admin"
else:
session["id"] = cred
session['logged_in'] = True
login_user(User.get(session["id"]), remember=remember)
next = request.args.get('next')
return redirect(next or url_for('slash'))
return render_template("login.html", msg="INVALID PASSWORD")
next = request.args.get('next', "")
if next:
next = f"?next={next}"
return render_template("login.html", msg="Password is the webhook URL that you are using for your channel.", next=next)
@app.route("/logout", methods=["POST", "GET"])
@login_required
def logout():
session.clear()
logout_user()
return redirect(url_for("slash"))
@app.route("/webedit", methods=["POST"])
@login_required
def webedit():
try:
new_message = request.json["message"]
clip_id = request.json["clip_id"]
except KeyError:
return "Invalid request", 400
clip = get_clip(clip_id=clip_id)
if not clip:
return "Clip not found", 404
if not current_user.admin:
if clip.channel != current_user.id:
return "You can't do this. You are not the owner of this channel"
clip.edit(new_message, conn)
return clip.desc, 200
@app.route("/webdelete", methods=["POST"])
@login_required
def webdelete():
try:
clip_id = request.json["clip_id"]
except KeyError:
return "Invalid request", 400
clip = get_clip(clip_id=clip_id)
if not clip:
return "Clip not found", 404
if not current_user.admin:
if clip.channel != current_user.id:
return "You can't do this. You are not the owner of this channel"
clip.delete(conn)
return "Deleted", 200
def get_video_id(video_link):
x = parse.urlparse(video_link)
to_return = ""
if x.path == "/watch":
to_return = x.query.replace("v=", "")
if "/live/" in x.path:
to_return = x.path.replace("/live/", "")
if "youtu.be" in x.netloc:
to_return = x.path.replace("/", "")
return to_return.split("&")[0]
@app.route("/ip")
def get_ip():
return request.remote_addr
@app.route("/settings/default", methods=["POST"])
@login_required
def default_settings():
with conn:
cur = conn.cursor()
cur.execute("DELETE FROM SETTINGS WHERE channel_id=?", (current_user.id,))
conn.commit()
add_default_settings(current_user.id)
return "OK", 200
@app.route("/settings" , methods=["POST", "GET"])
@login_required
def settings():
settings = get_channel_settings(current_user.id)
if request.method == "POST":
settings.show_link = request.json.get("show_link")
settings.screenshot = request.json.get("screenshot")
settings.delay = request.json.get("delay")
settings.force_desc = request.json.get("force_desc")
settings.silent = request.json.get("silent")
settings.private = request.json.get("private")
settings.webhook = request.json.get("webhook")
settings.message_level = request.json.get("message_level")
settings.take_delays = request.json.get("take_delays")
if not settings.write(conn):
return "Failed to write settings", 500
return "OK", 200
return render_template("settings.html", session=session, settings=settings)
# this is for nightbot to give back export link
@app.route("/export")
def export():
try:
channel = parse_qs(request.headers["Nightbot-Channel"])
except KeyError:
return "Not able to auth"
channel_id = channel.get("providerId")[0]
if request.is_secure:
htt = "https://"
else:
htt = "http://"
return f"You can see all the clips at {htt}{request.host}{url_for('exports', channel_id=get_channel_at(channel_id))}"
# this is for ALL CLIPS
@app.route("/e")
@app.route("/exports")
@app.route("/e/")
@app.route("/exports/")
def clips():
data = get_channel_clips()
data = [x.json() for x in data if not x.private]
for clip in data:
"""
if clip['discord']['webhook']:
if clip['channel'] in prefix_webhook:
clip['discord_url'] = f"{prefix_webhook[clip['channel']]}/{clip['discord']['webhook']}"
else:
webhook_url = creds.get(clip['channel'])
if not webhook_url:
continue
response = get(webhook_url)
if response.status_code != 200:
prefix_webhook[clip['channel']] = None
continue
j = response.json()
prefix_webhook[clip['channel']] = f"https://discord.com/channels/{j['guild_id']}/{j['channel_id']}"
clip['discord_url'] = f"{prefix_webhook[clip['channel']]}/{clip['discord']['webhook']}"""
clip['discord_url'] = "#a" # we don't want to do it for all clips. cuz its slowwwww
return render_template(
"export.html",
data=data,
clips_string=create_simplified(data),
channel_name="All channels",
channel_image="https://streamsnip.com/static/logo.png",
owner_icon=owner_icon,
mod_icon=mod_icon,
regular_icon=regular_icon,
subscriber_icon=subscriber_icon,
channel_id="all",
emoji_lookup_table=emoji_lookup_table
)
def get_channel_id_any(hint): # returns the UC id of the channel
if hint.lower().startswith("uc"):
return hint # already a channel id
if hint.startswith("@"):
available = [x for x in channel_info if hint.lower() in channel_info[x].get("username").lower()]
if available:
return available[0]
available = [x for x in channel_info if hint.lower() == channel_info[x].get("name").lower()] # we are first trying to find exact match.
if available:
return available[0]
available = [x for x in channel_info if hint.lower() in channel_info[x].get("name").lower()]
if available:
return available[0]
return None
def get_channel_at(channel_id): # returns the @username of the channel
"""
channel_info = {
"UCnSgtnvG74e9nxI9SibI-LA":{
"name":"Pakshi",
"image":"https://yt3.googleusercontent.com/Av-rtdhg7TzN6LWwhaMbilRgMz_cQmecp3NwgU9m_NtpzEt0VQ1KvJqYfMs-LSCeR9bIRkh9Pw=s900-c-k-c0x00ffffff-no-rj",
"username":"@Pakshi_Udd",
"last_updated":1731360906,
"sub_count":836
}
}
"""
if channel_id.startswith("@"):
return channel_id
get_channel_name_image(channel_id) # this will just come back if there is already a channel_id.
channel = channel_info.get(channel_id)
if not channel:
return channel_id
return channel["username"]
# this is for specific channel
@app.route("/exports/<channel_id>")
@app.route("/e/<channel_id>")
def exports(channel_id=None):
channel_id = get_channel_id_any(channel_id)
if not channel_id:
return redirect(url_for("slash")) # not found
try:
channel_name, channel_image = get_channel_name_image(channel_id)
except Exception as e:
print(e)
return redirect(url_for("slash"))
data = get_channel_clips(channel_id)
data = [x.json() for x in data if not x.private]
for clip in data:
if clip['discord']['webhook']:
if clip['channel'] in prefix_webhook and prefix_webhook.get(clip['channel']) is not None:
clip['discord_url'] = f"{prefix_webhook[clip['channel']]}/{clip['discord']['webhook']}"
else:
webhook_url = creds.get(clip['channel'])
if not webhook_url:
continue
response = get(webhook_url)
if response.status_code != 200:
prefix_webhook[clip['channel']] = None
continue
j = response.json()
prefix_webhook[clip['channel']] = f"https://discord.com/channels/{j['guild_id']}/{j['channel_id']}"
clip['discord_url'] = f"{prefix_webhook[clip['channel']]}/{clip['discord']['webhook']}"
else:
clip['discord_url'] = "#"
return render_template(
"export.html",
data=data,
clips_string=create_simplified(data),
channel_name=channel_name,
channel_image=channel_image,
owner_icon=owner_icon,
mod_icon=mod_icon,
regular_icon=regular_icon,
subscriber_icon=subscriber_icon,
channel_id=get_channel_at(channel_id),
emoji_lookup_table=emoji_lookup_table
)
@app.route("/channelstats")
@app.route("/channelstats/")
@app.route("/channelstats/<channel_id>")
@app.route("/channelstats/<channel_id>/")
@app.route("/cs")
@app.route("/cs/")
@app.route("/cs/<channel_id>")
@app.route("/cs/<channel_id>/")
def channel_stats(channel_id=None):
if not channel_id:
return redirect(url_for("slash"))
if channel_id == "all":
return redirect(url_for("stats"))
channel_id = get_channel_id_any(channel_id)
if not channel_id:
return redirect(url_for("slash"))
with conn:
cur = conn.cursor()
cur.execute(
"SELECT * FROM QUERIES WHERE channel_id=? AND private is not '1'",
(channel_id,),
)
data = cur.fetchall()
if not data:
return redirect(url_for("slash"))
clips = []
for x in data:
clips.append(Clip(x))
clip_count = len(clips)
user_count = len(set([clip.user_id for clip in clips]))
# "Name": no of clips
user_clips = {}
top_clippers = {}
notes = {}
for clip in clips:
if clip.user_id not in user_clips:
user_clips[clip.user_id] = 0
user_clips[clip.user_id] += 1