erfyhersr commited on
Commit
aafa08b
·
verified ·
1 Parent(s): e0e8ea0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -110
app.py CHANGED
@@ -1,112 +1,117 @@
1
- import os
2
- import uuid
3
- import threading
4
- from flask import Flask, send_from_directory, render_template_string
5
  import streamlit as st
6
- from pyngrok import ngrok
7
-
8
- # Hardcode your ngrok token here
9
- ngrok.set_auth_token("2t7Jj4yyE3WswdAoz23Rkki03l0_53iu3por9LUB5uFPWYRFy")
10
-
11
- # Directory to store videos
12
- VIDEO_DIR = "videos"
13
- if not os.path.exists(VIDEO_DIR):
14
- os.makedirs(VIDEO_DIR)
15
-
16
- # Create a Flask app to serve videos and an embed page
17
- app = Flask(__name__)
18
-
19
- @app.route('/video/<video_id>')
20
- def serve_video(video_id):
21
- """Serves the video file based on the unique video_id."""
22
- for filename in os.listdir(VIDEO_DIR):
23
- if filename.startswith(video_id):
24
- return send_from_directory(VIDEO_DIR, filename)
25
- return "Video not found", 404
26
-
27
- @app.route('/embed/<video_id>')
28
- def embed_video(video_id):
29
- """Returns a custom HTML page with a video player streaming the video."""
30
- video_file = None
31
- for filename in os.listdir(VIDEO_DIR):
32
- if filename.startswith(video_id):
33
- video_file = filename
34
- break
35
- if not video_file:
36
- return "Video not found", 404
37
-
38
- # The video source URL points to the /video/<video_id> route.
39
- video_url = f"/video/{video_id}"
40
- html = f"""
41
- <!DOCTYPE html>
42
- <html>
43
- <head>
44
- <title>Custom Video Player</title>
45
- <style>
46
- body {{
47
- margin: 0;
48
- background-color: #000;
49
- display: flex;
50
- align-items: center;
51
- justify-content: center;
52
- height: 100vh;
53
- }}
54
- video {{
55
- width: 80%;
56
- max-width: 800px;
57
- height: auto;
58
- outline: none;
59
- }}
60
- </style>
61
- </head>
62
- <body>
63
- <video controls autoplay>
64
- <source src="{video_url}" type="video/mp4">
65
- Your browser does not support the video tag.
66
- </video>
67
- </body>
68
- </html>
69
  """
