You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
2.8 KiB
Python
102 lines
2.8 KiB
Python
import os
|
|
import re
|
|
import sys
|
|
import socket
|
|
import secrets
|
|
import tempfile
|
|
import http.server
|
|
import socketserver
|
|
|
|
from threading import Thread
|
|
from urllib.request import urlopen
|
|
|
|
PORT = 4040
|
|
BEAM_SERVER = '192.168.0.192:4005'
|
|
|
|
def handler_for_dir(dir):
|
|
def myhandler(*args, **kwargs):
|
|
kwargs['directory'] = dir
|
|
return http.server.SimpleHTTPRequestHandler(*args, **kwargs)
|
|
|
|
return myhandler
|
|
|
|
def get_request(url):
|
|
resp = urlopen(url)
|
|
return (200 <= resp.status <= 299, "\n".join([d.decode() for d in resp.readlines()]))
|
|
|
|
# get ip address (sourced from https://stackoverflow.com/a/28950776/4141651)
|
|
def get_ip():
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
try:
|
|
# doesn't even have to be reachable
|
|
s.connect(('10.255.255.255', 1))
|
|
IP = s.getsockname()[0]
|
|
except Exception:
|
|
IP = '127.0.0.1'
|
|
finally:
|
|
s.close()
|
|
return IP
|
|
|
|
def local_session(target):
|
|
d = tempfile.TemporaryDirectory()
|
|
print("using tempdir " + d.name)
|
|
|
|
os.symlink(os.path.abspath(target), d.name + '/stream')
|
|
|
|
handler = handler_for_dir(d.name + '/')
|
|
token = None
|
|
|
|
try:
|
|
with http.server.HTTPServer(("0.0.0.0", PORT), handler) as httpd:
|
|
try:
|
|
print("serving at port", PORT)
|
|
t = Thread(target=httpd.serve_forever)
|
|
t.start()
|
|
print("calling beam target...")
|
|
host = get_ip()
|
|
resp = get_request(f'http://{BEAM_SERVER}/open/local?host={host}&port={PORT}')
|
|
if resp[0]:
|
|
token = resp[1].strip()
|
|
print(f"successfully started video - session {token}")
|
|
input("Just press enter when you are done...")
|
|
else:
|
|
print("Error statrtig video!")
|
|
finally:
|
|
print("shutting down server")
|
|
httpd.shutdown()
|
|
|
|
finally:
|
|
print("cleaning up")
|
|
if token:
|
|
get_request(f'http://{BEAM_SERVER}/stop/{token}')
|
|
d.cleanup()
|
|
|
|
def youtube_session(video):
|
|
id = re.match('^(https?:\/\/)?(www\.)?youtu(\.be\/|be\.com\/watch\?(.*&)?v=)([A-Za-z0-9]{5,20})', video)
|
|
if not id:
|
|
print(f"invalid match in {video}!")
|
|
return
|
|
id = id.group(5)
|
|
|
|
print(f"watching youtube video {id}")
|
|
|
|
resp = get_request(f'http://{BEAM_SERVER}/open/youtube/{id}')
|
|
|
|
if resp[0]:
|
|
token = resp[1].strip()
|
|
print(f"successfully started video - session {token}")
|
|
input("Just press enter when you are done...")
|
|
get_request(f'http://{BEAM_SERVER}/stop/{token}')
|
|
else:
|
|
print("Error statrtig video!")
|
|
|
|
|
|
target = sys.argv[1]
|
|
|
|
if re.match('^(https?:\/\/)?(www\.)?youtu(\.be\/|be\.com\/)', target):
|
|
youtube_session(target)
|
|
else:
|
|
local_session(target)
|
|
|
|
# symlink target to tempdir so we only expose a single file
|