Spaces:
Running
Running
File size: 6,191 Bytes
cd55e67 a0c14f1 2a30750 cc6c746 92f293d ed440ee cc6c746 a0c14f1 6509820 3c2a864 6509820 ddcc9ef 69be298 175c2da b7779db 1e62981 28bc63e 444d443 6be0cae 444d443 92f293d 80e1440 5eae221 80e1440 5eae221 c079e1b 5eae221 3a05da9 9dd9279 400820b 0d5968d 80e1440 a0c14f1 b94dcf8 2af4039 bf6c37d c079e1b bf6c37d 532ed57 dacc1bc d1f4a66 f42ef1d 532ed57 28bc63e 31c4438 f42ef1d 30aaad8 ed440ee 31c4438 1c6395a ea95f8e 31c4438 bc53648 18d21e2 3ff67ea b306f2e a0c14f1 7aa6c39 a4a02bf 6cecdc2 a4a02bf 91a216a 6cecdc2 a4a02bf 9714f25 7aa6c39 0df1994 7aa6c39 444d443 cb50560 444d443 44cedae 9714f25 a0c14f1 a38f152 80e1440 3a05da9 5c83afb a0c14f1 85130f8 a0c14f1 525173b 1c6395a 5db111d 1e62981 5db111d 6be0cae 5db111d 1952784 5db111d d075963 5db111d 1e62981 5db111d 9714f25 5c83afb a0c14f1 70760e8 a0c14f1 958d1c2 |
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 |
from flask import Flask, Response, render_template, send_file, stream_with_context, request, session, redirect, url_for
import requests
import random
import pickle as pkl
import pycountry
import datetime as dt
import pytz
from io import BytesIO
import logging
import os
import time
logging.basicConfig(level=logging.INFO)
app = Flask(__name__)
app.secret_key = 'green-flounder'
with open('video_urls.pkl', 'rb') as f:
live_urls = pkl.load(f)
live_urls = [i for i in live_urls if i!= 'http://2.40.36.158:8084/img/video.mjpeg']
with open('owner_dict.pkl', 'rb') as f:
owner_dict = pkl.load(f)
from urllib.parse import urlsplit, urlunsplit, quote, parse_qsl, urlencode
def encode_url(url):
scheme, netloc, path, query_string, fragment = urlsplit(url)
query_params = parse_qsl(query_string)
encoded_query_params = [(key, quote(value)) for key, value in query_params]
encoded_query_string = urlencode(encoded_query_params)
finished = urlunsplit((scheme, netloc, path, encoded_query_string, fragment))
print('ENCODED',finished)
return finished
from geolite2 import geolite2
def get_location(ip):
start_time = time.time()
reader = geolite2.reader()
location = reader.get(ip)
geolite2.close()
end_time = time.time()
elapsed_time = end_time - start_time
print(f"\nTime taken for get_location: {elapsed_time} seconds\n")
if location:
return {'country': location['country']['names']['en'] if 'country' in location else 'unknown country',
'city': location['city']['names']['en'] if 'city' in location else 'unknown city',
'region': location['subdivisions'][0]['names']['en'] if 'subdivisions' in location else 'unknown region',
'loc': str(location['location']['latitude']) + ',' + str(location['location']['longitude']) if 'location' in location else '0,0',
'timezone': location['location']['time_zone'] if 'location' in location and 'time_zone' in location['location'] else 'America/New_York'}
else:
return {'country': 'unknown country',
'city': 'unknown city',
'region': 'unknown region',
'loc': str(0) + ',' + str(0),
'timezone':'America/New_York'}
def latlon_to_pixel(loc):
latitude = float(loc.split(',')[0])
longitude = float(loc.split(',')[1])
y = ((90-latitude)/180)
x = ((longitude+180)/360)
return x*100, y*100
from urllib.parse import urlparse, parse_qs
@app.route('/proxy/<path:url>')
def proxy(url):
start_time = time.time()
full_url = url
query_string = request.query_string.decode("utf-8")
if query_string:
full_url += "?" + query_string
print("CHOSEN",full_url)
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.9',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Dnt': '1',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'
}
clean_url = full_url.replace('proxy/', '')
clean_url = encode_url(clean_url)
should_abort = lambda: 'abort' in session and session['abort']
def generate(should_abort):
for chunk in req.iter_content(chunk_size=1024):
if should_abort():
break
yield chunk
try:
start = time.time()
logging.info(f"Sending request to: {clean_url}")
req = requests.get(clean_url, headers=headers, stream=True, timeout=2)
return Response(generate(should_abort), content_type=req.headers['content-type'])
except Exception as e:
logging.error(f"Error in proxy: {str(e)}")
return Response("Error", status=500)
@app.route('/')
def index():
id = request.args.get('id')
if 'current_feed' in session and request.args.get('new', 'false') == 'false':
feed = session['current_feed']
url = live_urls[int(feed)]
else:
feed = random.randint(0, len(live_urls) - 1)
url = live_urls[int(feed)]
session['current_feed'] = feed
if id:
url = live_urls[int(id)]
feed = id
session['current_feed'] = id
print("GENERATED", url)
url = encode_url(url)
url = url.replace('640x480','1280x960')
id = feed
ip = ''.join(url.split('//')[-1]).split(':')[0]
print('IP:',ip)
info = get_location(ip)
country = info['country'].lower()
name = (info['city'] + ", " + info['region']).lower()
page_title = (info['city'] + ", " + info['region'] + ", " + country).lower()
timezone = pytz.timezone(info['timezone'])
time = dt.datetime.now(timezone)
time = time.strftime("%I:%M:%S %p")
loc = info['loc']
X, Y = latlon_to_pixel(info['loc'])
proxy_url = 'proxy/' + url
logging.info(f"Generated proxy URL: {proxy_url}")
loc_link = f"https://www.google.com/maps/search/{loc}"
ip_link = url
try:
owner = owner_dict[ip]
except:
owner = 'unknown'
return render_template('index.html',
name=name,
url=encode_url(proxy_url),
info=info,
country=country,
time=time,
timezone=timezone,
ip=ip,
ip_link=ip_link,
loc=loc,
loc_link=loc_link,
owner=owner,
X=X,
Y=Y,
id=id,
page_title=page_title)
@app.route('/abort_stream')
def abort_stream():
session['abort'] = True
return 'Aborted', 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port='7860')
|