70
- return render_template_string(html)
71
-
72
- def run_flask():
73
- # Bind to 0.0.0.0 to allow external connections and run on port 8000
74
- app.run(host="0.0.0.0", port=8000)
75
-
76
- # Start the Flask server in a background thread (only once).
77
- if "FLASK_STARTED" not in st.session_state:
78
- st.session_state.FLASK_STARTED = True
79
- threading.Thread(target=run_flask, daemon=True).start()
80
-
81
- # Setup ngrok to expose port 8000 publicly (only once).
82
- if "NGROK_URL" not in st.session_state:
83
- public_url = ngrok.connect(8000, bind_tls=True)
84
- st.session_state.NGROK_URL = public_url.public_url
85
-
86
- st.title("Cloud Video Hosting and Streaming")
87
-
88
- uploaded_file = st.file_uploader("Upload a video", type=["mp4", "mov", "avi", "mkv"])
89
- if uploaded_file is not None:
90
- # Save the uploaded video using a unique id
91
- video_id = str(uuid.uuid4())
92
- ext = uploaded_file.name.split('.')[-1]
93
- filename = f"{video_id}.{ext}"
94
- filepath = os.path.join(VIDEO_DIR, filename)
95
- with open(filepath, "wb") as f:
96
- f.write(uploaded_file.getbuffer())
97
- st.success("Video uploaded successfully!")
98
-
99
- # Generate a public embed link using the ngrok public URL
100
- public_url = st.session_state.NGROK_URL
101
- embed_link = f"{public_url}/embed/{video_id}"
102
- st.write("Your embed link:")
103
- st.code(embed_link)
104
- st.markdown(f"[Open Video]({embed_link})")
105
-
106
- # Optional: List available videos with their public embed links
107
- st.subheader("Available Videos")
108
- for fname in os.listdir(VIDEO_DIR):
109
- vid_id = fname.split('.')[0]
110
- public_url = st.session_state.NGROK_URL
111
- embed_link = f"{public_url}/embed/{vid_id}"
112
- st.markdown(f"- [Video {vid_id}]({embed_link})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import ftplib
3
+ import libtorrent as lt
4
+ import time
5
+ import os
6
+
7
+ def ftp_upload_file(ftp, local_path, remote_path):
8
+ """
9
+ Upload a file to the FTP server showing a progress bar.
10
+ """
11
+ file_size = os.path.getsize(local_path)
12
+ uploaded_bytes = 0
13
+ progress_bar = st.progress(0)
14
+
15
+ # Callback for storbinary that is called after each block is sent.
16
+ def handle_block(block):
17
+ nonlocal uploaded_bytes
18
+ uploaded_bytes += len(block)
19
+ progress = int((uploaded_bytes / file_size) * 100)
20
+ progress_bar.progress(progress)
21
+
22
+ with open(local_path, 'rb') as f:
23
+ ftp.storbinary(f"STOR {remote_path}", f, blocksize=1024, callback=handle_block)
24
+
25
+ def download_torrent(magnet_link, download_folder):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  """
27
+ Download a torrent from a magnet link using libtorrent.
28
+ Shows a progress bar and status updates.
29
+ """
30
+ st.write("Starting torrent session...")
31
+ ses = lt.session()
32
+ ses.listen_on(6881, 6891)
33
+ params = {
34
+ 'save_path': download_folder,
35
+ 'storage_mode': lt.storage_mode_t(2),
36
+ }
37
+
38
+ # Add the magnet link
39
+ handle = lt.add_magnet_uri(ses, magnet_link, params)
40
+ st.write("Fetching metadata...")
41
+
42
+ # Wait until metadata is received.
43
+ while not handle.has_metadata():
44
+ st.write("Waiting for metadata...")
45
+ time.sleep(1)
46
+
47
+ st.write("Metadata received. Starting download...")
48
+ progress_bar = st.progress(0)
49
+ status_text = st.empty()
50
+
51
+ # Loop until the torrent is complete (i.e. seeding)
52
+ while True:
53
+ s = handle.status()
54
+ progress = s.progress * 100
55
+ progress_bar.progress(int(progress))
56
+ status_text.text(
57
+ f"State: {s.state}, Progress: {progress:.2f}% | "
58
+ f"Down: {s.download_rate/1000:.2f} kB/s | "
59
+ f"Up: {s.upload_rate/1000:.2f} kB/s | "
60
+ f"Peers: {s.num_peers}"
61
+ )
62
+ if s.is_seeding:
63
+ break
64
+ time.sleep(1)
65
+ st.success("Torrent download complete!")
66
+ return download_folder
67
+
68
+ def main():
69
+ st.title("Magnet Link to FTP Downloader")
70
+
71
+ st.header("FTP Connection Details")
72
+ ftp_host = st.text_input("FTP Host", "ftp.example.com")
73
+ ftp_port = st.number_input("FTP Port", value=21, step=1)
74
+ ftp_username = st.text_input("FTP Username")
75
+ ftp_password = st.text_input("FTP Password", type="password")
76
+
77
+ st.header("Torrent Details")
78
+ magnet_link = st.text_area("Magnet Link", placeholder="magnet:?xt=urn:btih:...")
79
+ download_folder = st.text_input("Download Folder", "./downloads")
80
+
81
+ if st.button("Start Download & Upload"):
82
+ # --- Verify FTP connection ---
83
+ st.write("Verifying FTP connection...")
84
+ try:
85
+ ftp = ftplib.FTP()
86
+ ftp.connect(ftp_host, ftp_port, timeout=10)
87
+ ftp.login(ftp_username, ftp_password)
88
+ st.success("FTP connection successful!")
89
+ except Exception as e:
90
+ st.error(f"FTP connection failed: {e}")
91
+ return
92
+
93
+ # Create download folder if it doesn't exist.
94
+ if not os.path.exists(download_folder):
95
+ os.makedirs(download_folder)
96
+
97
+ # --- Start torrent download ---
98
+ downloaded_folder = download_torrent(magnet_link, download_folder)
99
+
100
+ # --- Upload downloaded files to FTP ---
101
+ st.write("Uploading downloaded files to FTP...")
102
+ for root, dirs, files in os.walk(downloaded_folder):
103
+ for file in files:
104
+ local_file = os.path.join(root, file)
105
+ remote_file = file # You can adjust the remote path as needed
106
+ st.write(f"Uploading {file}...")
107
+ try:
108
+ ftp_upload_file(ftp, local_file, remote_file)
109
+ st.success(f"Uploaded {file} successfully!")
110
+ except Exception as e:
111
+ st.error(f"Failed to upload {file}: {e}")
112
+
113
+ ftp.quit()
114
+ st.success("All files uploaded. FTP connection closed.")
115
+
116
+ if __name__ == '__main__':
117
+ main()