def trim_file(): if request.form["request_type"] == "upload_complete": chosen_file = request.files["chosen_file"] # Make the filename safe filename_secure = secure_filename(chosen_file.filename) # Save the uploaded file to the uploads folder. chosen_file.save(os.path.join("uploads", filename_secure)) return '' if request.form["request_type"] == "trim": filename = request.form["filename"] log_this(f'wants to trim: {filename}') uploaded_file_path = os.path.join("uploads", secure_filename(filename)) start_time = request.form["start_time"] end_time = request.form["end_time"] ext = "." + filename.split(".")[-1] just_name = filename.split(".")[0] output_name = just_name + " [trimmed]" + ext log.info(f'ffmpeg -y -ss {start_time} -i "{uploaded_file_path}" ' f'-to {end_time} -map 0 -c copy "trims/{output_name}"') os.system(f'ffmpeg -y -ss {start_time} -i "{uploaded_file_path}" ' f'-to {end_time} -map 0 -c copy "trims/{output_name}"') return { "message": "File trimmed. The trimmed file will now start downloading.", "downloadFilePath": f'/trims/{output_name}' }
def trim_file(): if request.form["request_type"] == "upload_complete": chosen_file = request.files["chosen_file"] # Make the filename safe filename_secure = secure_filename(chosen_file.filename) # Save the uploaded file to the uploads folder. chosen_file.save(os.path.join("uploads", filename_secure)) return '' if request.form["request_type"] == "trim": filename = request.form["filename"] log_this(f'wants to trim: {filename}') uploaded_file_path = os.path.join("uploads", secure_filename(filename)) start_time = request.form["start_time"] log.info(f'START TIME: {start_time}') end_time = request.form["end_time"] log.info(f'END TIME: {end_time}') ext = "." + filename.split(".")[-1] just_name = filename.split(".")[0] output_name = just_name + " [trimmed]" + ext output_file_path = os.path.join('trims', output_name) subprocess.run([ 'ffmpeg', '-y', '-i', uploaded_file_path, '-ss', start_time, '-to', end_time, '-map', '0', '-c', 'copy', output_file_path ], shell=False) return output_file_path
def homepage(): if request.form['request_type'] == 'uploaded': log_this(f'Uploaded {request.files["chosen_file"].filename}') filename_secure = secure_filename( request.files['chosen_file'].filename) # Save the uploaded file to the uploads folder. request.files['chosen_file'].save( os.path.join('uploads', filename_secure)) session['progress_filename'] = f'{str(time())[:-8]}.txt' with open( os.path.join('ffmpeg-progress', session['progress_filename']), 'w'): pass return os.path.join('api', 'ffmpeg-progress', session['progress_filename'])
def trim_file(): if request.form["request_type"] == "upload_complete": uploaded_file = request.files["chosen_file"] # Make the filename safe filename_secure = secure_filename(uploaded_file.filename) # Save the uploaded file to the trims folder. uploaded_file.save(os.path.join('uploads', filename_secure)) # Empty the trims folder to ensure that there will be enough storage space for the trimmed file. if os.path.exists('trims'): for file in os.listdir('trims'): os.remove(os.path.join('trims', file)) log.info(f'Deleted trims/{file}') return '' if request.form["request_type"] == "trim": filename = request.form["filename"] log_this(f'wants to trim: {filename}') uploaded_file_path = os.path.join("uploads", secure_filename(filename)) start_time = request.form["start_time"] log.info(f'Start: {start_time}') end_time = request.form["end_time"] log.info(f'End: {end_time}') just_name = os.path.splitext(filename)[0] extension = os.path.splitext(filename)[1] output_name = f'{just_name} [trimmed]{extension}' output_file_path = os.path.join('trims', output_name) try: subprocess.run([ 'ffmpeg', '-y', '-i', uploaded_file_path, '-ss', start_time, '-to', end_time, '-map', '0', '-c', 'copy', output_file_path ]) except Exception as error: log.error(f'Unable to trim file: \n{error}') return output_file_path
def yt_downloader(): # First POST request: progress_filename = str(time.time())[:-8] if request.form['button_clicked'] == 'yes': link = request.form['link'] if converter.does_variable_contain_bad_string(link, strings_not_allowed): return 'You tried being clever, but there is a server-side check for disallowed strings.', 400 else: # Create the progress file. with open(f'static/progress/{progress_filename}.txt', "w"): pass media_extensions = [ "mp4", "webm", "opus", "mkv", "aac", "m4a", "mp3" ] # Delete the videos that have already been downloaded so send_from_directory does not send back the wrong file. for file in os.listdir(): if file.split(".")[-1] in media_extensions: os.remove(file) return progress_filename # The rest of the code runs on the 2nd POST request: path_to_progress_file = f'static/progress/{progress_filename}.txt' link = request.form['link'] source = urllib.request.urlopen(f'{link}').read() soup = BeautifulSoup(source, features="html.parser") title = (soup.title.string[:-10]).replace('#', '') media_extensions = ["mp4", "webm", "opus", "mkv", "aac", "m4a", "mp3"] if request.form['button_clicked'] == 'Video [best]': log_this('chose Video [best]') log.info(f'They want to download {title}') os.system(f'youtube-dl --newline {link} | tee {path_to_progress_file}') #delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: log.info(f'Downloaded {file}') return f'/yt/{file}' elif request.form['button_clicked'] == 'Video [MP4]': log_this('chose Video [MP4]') log.info(f'They want to download {title}') os.system( f'youtube-dl --newline -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best" ' f'{link} | tee {path_to_progress_file}') #delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: log.info(f'Downloaded {file}') return f'/yt/{file}' elif request.form['button_clicked'] == 'Audio [best]': log_this('chose Audio [best]') log.info(f'They want to download {title}') os.system( f'youtube-dl --newline -x {link} | tee {path_to_progress_file}') #delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: log.info(f'Downloaded {file}') return f'/yt/{file}' elif request.form['button_clicked'] == 'MP3': log_this('chose MP3') log.info(f'They want to download {title}') os.system( f'youtube-dl --newline -x --audio-format mp3 --audio-quality 0 ' f'--embed-thumbnail {link} | tee {path_to_progress_file}') #delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: log.info(f'Downloaded {file}') return f'/yt/{file}'
def yt_downloader(): # First POST request when the user clicks on a download button. if request.form['button_clicked'] == 'yes': log_this('Clicked on a download button.') update_database() # I want to save the download progress to a file and read from that file to show the download progress # to the user. Set the name of the file to the time since the epoch. progress_file_name = f'{str(time())[:-8]}.txt' session['progress_file_path'] = os.path.join('yt-progress', progress_file_name) return session['progress_file_path'] # Second POST request: video_link = request.form['link'] video_id = video_link.split('=')[1] if get_video_id(video_link) is None else get_video_id(video_link) # Video (best quality) if request.form['button_clicked'] == 'Video [best]': log.info(f'{video_link} | Video') options = { 'format': 'bestvideo+bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s-%(id)s-[video].%(ext)s', 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl([video_link], options) return send_json_response(session['progress_file_path'], video_id, '-[video]') # MP4 elif request.form['button_clicked'] == 'Video [MP4]': log.info(f'{video_link} | MP4') options = { 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', 'outtmpl': f'{download_dir}/%(title)s-%(id)s-[MP4].%(ext)s', 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl([video_link], options) return send_json_response(session['progress_file_path'], video_id, '-[MP4]') # Audio (best quality) elif request.form['button_clicked'] == 'Audio [best]': log.info(f'{video_link} | Audio') options = { 'format': 'bestaudio', 'outtmpl': f'{download_dir}/%(title)s-%(id)s-[audio].%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio' }], 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl([video_link], options) return send_json_response(session['progress_file_path'], video_id, '-[audio]') # MP3 elif request.form['button_clicked'] == 'MP3': log.info(f'{video_link} | MP3') options = { 'format': 'bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s-%(id)s-[MP3].%(ext)s', 'postprocessors': [ { 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '0' # -q:a 0 }, { 'key': 'EmbedThumbnail' } ], 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl([video_link], options) return send_json_response(session['progress_file_path'], video_id, '-[MP3]')
def yt_downloader(): # First POST request when the user clicks on a download button. if request.form['button_clicked'] == 'yes': log_this('clicked a download button.') # Use the get_ip function imported from loggers.py user_ip = get_ip() # Query the database by IP. user = User.query.filter_by(ip=user_ip).first() if user: x = 'time' if user.times_used_yt_downloader == 1 else 'times' log.info(f'This user has used the downloader {user.times_used_yt_downloader} {x} before.') user.times_used_yt_downloader += 1 db.session.commit() else: new_user = User(ip=user_ip, times_used_yt_downloader=1, mb_downloaded=0) db.session.add(new_user) db.session.commit() # I want to save the download progress to a file and read from that file to show the download progress # to the user. Set the name of the file to the time since the epoch. progress_file_name = f'{str(time.time())[:-8]}.txt' session['progress_file_path'] = os.path.join('yt-progress', progress_file_name) log.info(f'Progress will be saved to: {session["progress_file_path"]}') return session['progress_file_path'] # Second POST request: video_link = request.form['link'] # Use the get_video_id function to get the video ID from the link. video_id = str(get_video_id(video_link)) log.info(f'{video_link} | {video_id}') download_template = f'{download_dir}/%(title)s-%(id)s.%(ext)s' # Video [best] if request.form['button_clicked'] == 'Video [best]': args = [youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-o', download_template, '--', video_id] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info(f'Video [best] was chosen. Download took: {round((download_complete_time - download_start_time), 1)}s') return send_json_response(session['progress_file_path'], video_id) # Video [MP4] elif request.form['button_clicked'] == 'Video [MP4]': args = [youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', '-o', download_template, '--', video_id] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info(f'MP4 was chosen. Download took: {round((download_complete_time - download_start_time), 1)}s') return send_json_response(session['progress_file_path'], video_id, applicable_extensions) # Audio [best] elif request.form['button_clicked'] == 'Audio [best]': args = [youtube_dl_path, '--newline','--restrict-filenames', '--cookies', 'cookies.txt', '-x', '-o', download_template, '--', video_id] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info(f'Audio [best] was chosen. Download took: {round((download_complete_time - download_start_time), 1)}s') return send_json_response(session['progress_file_path'], video_id) # MP3 elif request.form['button_clicked'] == 'MP3': args = [youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-x', '--embed-thumbnail', '--audio-format', 'mp3', '--audio-quality', '0', '-o', download_template, '--', video_id] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info(f'MP3 was chosen. Download took: {round((download_complete_time - download_start_time), 1)}s') return send_json_response(session['progress_file_path'], video_id)
def yt_downloader(): # First POST request when the user clicks on a download button. if request.form['button_clicked'] == 'yes': log_this('Clicked on a download button.') update_database() # I want to save the download progress to a file and read from that file to show the download progress # to the user. Set the name of the file to the time since the epoch. progress_file_name = f'{str(time())[:-8]}.txt' session['progress_file_path'] = os.path.join('yt-progress', progress_file_name) return session['progress_file_path'] # Second POST request: video_link = request.form['link'] # If the user clicked on the "Other" button. if request.form['button_clicked'] == 'other': log.info(f'{video_link} | Other') video_audio_streams = [] options = {} with YoutubeDL(options) as ydl: info = ydl.extract_info(video_link, download=False) for data in info['formats']: if data['filesize'] is not None: filesize = f"{round(int(data['filesize']) / 1000000, 1)} MB" if data['height'] is None: stream_type = 'Audio' resolution = 'N/A' codec = 'AAC' if 'mp4a' in data['acodec'] else data['acodec'] extension = '.weba' if data[ 'ext'] == 'webm' else f".{data['ext']}" else: stream_type = 'Video' resolution = f"{data['height']}x{data['width']}" if 'avc' in data['vcodec']: codec = 'AVC' elif 'av01' in data['vcodec']: codec = 'AV1' elif data['vcodec'] == 'vp9': codec = 'VP9' else: codec = data['vcodec'] extension = f".{data['ext']}" video_audio_streams.append({ 'type': stream_type, 'resolution': resolution, 'codec': codec, 'extension': extension, 'filesize': filesize, 'video_url': data['url'] }) video_audio_streams = json.dumps(video_audio_streams[::-1]) return jsonify(streams=video_audio_streams) # Video (best quality) elif request.form['button_clicked'] == 'Video [best]': log.info(f'{video_link} | Video') options = { 'format': 'bestvideo+bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s-[video].%(ext)s', 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return send_json_response('-[video].') # MP4 elif request.form['button_clicked'] == 'Video [MP4]': log.info(f'{video_link} | MP4') options = { 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', 'outtmpl': f'{download_dir}/%(title)s-[MP4].%(ext)s', 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return send_json_response('-[MP4].') # Audio (best quality) elif request.form['button_clicked'] == 'Audio [best]': log.info(f'{video_link} | Audio') options = { 'format': 'bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s-[audio].%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio' }], 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return send_json_response('-[audio].') # MP3 elif request.form['button_clicked'] == 'MP3': log.info(f'{video_link} | MP3') options = { 'format': 'bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s-[MP3].%(ext)s', 'writethumbnail': True, 'postprocessors': [ { 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '0' # -q:a 0 }, { 'key': 'EmbedThumbnail' } ], 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return send_json_response('-[MP3].')
def yt_downloader(): if request.form['button_clicked'] == 'yes': log_this('Clicked a download button.') #db.create_all() # Intialise the size_of_media_files variable size_of_media_files = 0 # Iterate over each file in the folder and add its size to the above variable. for file in os.listdir(download_dir): size_of_file = os.path.getsize( f'{download_dir}/{file}') / 1_000_000 size_of_media_files += size_of_file # If there's more than 10 GB of files in the downloads folder, empty it. if size_of_media_files > 10_000: log.info( f'More than 10 GB worth of downloads found. Emptying downloads folder...' ) for file in os.listdir(download_dir): if file.split('.')[-1] in relevant_extensions: os.remove(f'{download_dir}/{file}') log.info('Downloads folder emptied.') # I want to save the download progress to a file and read from that file to show the download progress # to the user. Set the name of the file to the time since the epoch. progress_file_name = str(time.time())[:-8] + '.txt' session['progress_file_path'] = os.path.join('yt-progress', progress_file_name) log.info( f'Progress will be saved to: {session["progress_file_path"] }') user_ip = get_ip() user = User.query.filter_by(ip=user_ip).first() if user: x = 'time' if user.times_used_yt_downloader == 1 else 'times' log.info( f'This user has used the downloader {user.times_used_yt_downloader} {x} before.' ) user.times_used_yt_downloader += 1 db.session.commit() else: new_user = User(ip=user_ip, times_used_yt_downloader=1, mb_downloaded=0) db.session.add(new_user) db.session.commit() return session['progress_file_path'] # The following runs after the 2nd POST request: link = request.form['link'] video_id = str(get_video_id(link)) log.info(f'LINK: {link} | ID: {video_id}') if request.form['button_clicked'] == 'Video [best]': log.info(f'Video [best] was chosen.') download_template = f'{download_dir}/%(title)s-%(id)s [Video].%(ext)s' args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-o', download_template, '--', video_id ] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(session['progress_file_path'], video_id, '[Video]') return download_link elif request.form['button_clicked'] == 'Video [MP4]': log.info(f'MP4 was chosen.') download_template = f'{download_dir}/%(title)s-%(id)s [MP4].%(ext)s' args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', '-o', download_template, '--', video_id ] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(session['progress_file_path'], video_id, '[MP4]') return download_link elif request.form['button_clicked'] == 'Audio [best]': log.info(f'Audio [best] was chosen.') download_template = f'{download_dir}/%(title)s-%(id)s [Audio].%(ext)s' args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-x', '-o', download_template, '--', video_id ] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(session['progress_file_path'], video_id, '[Audio]') return download_link elif request.form['button_clicked'] == 'MP3': log.info(f'MP3 was chosen.') download_template = f'{download_dir}/%(title)s-%(id)s [MP3].%(ext)s' args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-x', '--embed-thumbnail', '--audio-format', 'mp3', '--audio-quality', '0', '-o', download_template, '--', video_id ] download_start_time = time.time() with open(session['progress_file_path'], 'w') as f: subprocess.run(args, stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(session['progress_file_path'], video_id, '[MP3]') return download_link
def homepage(): if request.form['request_type'] == 'log_convert_clicked': log_this('clicked on the convert button.') return '' elif request.form["request_type"] == "uploaded": session['progress_filename'] = str(time())[:-8] + '.txt' log_this('uploaded a file:') chosen_file = request.files["chosen_file"] filesize = request.form["filesize"] log.info(chosen_file) log.info(f'Size: {filesize} MB') # Make the filename safe filename_secure = secure_filename(chosen_file.filename) # Save the uploaded file to the uploads folder. os.makedirs('uploads', exist_ok=True) chosen_file.save(os.path.join("uploads", filename_secure)) return session['progress_filename'] elif request.form["request_type"] == "convert": wav_bit_depth = request.form["wav_bit_depth"] filename = request.form["filename"] chosen_codec = request.form["chosen_codec"] crf_value = request.form["crf_value"] mp4_encoding_mode = request.form["mp4_encoding_mode"] is_keep_video = request.form["is_keep_video"] uploaded_file_path = os.path.join("uploads", secure_filename(filename)) # MP3 mp3_encoding_type = request.form["mp3_encoding_type"] mp3_bitrate = request.form["mp3_bitrate"] mp3_vbr_setting = request.form["mp3_vbr_setting"] # AAC fdk_type = request.form["fdk_type"] fdk_cbr = request.form["fdk_cbr"] fdk_vbr = request.form["fdk_vbr"] is_fdk_lowpass = request.form["is_fdk_lowpass"] fdk_lowpass = request.form["fdk_lowpass"] # Vorbis vorbis_encoding = request.form["vorbis_encoding"] vorbis_quality = request.form["vorbis_quality"] # Vorbis/Opus opus_vorbis_slider = request.form["opus_vorbis_slider"] # AC3 ac3_bitrate = request.form["ac3_bitrate"] # FLAC flac_compression = request.form["flac_compression"] # DTS dts_bitrate = request.form["dts_bitrate"] # Opus opus_cbr_bitrate = request.form["opus_cbr_bitrate"] opus_encoding_type = request.form["opus_encoding_type"] # Desired filename output_name = request.form["output_name"] log.info(f'They chose {chosen_codec} | Output Filename: {output_name}') os.makedirs('conversions', exist_ok=True) output_path = os.path.join('conversions', output_name) def run_converter(codec, params): codec_to_converter = { "aac": converter.aac, "ac3": converter.ac3, "alac": converter.alac, "dts": converter.dts, "flac": converter.flac, "mka": converter.mka, "mkv": converter.mkv, "mp3": converter.mp3, "mp4": converter.mp4, "opus": converter.opus, "vorbis": converter.vorbis, "wav": converter.wav } return codec_to_converter[codec](*params) # Run the appropriate function in converter.py: # AAC if chosen_codec == 'AAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, fdk_type, fdk_cbr, fdk_vbr, is_fdk_lowpass, fdk_lowpass, output_path ] extension = run_converter('aac', params) # AC3 elif chosen_codec == 'AC3': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, ac3_bitrate, output_path ] extension = run_converter('ac3', params) # ALAC elif chosen_codec == 'ALAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, output_path ] extension = run_converter('alac', params) # CAF elif chosen_codec == 'CAF': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('caf', params) # DTS elif chosen_codec == 'DTS': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, dts_bitrate, output_path ] extension = run_converter('dts', params) # FLAC elif chosen_codec == 'FLAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, flac_compression, output_path ] extension = run_converter('flac', params) # MKA elif chosen_codec == 'MKA': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('mka', params) # MKV elif chosen_codec == 'MKV': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('mkv', params) # MP3 elif chosen_codec == 'MP3': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, mp3_encoding_type, mp3_bitrate, mp3_vbr_setting, output_path ] extension = run_converter('mp3', params) # MP4 elif chosen_codec == 'MP4': params = [ session['progress_filename'], uploaded_file_path, mp4_encoding_mode, crf_value, output_path ] extension = run_converter('mp4', params) # Opus elif chosen_codec == 'Opus': params = [ session['progress_filename'], uploaded_file_path, opus_encoding_type, opus_vorbis_slider, opus_cbr_bitrate, output_path ] extension = run_converter('opus', params) # Vorbis elif chosen_codec == 'Vorbis': params = [ session['progress_filename'], uploaded_file_path, vorbis_encoding, vorbis_quality, opus_vorbis_slider, output_path ] extension = run_converter('vorbis', params) # WAV elif chosen_codec == 'WAV': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, wav_bit_depth, output_path ] extension = run_converter('wav', params) # Filename after conversion. converted_file_name = f'{output_name}.{extension}' return { 'download_path': os.path.join('conversions', converted_file_name), 'log_file': os.path.join('ffmpeg-progress', f'{session["progress_filename"]}.txt') }
def yt_downloader(): user_ip = request.environ['HTTP_X_FORWARDED_FOR'] user = User.query.filter_by(ip=user_ip).first() if user: user.times_used_yt_downloader += 1 x = 'time' if user.times_used_yt_downloader == 1 else 'times' log.info( f'This user has used the downloader {user.times_used_yt_downloader} {x}.' ) db.session.commit() else: new_user = User(ip=user_ip, times_used_yt_downloader=1) db.session.add(new_user) db.session.commit() # I want to save the download progress to a file and read from that file to show the download progress to the user. # Set the name of the file to the time since the epoch. progress_filename = str(time.time())[:-8] path_to_progress_file = f'static/yt-progress/{progress_filename}.txt' if request.form['button_clicked'] == 'yes': log_this('Clicked a button.') link = request.form['link'] # Create the progress file. with open(path_to_progress_file, "w"): pass log.info(f'Progress will be saved to: {path_to_progress_file}') return progress_filename # The following runs after the 2nd POST request: size_of_media_files = 0 # Get the total size of the media files in the download folder. for file in os.listdir(download_dir): size_of_file = os.path.getsize(f'{download_dir}/{file}') / 1_000_000 size_of_media_files += size_of_file log.info(f'SIZE OF MEDIA FILES: {round(size_of_media_files, 2)} MB') # If there's more than 10 GB of media files, delete them: if size_of_media_files > 10_000: log.info(f'More than 10 GB worth of media files found.') for file in os.listdir(download_dir): if file.split('.')[-1] in relevant_extensions: os.remove(f'{download_dir}/{file}') log.info(f'DELETED {file}') link = request.form['link'] #download_template = f'{download_dir}/%(title)s.%(ext)s' video_id = get_video_id(link) if request.form['button_clicked'] == 'Video [best]': log.info(f'Video [best] was chosen. {link}') download_template = f'{download_dir}/%(title)s-%(id)s [Video].%(ext)s' download_start_time = time.time() with open(path_to_progress_file, 'w') as f: subprocess.run([ youtube_dl_path, '-v', '-o', download_template, '--newline', '--', video_id ], stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(path_to_progress_file, video_id, '[Video]') return download_link elif request.form['button_clicked'] == 'Video [MP4]': log.info(f'MP4 was chosen. {link}') download_template = f'{download_dir}/%(title)s-%(id)s [MP4].%(ext)s' download_start_time = time.time() with open(path_to_progress_file, 'w') as f: subprocess.run([ youtube_dl_path, '-v', '--embed-thumbnail', '-o', download_template, '--newline', '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', '--', video_id ], stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(path_to_progress_file, video_id, '[MP4]') return download_link elif request.form['button_clicked'] == 'Audio [best]': log.info(f'Audio [best] was chosen. {link}') download_template = f'{download_dir}/%(title)s-%(id)s [Audio].%(ext)s' download_start_time = time.time() with open(path_to_progress_file, 'w') as f: subprocess.run([ youtube_dl_path, '-v', '-o', download_template, '--newline', '-x', '--', video_id ], stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(path_to_progress_file, video_id, '[Audio]') return download_link elif request.form['button_clicked'] == 'MP3': log.info(f'MP3 was chosen. {link}') download_template = f'{download_dir}/%(title)s-%(id)s [MP3].%(ext)s' download_start_time = time.time() with open(path_to_progress_file, 'w') as f: subprocess.run([ youtube_dl_path, '-v', '--embed-thumbnail', '-o', download_template, '--newline', '-x', '--audio-format', 'mp3', '--audio-quality', '0', '--', video_id ], stdout=f) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(path_to_progress_file, video_id, '[MP3]') return download_link
def yt_downloader(): progress_filename = str(time.time())[:-8] path_to_progress_file = f'static/progress/{progress_filename}.txt' if request.form['button_clicked'] == 'yes': log_this('Clicked a button.') link = request.form['link'] if converter.does_variable_contain_bad_string(link, strings_not_allowed): log.info('Bad string detected.') return 'You tried being clever, but there is a server-side check for disallowed strings.', 400 else: # Create the progress file. with open(path_to_progress_file, "w"): pass return progress_filename # The rest runs after the 2nd POST request: size_of_media_files = 0 # Get the total size of the media files in the download folder. for file in os.listdir(download_dir): size_of_file = os.path.getsize(f'{download_dir}/{file}') / 1_000_000 size_of_media_files += size_of_file log.info(f'SIZE OF MEDIA FILES: {round(size_of_media_files, 2)} MB') # If there's more than 10 GB of media files, delete them: if size_of_media_files > 10_000: log.info(f'More than 10 GB worth of media files found.') for file in os.listdir(download_dir): if file.split('.')[-1] in relevant_extensions: os.remove(f'{download_dir}/{file}') log.info(f'DELETED {file}') link = request.form['link'] download_template = f'{download_dir}/%(title)s-%(id)s.%(ext)s' video_id = get_video_id(link) if request.form['button_clicked'] == 'Video [best]': log.info(f'Video [best] was chosen. {link}') download_start_time = time.time() os.system( f'{youtube_dl} -o "{download_template}" --newline {video_id} | tee {path_to_progress_file}' ) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(video_id) return download_link elif request.form['button_clicked'] == 'Video [MP4]': log.info(f'MP4 was chosen. {link}') download_start_time = time.time() os.system( f'{youtube_dl} -o "{download_template}" --embed-thumbnail --newline -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best" ' f'{video_id} | tee {path_to_progress_file}') download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(video_id) return download_link elif request.form['button_clicked'] == 'Audio [best]': log.info(f'Audio [best] was chosen. {link}') download_start_time = time.time() os.system( f'{youtube_dl} -o "{download_template}" --newline -x {video_id} | tee {path_to_progress_file}' ) download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(video_id) return download_link elif request.form['button_clicked'] == 'MP3': log.info(f'MP3 was chosen. {link}') download_start_time = time.time() os.system( f'{youtube_dl} -o "{download_template}" --newline -x --embed-thumbnail --audio-format mp3 --audio-quality 0 {video_id} | ' f'tee {path_to_progress_file}') download_complete_time = time.time() log.info( f'Download took: {round((download_complete_time - download_start_time), 1)}s' ) download_link = return_download_link(video_id) return download_link
def yt_downloader(): progress_filename = str(time.time())[:-8] if request.form['button_clicked'] == 'yes': with open(f'static/progress/{progress_filename}.txt', "w"): pass return progress_filename path_to_progress_file = f'static/progress/{progress_filename}.txt' media_extensions = ["mp4", "webm", "opus", "mkv", "aac", "m4a", "mp3"] strings_not_allowed = [ 'command', ';', '$', '&&', '\\' '"', '*', '<', '>', '|', '`' ] link = request.form['link'] source = urllib.request.urlopen(f'{link}').read() soup = BeautifulSoup(source, features="html.parser") title = (soup.title.string[:-10]).replace('#', '') # check_no_variable_contains_bad_string is a func defined in converter.py if not converter.check_no_variable_contains_bad_string( link, strings_not_allowed): return { "message": "You tried being clever, but there's a server-side check for disallowed strings." }, 400 # Delete the videos that have already been downloaded so send_from_directory does not send back the wrong file. for file in os.listdir(): if file.split(".")[-1] in media_extensions: os.remove(file) else: pass if request.form['button_clicked'] == 'Video [best]': log_this('chose Video [best]') log.info(title) os.system(f'youtube-dl --newline {link} | tee {path_to_progress_file}') log.info('DOWNLOAD COMPLETE.') delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: return f'/yt/{file}' elif request.form['button_clicked'] == 'Video [MP4]': log_this('chose Video [MP4]') log.info(title) os.system( f'youtube-dl --newline -f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best" ' f'{link} | tee {path_to_progress_file}') log.info('DOWNLOAD COMPLETE.') delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: return f'/yt/{file}' elif request.form['button_clicked'] == 'Audio [best]': log_this('chose Audio [best]') log.info(title) os.system( f'youtube-dl --newline -x {link} | tee {path_to_progress_file}') log.info('DOWNLOAD COMPLETE.') delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: return f'/yt/{file}' elif request.form['button_clicked'] == 'MP3': log_this('chose Audio [MP3]') log.info(title) os.system( f'youtube-dl --newline -x --audio-format mp3 --audio-quality 0 ' f'--embed-thumbnail {link} | tee {path_to_progress_file}') log.info('DOWNLOAD COMPLETE.') delete_progress_files() with open("downloaded-files.txt", "a") as f: f.write("\n" + title + " downloaded.") for file in os.listdir(): if file.split(".")[-1] in media_extensions: return f'/yt/{file}'
def homepage(): if request.form['request_type'] == 'log_convert_clicked': log_this('clicked on the convert button.') return '' elif request.form["request_type"] == "uploaded": session['progress_filename'] = str(time())[:-8] log_this('uploaded a file:') chosen_file = request.files["chosen_file"] filesize = request.form["filesize"] log.info(chosen_file) log.info(f'Size: {filesize} MB') # Make the filename safe filename_secure = secure_filename(chosen_file.filename) # Save the uploaded file to the uploads folder. os.makedirs('uploads', exist_ok=True) chosen_file.save(os.path.join("uploads", filename_secure)) return session['progress_filename'] elif request.form["request_type"] == "convert": wav_bit_depth = request.form["wav_bit_depth"] filename = request.form["filename"] chosen_codec = request.form["chosen_codec"] crf_value = request.form["crf_value"] mp4_encoding_mode = request.form["mp4_encoding_mode"] is_keep_video = request.form["is_keep_video"] uploaded_file_path = os.path.join("uploads", secure_filename(filename)) # MP3 mp3_encoding_type = request.form["mp3_encoding_type"] mp3_bitrate = request.form["mp3_bitrate"] mp3_vbr_setting = request.form["mp3_vbr_setting"] # AAC fdk_type = request.form["fdk_type"] fdk_cbr = request.form["fdk_cbr"] fdk_vbr = request.form["fdk_vbr"] is_fdk_lowpass = request.form["is_fdk_lowpass"] fdk_lowpass = request.form["fdk_lowpass"] # Vorbis vorbis_encoding = request.form["vorbis_encoding"] vorbis_quality = request.form["vorbis_quality"] # Vorbis/Opus opus_vorbis_slider = request.form["opus_vorbis_slider"] # AC3 ac3_bitrate = request.form["ac3_bitrate"] # FLAC flac_compression = request.form["flac_compression"] # DTS dts_bitrate = request.form["dts_bitrate"] # Opus opus_cbr_bitrate = request.form["opus_cbr_bitrate"] opus_encoding_type = request.form["opus_encoding_type"] # Desired filename output_name = request.form["output_name"] log.info(f'They chose {chosen_codec} | Output Filename: {output_name}') os.makedirs('conversions', exist_ok=True) output_path = f'conversions/{output_name}' # Run the appropriate section of converter.py: if chosen_codec == 'MP3': converter.run_mp3(session['progress_filename'], uploaded_file_path, is_keep_video, mp3_encoding_type, mp3_bitrate, mp3_vbr_setting, output_path) if is_keep_video == "yes": just_ext = uploaded_file_path.split('.')[-1] if just_ext == 'mp4': extension = 'mp4' else: extension = 'mkv' else: extension = 'mp3' elif chosen_codec == 'AAC': converter.run_aac(session['progress_filename'], uploaded_file_path, is_keep_video, fdk_type, fdk_cbr, fdk_vbr, is_fdk_lowpass, fdk_lowpass, output_path) if is_keep_video == "yes": just_ext = uploaded_file_path.split('.')[-1] if just_ext == 'mp4': extension = 'mp4' else: extension = 'mkv' else: extension = 'm4a' elif chosen_codec == 'Opus': converter.run_opus(session['progress_filename'], uploaded_file_path, opus_encoding_type, opus_vorbis_slider, opus_cbr_bitrate, output_path) extension = 'opus' elif chosen_codec == 'FLAC': converter.run_flac(session['progress_filename'], uploaded_file_path, is_keep_video, flac_compression, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'flac' elif chosen_codec == 'Vorbis': converter.run_vorbis(session['progress_filename'], uploaded_file_path, vorbis_encoding, vorbis_quality, opus_vorbis_slider, output_path) extension = 'mka' elif chosen_codec == 'WAV': converter.run_wav(session['progress_filename'], uploaded_file_path, is_keep_video, wav_bit_depth, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'wav' elif chosen_codec == 'MKV': converter.run_mkv(session['progress_filename'], uploaded_file_path, output_path) extension = 'mkv' elif chosen_codec == 'MKA': converter.run_mka(session['progress_filename'], uploaded_file_path, output_path) extension = 'mka' elif chosen_codec == 'ALAC': converter.run_alac(session['progress_filename'], uploaded_file_path, is_keep_video, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'm4a' elif chosen_codec == 'AC3': converter.run_ac3(session['progress_filename'], uploaded_file_path, is_keep_video, ac3_bitrate, output_path) if is_keep_video == "yes": just_ext = uploaded_file_path.split('.')[-1] if just_ext == 'mp4': extension = 'mp4' else: extension = 'mkv' else: extension = 'ac3' elif chosen_codec == 'CAF': converter.run_caf(session['progress_filename'], uploaded_file_path, output_path) extension = 'caf' elif chosen_codec == 'DTS': converter.run_dts(session['progress_filename'], uploaded_file_path, is_keep_video, dts_bitrate, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'dts' elif chosen_codec == 'MP4': converter.run_mp4(session['progress_filename'], uploaded_file_path, mp4_encoding_mode, crf_value, output_path) extension = 'mp4' elif chosen_codec == 'MKV': converter.run_mkv(session['progress_filename'], uploaded_file_path, output_path) extension = 'mkv' converted_file_name = output_name + "." + extension return f'/conversions/{converted_file_name}'
def homepage(): # First POST request. if request.form['request_type'] == 'log_convert_clicked': log_this('clicked on the convert button.') return '' elif request.form["request_type"] == "convert_url": url = request.form["url"] conversion_progress_filename = f'{str(time())[:-8]}.txt' session['progress_filename'] = conversion_progress_filename return session['progress_filename'] # Second POST request. elif request.form["request_type"] == "uploaded": upload_time = datetime.now().strftime('%H:%M:%S') log.info(f'Upload complete at {upload_time}') uploaded_file = request.files["chosen_file"] filesize = request.form["filesize"] log.info(uploaded_file) log.info(f'Size: {filesize} MB') # Make the filename safe. filename_secure = secure_filename(uploaded_file.filename) # Save the uploaded file to the uploads folder. uploaded_file.save(os.path.join("uploads", filename_secure)) conversion_progress_filename = f'{str(time())[:-8]}.txt' session['progress_filename'] = conversion_progress_filename return session['progress_filename'] elif request.form["request_type"] == "convert": filename = request.form["filename"] if 'http' in filename and '://' in filename: uploaded_file_path = filename else: uploaded_file_path = os.path.join("uploads", secure_filename(filename)) chosen_codec = request.form["chosen_codec"] crf_value = request.form["crf_value"] video_mode = request.form["video_mode"] is_keep_video = request.form["is_keep_video"] # MP3 mp3_encoding_type = request.form["mp3_encoding_type"] mp3_bitrate = request.form["mp3_bitrate"] mp3_vbr_setting = request.form["mp3_vbr_setting"] # AAC fdk_type = request.form["fdk_type"] fdk_cbr = request.form["fdk_cbr"] fdk_vbr = request.form["fdk_vbr"] is_fdk_lowpass = request.form["is_fdk_lowpass"] fdk_lowpass = request.form["fdk_lowpass"] # Vorbis vorbis_encoding = request.form["vorbis_encoding"] vorbis_quality = request.form["vorbis_quality"] # Vorbis/Opus opus_vorbis_slider = request.form["opus_vorbis_slider"] # AC3 ac3_bitrate = request.form["ac3_bitrate"] # FLAC flac_compression = request.form["flac_compression"] # DTS dts_bitrate = request.form["dts_bitrate"] # Opus opus_cbr_bitrate = request.form["opus_cbr_bitrate"] opus_encoding_type = request.form["opus_encoding_type"] # WAV wav_bit_depth = request.form["wav_bit_depth"] # Desired filename output_name = request.form["output_name"] log.info(f'They chose {chosen_codec} | Output Filename: {output_name}') os.makedirs('conversions', exist_ok=True) output_path = os.path.join('conversions', output_name) # AAC if chosen_codec == 'AAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, fdk_type, fdk_cbr, fdk_vbr, is_fdk_lowpass, fdk_lowpass, output_path ] extension = run_converter('aac', params) # AC3 elif chosen_codec == 'AC3': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, ac3_bitrate, output_path ] extension = run_converter('ac3', params) # ALAC elif chosen_codec == 'ALAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, output_path ] extension = run_converter('alac', params) # CAF elif chosen_codec == 'CAF': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('caf', params) # DTS elif chosen_codec == 'DTS': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, dts_bitrate, output_path ] extension = run_converter('dts', params) # FLAC elif chosen_codec == 'FLAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, flac_compression, output_path ] extension = run_converter('flac', params) # MKA elif chosen_codec == 'MKA': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('mka', params) # MKV elif chosen_codec == 'MKV': params = [ session['progress_filename'], uploaded_file_path, video_mode, crf_value, output_path ] extension = run_converter('mkv', params) # MP3 elif chosen_codec == 'MP3': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, mp3_encoding_type, mp3_bitrate, mp3_vbr_setting, output_path ] extension = run_converter('mp3', params) # MP4 elif chosen_codec == 'MP4': params = [ session['progress_filename'], uploaded_file_path, video_mode, crf_value, output_path ] extension = run_converter('mp4', params) # Opus elif chosen_codec == 'Opus': params = [ session['progress_filename'], uploaded_file_path, opus_encoding_type, opus_vorbis_slider, opus_cbr_bitrate, output_path ] extension = run_converter('opus', params) # Vorbis elif chosen_codec == 'Vorbis': params = [ session['progress_filename'], uploaded_file_path, vorbis_encoding, vorbis_quality, opus_vorbis_slider, output_path ] extension = run_converter('vorbis', params) # WAV elif chosen_codec == 'WAV': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, wav_bit_depth, output_path ] extension = run_converter('wav', params) # Filename after conversion. converted_file_name = f'{output_name}.{extension}' return { 'download_path': os.path.join('conversions', converted_file_name), 'log_file': os.path.join('ffmpeg-progress', session["progress_filename"]) }
def homepage(): # First POST request. if request.form['request_type'] == 'log_convert_clicked': log_this('clicked on the convert button.') return '' # Second POST request. elif request.form["request_type"] == "uploaded": upload_time = datetime.now().strftime('%H:%M:%S') log.info(f'Upload complete at {upload_time}') # Empty the conversions folder to ensure there's room for the file that is going to be converted. for file in os.listdir('conversions'): os.remove(os.path.join('conversions', file)) log.info(f'Deleted conversions/{file}') uploads_folder_size = 0 # Iterate over each file in the folder and add its size to the above variable. for file in os.listdir('uploads'): size_of_file = os.path.getsize(f'uploads/{file}') / 1_000_000 uploads_folder_size += size_of_file # If there's more than 1 GB of files in the conversions folder, empty it. if uploads_folder_size > 1000: log.info( f'More than 1 GB worth of uploads found. Emptying uploads folder...' ) for file in os.listdir('uploads'): os.remove(os.path.join('uploads', file)) log.info('Conversions folder emptied.') # Grabbing the JavaScript FormData chosen_file = request.files["chosen_file"] filesize = request.form["filesize"] log.info(chosen_file) log.info(f'Size: {filesize} MB') # Make the filename safe filename_secure = secure_filename(chosen_file.filename) # Save the uploaded file to the uploads folder. os.makedirs('uploads', exist_ok=True) chosen_file.save(os.path.join("uploads", filename_secure)) conversion_progress_filename = f'{str(time())[:-8]}.txt' session['progress_filename'] = conversion_progress_filename return session['progress_filename'] elif request.form["request_type"] == "convert": conversion_start_time = time() wav_bit_depth = request.form["wav_bit_depth"] filename = request.form["filename"] chosen_codec = request.form["chosen_codec"] crf_value = request.form["crf_value"] mp4_encoding_mode = request.form["mp4_encoding_mode"] is_keep_video = request.form["is_keep_video"] uploaded_file_path = os.path.join("uploads", secure_filename(filename)) # MP3 mp3_encoding_type = request.form["mp3_encoding_type"] mp3_bitrate = request.form["mp3_bitrate"] mp3_vbr_setting = request.form["mp3_vbr_setting"] # AAC fdk_type = request.form["fdk_type"] fdk_cbr = request.form["fdk_cbr"] fdk_vbr = request.form["fdk_vbr"] is_fdk_lowpass = request.form["is_fdk_lowpass"] fdk_lowpass = request.form["fdk_lowpass"] # Vorbis vorbis_encoding = request.form["vorbis_encoding"] vorbis_quality = request.form["vorbis_quality"] # Vorbis/Opus opus_vorbis_slider = request.form["opus_vorbis_slider"] # AC3 ac3_bitrate = request.form["ac3_bitrate"] # FLAC flac_compression = request.form["flac_compression"] # DTS dts_bitrate = request.form["dts_bitrate"] # Opus opus_cbr_bitrate = request.form["opus_cbr_bitrate"] opus_encoding_type = request.form["opus_encoding_type"] # Desired filename output_name = request.form["output_name"] log.info(f'They chose {chosen_codec} | Output Filename: {output_name}') os.makedirs('conversions', exist_ok=True) output_path = os.path.join('conversions', output_name) def run_converter(codec, params): codec_to_converter = { "aac": converter.aac, "ac3": converter.ac3, "alac": converter.alac, "dts": converter.dts, "flac": converter.flac, "mka": converter.mka, "mkv": converter.mkv, "mp3": converter.mp3, "mp4": converter.mp4, "opus": converter.opus, "vorbis": converter.vorbis, "wav": converter.wav } # Pass the list of parameters (params) to the appropriate converter function. return codec_to_converter[codec](*params) # Run the appropriate function in converter.py: # AAC if chosen_codec == 'AAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, fdk_type, fdk_cbr, fdk_vbr, is_fdk_lowpass, fdk_lowpass, output_path ] extension = run_converter('aac', params) # AC3 elif chosen_codec == 'AC3': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, ac3_bitrate, output_path ] extension = run_converter('ac3', params) # ALAC elif chosen_codec == 'ALAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, output_path ] extension = run_converter('alac', params) # CAF elif chosen_codec == 'CAF': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('caf', params) # DTS elif chosen_codec == 'DTS': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, dts_bitrate, output_path ] extension = run_converter('dts', params) # FLAC elif chosen_codec == 'FLAC': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, flac_compression, output_path ] extension = run_converter('flac', params) # MKA elif chosen_codec == 'MKA': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('mka', params) # MKV elif chosen_codec == 'MKV': params = [ session['progress_filename'], uploaded_file_path, output_path ] extension = run_converter('mkv', params) # MP3 elif chosen_codec == 'MP3': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, mp3_encoding_type, mp3_bitrate, mp3_vbr_setting, output_path ] extension = run_converter('mp3', params) # MP4 elif chosen_codec == 'MP4': params = [ session['progress_filename'], uploaded_file_path, mp4_encoding_mode, crf_value, output_path ] extension = run_converter('mp4', params) # Opus elif chosen_codec == 'Opus': params = [ session['progress_filename'], uploaded_file_path, opus_encoding_type, opus_vorbis_slider, opus_cbr_bitrate, output_path ] extension = run_converter('opus', params) # Vorbis elif chosen_codec == 'Vorbis': params = [ session['progress_filename'], uploaded_file_path, vorbis_encoding, vorbis_quality, opus_vorbis_slider, output_path ] extension = run_converter('vorbis', params) # WAV elif chosen_codec == 'WAV': params = [ session['progress_filename'], uploaded_file_path, is_keep_video, wav_bit_depth, output_path ] extension = run_converter('wav', params) conversion_complete_time = time() log.info( f'Conversion took {round((conversion_complete_time - conversion_start_time), 1)} seconds.' ) # Filename after conversion. converted_file_name = f'{output_name}.{extension}' return { 'download_path': os.path.join('conversions', converted_file_name), 'log_file': os.path.join('ffmpeg-progress', session["progress_filename"]) }
def yt_downloader(): # First POST request: if request.form['button_clicked'] == 'yes': # Empty the downloads folder if there is less than 2 GB free storage space. free_space = shutil.disk_usage('/')[2] free_space_gb = free_space / 1_000_000_000 if free_space_gb < 2: empty_folder('downloads') progress_file_name = f'{str(time())[:-8]}.txt' session['progress_file_path'] = f'yt-progress/{progress_file_name}' return session['progress_file_path'], 200 # Second POST request: log_this(f'Clicked on {request.form["button_clicked"]}') user_ip = get_ip() # Query the database by IP. user = User.query.filter_by(ip=user_ip).first() if user: string = f'{user.times_used_yt_downloader} times' if user.times_used_yt_downloader > 1 else 'once' log.info(f'This user has used the downloader {string} before.') video_link = request.form['link'] log.info(video_link) # Video (best quality) if request.form['button_clicked'] == 'video_best': options = { 'format': 'bestvideo+bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s.%(ext)s', 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return return_download_path() # MP4 elif request.form['button_clicked'] == 'mp4': options = { 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', 'outtmpl': f'{download_dir}/%(title)s.%(ext)s', 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return return_download_path() # Audio (best quality) elif request.form['button_clicked'] == 'audio_best': options = { 'format': 'bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s.%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio' }], 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return return_download_path() # MP3 elif request.form['button_clicked'] == 'audio_mp3': options = { 'format': 'bestaudio/best', 'outtmpl': f'{download_dir}/%(title)s.%(ext)s', 'writethumbnail': True, 'postprocessors': [ { 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '0' }, { 'key': 'EmbedThumbnail' } ], 'restrictfilenames': True, 'logger': Logger() } run_youtube_dl(video_link, options) return return_download_path()
def yt_downloader(): # First POST request when the user clicks on a download button. if request.form['button_clicked'] == 'yes': log_this('clicked a download button.') downloads_folder_size = 0 for file in os.listdir(download_dir): # Downloads folder size in MB. downloads_folder_size += os.path.getsize( os.path.join(download_dir, file)) / 1_000_000 if downloads_folder_size > 3000: log.info( 'Downloads folder larger than 3 GB. Emptying the folder...') for file in os.listdir(download_dir): os.remove(os.path.join(download_dir, file)) log.info('Downloads folder emptied.') # Use the get_ip function imported from loggers.py user_ip = get_ip() # Query the database by IP. user = User.query.filter_by(ip=user_ip).first() if user: x = 'time' if user.times_used_yt_downloader == 1 else 'times' log.info( f'This user has used the downloader {user.times_used_yt_downloader} {x} before.' ) user.times_used_yt_downloader += 1 db.session.commit() else: new_user = User(ip=user_ip, times_used_yt_downloader=1, mb_downloaded=0) db.session.add(new_user) db.session.commit() # I want to save the download progress to a file and read from that file to show the download progress # to the user. Set the name of the file to the time since the epoch. progress_file_name = f'{str(time())[:-8]}.txt' session['progress_file_path'] = os.path.join('yt-progress', progress_file_name) log.info(f'Progress will be saved to: {session["progress_file_path"]}') return session['progress_file_path'] # Second POST request: video_link = request.form['link'] # Use the get_video_id function to get the video ID from the link. video_id = str(get_video_id(video_link)) log.info(f'{video_link} | {video_id}') download_template = f'{download_dir}/%(title)s-%(id)s.%(ext)s' # Video [best] if request.form['button_clicked'] == 'Video [best]': args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-o', download_template, '--', video_id ] run_youtube_dl(request.form['button_clicked'], args) log_downloads_per_day() return send_json_response(session['progress_file_path'], video_id) # Video [MP4] elif request.form['button_clicked'] == 'Video [MP4]': args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best', '-o', download_template, '--', video_id ] run_youtube_dl(request.form['button_clicked'], args) log_downloads_per_day() return send_json_response(session['progress_file_path'], video_id) # Audio [best] elif request.form['button_clicked'] == 'Audio [best]': args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-x', '-o', download_template, '--', video_id ] run_youtube_dl(request.form['button_clicked'], args) log_downloads_per_day() return send_json_response(session['progress_file_path'], video_id) # MP3 elif request.form['button_clicked'] == 'MP3': args = [ youtube_dl_path, '--newline', '--restrict-filenames', '--cookies', 'cookies.txt', '-x', '--audio-format', 'mp3', '--audio-quality', '0', '-o', download_template, '--', video_id ] run_youtube_dl(request.form['button_clicked'], args) log_downloads_per_day() return send_json_response(session['progress_file_path'], video_id)
def homepage(): if request.form['request_type'] == 'log_convert_clicked': log_this('clicked Convert Button') return '' elif request.form["request_type"] == "uploaded": session['progress_filename'] = str(time.time())[:-8] log_this('uploaded a file:') chosen_file = request.files["chosen_file"] filesize = request.form["filesize"] log.info(chosen_file) log.info(f'Size: {filesize} MB') # Make the filename safe filename_secure = secure_filename(chosen_file.filename) # Save the uploaded file to the uploads folder. chosen_file.save(os.path.join("uploads", filename_secure)) return session['progress_filename'] elif request.form["request_type"] == "convert": wav_bit_depth = request.form["wav_bit_depth"] filename = request.form["filename"] filename_without_ext = filename.split('.')[0] chosen_codec = request.form["chosen_codec"] crf_value = request.form["crf_value"] mp4_encoding_mode = request.form["mp4_encoding_mode"] is_keep_video = request.form["is_keep_video"] uploaded_file_path = os.path.join("uploads", secure_filename(filename)) # MP3 mp3_encoding_type = request.form["mp3_encoding_type"] mp3_bitrate = request.form["mp3_bitrate"] mp3_vbr_setting = request.form["mp3_vbr_setting"] # AAC fdk_type = request.form["fdk_type"] fdk_cbr = request.form["fdk_cbr"] fdk_vbr = request.form["fdk_vbr"] is_fdk_lowpass = request.form["is_fdk_lowpass"] fdk_lowpass = request.form["fdk_lowpass"] # Vorbis vorbis_encoding = request.form["vorbis_encoding"] vorbis_quality = request.form["vorbis_quality"] # Vorbis/Opus opus_vorbis_slider = request.form["opus_vorbis_slider"] # AC3 ac3_bitrate = request.form["ac3_bitrate"] # FLAC flac_compression = request.form["flac_compression"] # DTS dts_bitrate = request.form["dts_bitrate"] # Opus opus_cbr_bitrate = request.form["opus_cbr_bitrate"] opus_encoding_type = request.form["opus_encoding_type"] # Desired filename output_name = request.form["output_name"] variables_to_validate = [filename_without_ext, chosen_codec, is_keep_video, mp3_encoding_type, mp3_bitrate, mp3_vbr_setting, fdk_type, fdk_cbr, fdk_vbr, is_fdk_lowpass, vorbis_encoding, vorbis_quality, opus_vorbis_slider, ac3_bitrate, flac_compression, dts_bitrate, opus_cbr_bitrate, opus_encoding_type, output_name, wav_bit_depth, mp4_encoding_mode, crf_value] strings_not_allowed = ['command', ';', '$', '&&', '/', '\\' '"', '?', '*', '<', '>', '|', ':', '`', '.'] # check_no_variable_contains_bad_string is a func defined in converter.py if converter.is_bad_string_in_variables(variables_to_validate, strings_not_allowed): return 'You tried being clever, but there\'s a server-side check for disallowed strings', 400 else: log.info(f'They chose {chosen_codec}\nOutput Filename: {output_name}') output_path = f'"conversions/{output_name}"' # Run the appropritate section of converter.py: if chosen_codec == 'MP3': converter.run_mp3(session['progress_filename'], uploaded_file_path, is_keep_video, mp3_encoding_type, mp3_bitrate, mp3_vbr_setting, output_path) if is_keep_video == "yes": just_ext = uploaded_file_path.split('.')[-1] if just_ext == 'mp4': extension = 'mp4' else: extension = 'mkv' else: extension = 'mp3' elif chosen_codec == 'AAC': converter.run_aac(session['progress_filename'], uploaded_file_path, is_keep_video, fdk_type, fdk_cbr, fdk_vbr, is_fdk_lowpass, fdk_lowpass, output_path) if is_keep_video == "yes": just_ext = uploaded_file_path.split('.')[-1] if just_ext == 'mp4': extension = 'mp4' else: extension = 'mkv' else: extension = 'm4a' elif chosen_codec == 'Opus': converter.run_opus(session['progress_filename'], uploaded_file_path, opus_encoding_type, opus_vorbis_slider, opus_cbr_bitrate, output_path) extension = 'opus' elif chosen_codec == 'FLAC': converter.run_flac(session['progress_filename'], uploaded_file_path, is_keep_video, flac_compression, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'flac' elif chosen_codec == 'Vorbis': converter.run_vorbis(session['progress_filename'], uploaded_file_path, vorbis_encoding, vorbis_quality, opus_vorbis_slider, output_path) extension = 'mka' elif chosen_codec == 'WAV': converter.run_wav(session['progress_filename'], uploaded_file_path, is_keep_video, wav_bit_depth, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'wav' elif chosen_codec == 'MKV': converter.run_mkv(session['progress_filename'], uploaded_file_path, output_path) extension = 'mkv' elif chosen_codec == 'MKA': converter.run_mka(session['progress_filename'], uploaded_file_path, output_path) extension = 'mka' elif chosen_codec == 'ALAC': converter.run_alac(session['progress_filename'], uploaded_file_path, is_keep_video, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'm4a' elif chosen_codec == 'AC3': converter.run_ac3(session['progress_filename'], uploaded_file_path, is_keep_video, ac3_bitrate, output_path) if is_keep_video == "yes": just_ext = uploaded_file_path.split('.')[-1] if just_ext == 'mp4': extension = 'mp4' else: extension = 'mkv' else: extension = 'ac3' elif chosen_codec == 'CAF': converter.run_caf(session['progress_filename'], uploaded_file_path, output_path) extension = 'caf' elif chosen_codec == 'DTS': converter.run_dts(session['progress_filename'], uploaded_file_path, is_keep_video, dts_bitrate, output_path) if is_keep_video == "yes": extension = 'mkv' else: extension = 'dts' elif chosen_codec == 'MP4': converter.run_mp4(session['progress_filename'], uploaded_file_path, mp4_encoding_mode, crf_value, output_path) extension = 'mp4' elif chosen_codec == 'MKV': converter.run_mkv(session['progress_filename'], uploaded_file_path, output_path) extension = 'mkv' converted_file_name = output_name + "." + extension return f'/conversions/{converted_file_name}'