Amazing-Python-Scripts

Форк
0
140 строк · 3.4 Кб
1
# ALL Imports
2
import time
3
from tkinter.ttk import *
4
import tkinter as tk
5
from requests import get, HTTPError, ConnectionError
6
from re import findall
7
from urllib.parse import unquote
8
from threading import Thread
9
import queue
10
from queue import Empty
11

12

13
def Invalid_Url():
14
    """ Sets Status bar label to error message """
15
    Status["text"] = "Invalid URL..."
16
    Status["fg"] = "red"
17

18

19
def get_downloadlink(url):
20

21
    url = url.replace("www", "mbasic")
22
    try:
23
        r = get(url, timeout=5, allow_redirects=True)
24
        if r.status_code != 200:
25
            raise HTTPError
26
        a = findall("/video_redirect/", r.text)
27
        if len(a) == 0:
28
            print("[!] Video Not Found...")
29
            exit(0)
30
        else:
31
            return unquote(r.text.split("?src=")[1].split('"')[0])
32
    except (HTTPError, ConnectionError):
33
        print("[x] Invalid URL")
34
        exit(1)
35

36

37
def Download_vid():
38

39
    # Validates Link and download Video
40
    global Url_Val
41
    url = Url_Val.get()
42

43
    Status["text"] = "Downloading"
44
    Status["fg"] = "green"
45

46
    # Validating Input
47

48
    if not "www.facebook.com" in url:
49
        Invalid_Url()
50
        return
51

52
    link = get_downloadlink(url)
53

54
    start_downloading()
55

56
    download_thread = VideoDownload(link)
57
    download_thread.start()
58
    monitor(download_thread)
59

60

61
def monitor(download_thread):
62
    """ Monitor the download thread """
63
    if download_thread.is_alive():
64

65
        try:
66
            bar["value"] = queue.get(0)
67
            ld_window.after(10, lambda: monitor(download_thread))
68
        except Empty:
69
            pass
70

71

72
class VideoDownload(Thread):
73

74
    def __init__(self, url):
75
        super().__init__()
76

77
        self.url = url
78

79
    def run(self):
80
        """ download video"""
81

82
        # save the picture to a file
83
        block_size = 1024  # 1kB
84
        r = get(self.url, stream=True)
85
        total_size = int(r.headers.get("content-length"))
86

87
        with open('video.mp4', 'wb') as file:
88
            totaldata = 0
89
            for data in r.iter_content(block_size):
90
                totaldata += len(data)
91
                per_downloaded = totaldata*100/total_size
92
                queue.put(per_downloaded)
93
                bar['value'] = per_downloaded
94
                file.write(data)
95
                time.sleep(0.01)
96
            file.close()
97
            print("Download Finished")
98

99
        print("Download Complete !!!")
100
        Status["text"] = "Finished!!"
101
        Status["fg"] = "green"
102

103

104
# start download
105
def start_downloading():
106
    bar["value"] = 0
107

108
# GUI
109

110

111
ld_window = tk.Tk()
112
ld_window.title("Facebook Video Downloader")
113
ld_window.geometry("400x300")
114

115
# Label for URL Input
116
input_label = tk.Label(ld_window, text="Enter Facebook Video URL:")
117
input_label.pack()
118

119
# Input of URL
120
Url_Val = tk.StringVar()
121
Url_Input = tk.Entry(ld_window, textvariable=Url_Val, font=("Calibri", 9))
122
Url_Input.place(x=25, y=50, width=350)
123

124
# Button for Download
125
Download_button = tk.Button(ld_window, text="Download", font=(
126
    "Calibri", 9), command=Download_vid)
127
Download_button.place(x=100, y=100, width=200)
128

129
# Progress Bar
130
bar = Progressbar(ld_window, length=350,
131
                  style='grey.Horizontal.TProgressbar', mode='determinate')
132
bar.place(y=200, width=350, x=25)
133

134
queue = queue.Queue()
135
# Text for Status of Downloading
136
Status = tk.Label(ld_window, text="Hello!! :D", fg="blue", font=(
137
    "Calibri", 9), bd=1, relief=tk.SUNKEN, anchor=tk.W, padx=3)
138
Status.pack(side=tk.BOTTOM, fill=tk.X)
139

140
ld_window.mainloop()
141

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.