Najeebsk

IPTV-M3U-YOUTUBE-PREVIEW.pyw

May 26th, 2024
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.95 KB | None | 0 0
  1. import os
  2. import tkinter as tk
  3. from tkinter import ttk, filedialog, messagebox
  4. import requests
  5. import subprocess
  6. import threading
  7. import time
  8. import vlc
  9. import chardet
  10. from youtube_dl import YoutubeDL  # or use yt-dlp
  11. from apiclient.discovery import build
  12.  
  13. # Constants
  14. YOUTUBE_API_KEY = 'AIzaSyCzS7PGThVFxD83UFbfU5DOSZBMTxNpEeA'
  15. YOUTUBE_API_SERVICE_NAME = 'youtube'
  16. YOUTUBE_API_VERSION = 'v3'
  17.  
  18. # Functions for the main functionalities
  19. def search_channels():
  20.     search_term = url_entry.get().lower()
  21.     if search_term.startswith("http"):
  22.         search_by_url(search_term)
  23.     else:
  24.         search_by_path_or_category(search_term)
  25.  
  26. def search_by_url(url):
  27.     try:
  28.         if os.path.exists(url):
  29.             with open(url, 'r', encoding='utf-8') as file:
  30.                 m3u_data = file.readlines()
  31.             process_m3u_data(m3u_data)
  32.         else:
  33.             response = requests.get(url)
  34.             if response.status_code == 200:
  35.                 try:
  36.                     m3u_data = response.text.split('\n')
  37.                 except UnicodeDecodeError:
  38.                     m3u_data = response.content.decode('ISO-8859-1').split('\n')
  39.                 process_m3u_data(m3u_data)
  40.             else:
  41.                 result_text.insert(tk.END, f"Error: Failed to fetch channel data. Status Code: {response.status_code}\n")
  42.     except Exception as e:
  43.         result_text.insert(tk.END, f"Error: {str(e)}\n")
  44.  
  45. def search_by_path_or_category(path):
  46.     try:
  47.         if os.path.exists(path):
  48.             try:
  49.                 with open(path, 'r', encoding='utf-8') as file:
  50.                     m3u_data = file.readlines()
  51.             except UnicodeDecodeError:
  52.                 with open(path, 'r', encoding='ISO-8859-1') as file:
  53.                     m3u_data = file.readlines()
  54.             process_m3u_data(m3u_data)
  55.         else:
  56.             selected_category = category_var.get()
  57.             if selected_category in category_urls:
  58.                 category_url = category_urls[selected_category]
  59.                 if category_url:
  60.                     search_by_url(category_url)
  61.                 else:
  62.                     result_text.insert(tk.END, f"Error: Category URL is not provided for {selected_category}\n")
  63.             else:
  64.                 result_text.insert(tk.END, f"Error: Category '{selected_category}' not found\n")
  65.     except Exception as e:
  66.         result_text.insert(tk.END, f"Error: {str(e)}\n")
  67.  
  68. def process_m3u_data(m3u_data):
  69.     result_text.delete(0, tk.END)
  70.     global channels_info
  71.     channels_info = {}
  72.     channel_name = None
  73.     for line in m3u_data:
  74.         if line.startswith('#EXTINF:'):
  75.             channel_name = line.split(',')[-1].strip()
  76.         elif line.startswith('http') and channel_name:
  77.             channels_info[channel_name] = line.strip()
  78.             result_text.insert(tk.END, channel_name)
  79.             channel_name = None
  80.  
  81. def search_youtube():
  82.     query = search_entry.get()
  83.     youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=YOUTUBE_API_KEY)
  84.     search_response = youtube.search().list(q=query, part='id,snippet', maxResults=10).execute()
  85.     result_text.delete(0, tk.END)
  86.     global channels_info
  87.     channels_info = {}
  88.     for item in search_response['items']:
  89.         if item['id']['kind'] == 'youtube#video':
  90.             video_title = item['snippet']['title']
  91.             video_id = item['id']['videoId']
  92.             video_url = f"https://www.youtube.com/watch?v={video_id}"
  93.             channels_info[video_title] = video_url
  94.             result_text.insert(tk.END, video_title)
  95.             print("Searching YouTube for:", query)
  96.  
  97. def play_selected_channel(event):
  98.     try:
  99.         selected_channel = result_text.get(tk.ACTIVE)
  100.         if selected_channel in channels_info:
  101.             url = channels_info[selected_channel]
  102.             if 'youtube.com' in url or 'youtu.be' in url:
  103.                 download_and_play_youtube(url)
  104.             elif os.path.exists(url):
  105.                 subprocess.Popen([r"C:\Program Files\VideoLAN\VLC\vlc.exe", url])
  106.     except (tk.TclError, KeyError):
  107.         pass
  108.  
  109. def download_and_play_youtube(url):
  110.     ydl_opts = {'format': 'best'}
  111.     with YoutubeDL(ydl_opts) as ydl:
  112.         info_dict = ydl.extract_info(url, download=False)
  113.         video_url = info_dict['url']
  114.         subprocess.Popen([r"C:\Program Files\VideoLAN\VLC\vlc.exe", video_url])
  115.  
  116. def check_links():
  117.     global working_links
  118.     working_links = {}
  119.     for channel_name, url in channels_info.items():
  120.         try:
  121.             response = requests.get(url)
  122.             if response.status_code == 200:
  123.                 working_links[channel_name] = url
  124.         except requests.RequestException:
  125.             pass
  126.  
  127.     result_text.delete(0, tk.END)
  128.     for channel_name, url in working_links.items():
  129.         result_text.insert(tk.END, f"{channel_name}: {url}\n")
  130.  
  131. def save_working_links():
  132.     with open("working_channels.m3u", "w", encoding="utf-8") as f:
  133.         for channel_name, url in working_links.items():
  134.             f.write(f"#EXTINF:-1,{channel_name}\n{url}\n")
  135.  
  136. def filter_channels(event=None):
  137.     keyword = search_entry.get().lower()
  138.     result_text.delete(0, tk.END)
  139.     for channel_name, url in channels_info.items():
  140.         if keyword in channel_name.lower():
  141.             result_text.insert(tk.END, channel_name)
  142.  
  143. def browse_file():
  144.     file_path = filedialog.askopenfilename(filetypes=[("M3U Files", "*.m3u"), ("All Files", "*.*")])
  145.     if file_path:
  146.         url_entry.delete(0, tk.END)
  147.         url_entry.insert(0, file_path)
  148.  
  149. def preview_selected_link():
  150.     def play_media():
  151.         selected_channel = result_text.get(tk.ACTIVE).strip()
  152.         if selected_channel in channels_info:
  153.             url = channels_info[selected_channel]
  154.             media = instance.media_new(url)
  155.             player.set_media(media)
  156.             player.play()
  157.             update_slider()
  158.         else:
  159.             messagebox.showerror("Error", "Selected text is not a valid URL.")
  160.  
  161.     threading.Thread(target=play_media).start()
  162.  
  163. def stop_preview():
  164.     player.stop()
  165.     preview_frame.pack_forget()
  166.  
  167. def capture_video():
  168.     try:
  169.         selected_channel = result_text.get(tk.ACTIVE).strip()
  170.         if selected_channel in channels_info:
  171.             url = channels_info[selected_channel]
  172.             filename = filedialog.asksaveasfilename(defaultextension=".mp4", filetypes=[("MP4 files", "*.mp4")])
  173.             if filename:
  174.                 command = ['ffmpeg', '-y', '-i', url, '-t', '03:55:00', '-c', 'copy', filename]
  175.                 threading.Thread(target=lambda: subprocess.run(command)).start()
  176.                 messagebox.showinfo("Capturing", f"Capturing 03:55 minutes of video to {filename}")
  177.         else:
  178.             messagebox.showerror("Error", "Selected text is not a valid URL.")
  179.     except tk.TclError:
  180.         messagebox.showerror("Error", "No text selected.")
  181.  
  182. def record_audio():
  183.     try:
  184.         selected_channel = result_text.get(tk.ACTIVE).strip()
  185.         if selected_channel in channels_info:
  186.             url = channels_info[selected_channel]
  187.             filename = filedialog.asksaveasfilename(defaultextension=".mp3", filetypes=[("MP3 files", "*.mp3")])
  188.             if filename:
  189.                 command = ['ffmpeg', '-y', '-i', url, '-f', 'mp3', '-c:a', 'libmp3lame', filename]
  190.                 global process
  191.                 process = subprocess.Popen(command)
  192.                 messagebox.showinfo("Recording", f"Recording audio to {filename}")
  193.         else:
  194.             messagebox.showerror("Error", "Selected text is not a valid URL.")
  195.     except tk.TclError:
  196.         messagebox.showerror("Error", "No text selected.")
  197.  
  198. def stop_recording():
  199.     if process:
  200.         process.terminate()
  201.         messagebox.showinfo("Stopped", "Recording stopped")
  202.  
  203. def capture_screenshots():
  204.     if player.get_media():
  205.         filename_base = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png")])
  206.         if filename_base:
  207.             interval = 5
  208.             num_screenshots = 5
  209.             for i in range(num_screenshots):
  210.                 time.sleep(interval)
  211.                 filename = f"{filename_base}_{i+1}.png"
  212.                 player.video_take_snapshot(0, filename, 0, 0)
  213.                 messagebox.showinfo("Captured", f"Screenshot {i+1} saved to {filename}")
  214.  
  215. def update_slider():
  216.     if player.get_media():
  217.         length = player.get_length() / 1000
  218.         position = player.get_time() / 1000
  219.         if length > 0:
  220.             slider.set(position / length * 100)
  221.         root.after(1000, update_slider)
  222.  
  223. def set_position(event):
  224.     if player.get_media():
  225.         length = player.get_length() / 1000
  226.         player.set_time(int(slider.get() / 100 * length * 1000))
  227.  
  228. def on_configure(event):
  229.     if event.widget == canvas:
  230.         player.set_hwnd(canvas.winfo_id())
  231.  
  232. #def toggle_mute():
  233.     #is_muted = player.audio_get_mute()
  234.     #player.audio_set_mute(not is_muted)
  235.  
  236. def download_and_play_youtube(url):
  237.     ydl_opts = {'format': 'best', 'extract_flat': True}
  238.     with YoutubeDL(ydl_opts) as ydl:
  239.         info_dict = ydl.extract_info(url, download=False)
  240.         video_url = info_dict.get('url')
  241.         if video_url:
  242.             subprocess.Popen([r"C:\Program Files\VideoLAN\VLC\vlc.exe", video_url])
  243.         else:
  244.             messagebox.showerror("Error", "Failed to extract video URL.")
  245.  
  246. def set_volume(value):
  247.         player.audio_set_volume(int(value))            
  248.    
  249.  
  250. # GUI setup
  251. root = tk.Tk()
  252. root.title("Najeeb IPTV Channel Link Checker")
  253. root.configure(bg="#4a4a4a")
  254.  
  255. url_frame = tk.Frame(root, bg="#4a4a4a")
  256. url_frame.pack(pady=10)
  257.  
  258. url_label = tk.Label(url_frame, text="Enter URL or local path or select category:", bg="#4a4a4a", fg="white")
  259. url_label.pack(side=tk.LEFT, padx=5)
  260.  
  261. url_entry = tk.Entry(url_frame, width=80)
  262. url_entry.pack(side=tk.LEFT, padx=5)
  263.  
  264. search_button = tk.Button(url_frame, text="Search", command=search_channels, bg="#FFA500", fg="white")
  265. search_button.pack(side=tk.LEFT, padx=5)
  266.  
  267. result_label = tk.Label(root, text="Check and save working URLs in M3U file:", bg="#4a4a4a", fg="white")
  268. result_label.pack()
  269.  
  270. search_frame = tk.Frame(root, bg="#4a4a4a")
  271. search_frame.pack()
  272.  
  273. search_label = tk.Label(search_frame, text="Search Channel Name:", bg="#4a4a4a", fg="white")
  274. search_label.pack(side=tk.LEFT, padx=5)
  275.  
  276. search_entry = tk.Entry(search_frame, width=105)
  277. search_entry.pack(side=tk.LEFT, padx=5)
  278. search_entry.bind('<KeyRelease>', filter_channels)
  279.  
  280. scrollbar = tk.Scrollbar(root, orient=tk.VERTICAL)
  281. scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  282.  
  283. result_text = tk.Listbox(root, height=12, width=160, yscrollcommand=scrollbar.set)
  284. result_text.pack()
  285.  
  286. scrollbar.config(command=result_text.yview)
  287. result_text.bind("<Double-1>", play_selected_channel)
  288.  
  289. check_button = tk.Button(root, text="Check Links", command=check_links, bg="#008000", fg="white")
  290. check_button.pack(side=tk.RIGHT, padx=5)
  291.  
  292. save_button = tk.Button(root, text="Save Working Links", command=save_working_links, bg="#FF0000", fg="white")
  293. save_button.pack(side=tk.LEFT, padx=5)
  294.  
  295. category_urls = {
  296.     "NAJEEB-IPTV": "",
  297.     "ALL-INDEX": "https://iptv-org.github.io/iptv/index.m3u",
  298.     "CATEGORY": "https://iptv-org.github.io/iptv/index.category.m3u",
  299.     "LANGUAGE": "https://iptv-org.github.io/iptv/index.language.m3u",
  300.     "REGION": "https://iptv-org.github.io/iptv/index.region.m3u",
  301.     "Brazil": "https://iptv-org.github.io/iptv/countries/br.m3u",
  302.     "France": "https://iptv-org.github.io/iptv/countries/fr.m3u",
  303.     "India": "https://iptv-org.github.io/iptv/countries/in.m3u",
  304.     "Italy": "https://iptv-org.github.io/iptv/countries/it.m3u",
  305.     "Pakistan": "https://iptv-org.github.io/iptv/countries/pk.m3u",
  306.     "Spain": "https://iptv-org.github.io/iptv/countries/es.m3u",
  307.     "Thailand": "https://iptv-org.github.io/iptv/countries/th.m3u",
  308.     "UK": "https://iptv-org.github.io/iptv/countries/uk.m3u",
  309.     "USA": "https://iptv-org.github.io/iptv/countries/us.m3u",
  310.     "Classic": "https://iptv-org.github.io/iptv/categories/classic.m3u",
  311.     "Comedy": "https://iptv-org.github.io/iptv/categories/comedy.m3u",
  312.     "Documentary": "https://iptv-org.github.io/iptv/categories/documentary.m3u",
  313.     "Entertainment": "https://iptv-org.github.io/iptv/categories/entertainment.m3u",
  314.     "Kids": "https://iptv-org.github.io/iptv/categories/kids.m3u",
  315.     "Movies": "https://iptv-org.github.io/iptv/categories/movies.m3u",
  316.     "Music": "https://iptv-org.github.io/iptv/categories/music.m3u",
  317.     "News": "https://iptv-org.github.io/iptv/categories/news.m3u",
  318.     "Science": "https://iptv-org.github.io/iptv/categories/science.m3u",
  319.     "Sports": "https://iptv-org.github.io/iptv/categories/sports.m3u",
  320.     "Travel": "https://iptv-org.github.io/iptv/categories/travel.m3u",
  321.     "PLAYLIST-1": "C:/Users/Najeeb/Desktop/IPTV/PL1.m3u",
  322.     "PLAYLIST-2": "C:/Users/Najeeb/Desktop/IPTV/PL2.m3u",
  323.     "PLAYLIST-3": "C:/Users/Najeeb/Desktop/IPTV/PL3.m3u",
  324.     "PLAYLIST-4": "C:/Users/Najeeb/Desktop/IPTV/PL4.m3u",
  325.     "PLAYLIST-5": "C:/Users/Najeeb/Desktop/IPTV/PL5.m3u",
  326.     "PLAYLIST-6": "C:/Users/Najeeb/Desktop/IPTV/PL6.m3u",
  327.     "PLAYLIST-R": "C:/Users/Najeeb/Desktop/IPTV/PLR.m3u",
  328.     "PLAYLIST-X": "C:/Users/Najeeb/Desktop/IPTV/PLX.m3u",
  329. }
  330.  
  331. category_var = tk.StringVar(root)
  332. category_var.set("NAJEEB-IPTV")
  333. category_dropdown = ttk.OptionMenu(root, category_var, *category_urls.keys())
  334. category_dropdown.pack(pady=10)
  335.  
  336.  
  337. button_frame = tk.Frame(root, bg="#4a4a4a")
  338. button_frame.pack()
  339.  
  340. volume_scale = tk.Scale(button_frame, from_=0, to=100, orient="horizontal", command=set_volume, label="Volume", bg="#4a4a4a", fg="white")
  341. volume_scale.set(50)  # Set the initial volume to 50%
  342. volume_scale.pack(side="left", fill="x", padx=5, pady=5)
  343.  
  344. browse_button = tk.Button(button_frame, text="Browse Playlist", command=browse_file, bg="#5a5a5a", fg="white")
  345. browse_button.pack(side=tk.LEFT, padx=5)
  346.  
  347. preview_button = tk.Button(button_frame, text="Preview", command=preview_selected_link, bg="#5a5a5a", fg="white")
  348. preview_button.pack(side=tk.LEFT, padx=5)
  349.  
  350. capture_video_button = tk.Button(button_frame, text="Capture Video", command=capture_video, bg="#5a5a5a", fg="white")
  351. capture_video_button.pack(side=tk.LEFT, padx=5)
  352.  
  353. record_button = tk.Button(button_frame, text="Record Audio", command=record_audio, bg="#5a5a5a", fg="white")
  354. record_button.pack(side=tk.LEFT, padx=5)
  355.  
  356. stop_button = tk.Button(button_frame, text="Stop Recording", command=stop_recording, bg="#5a5a5a", fg="white")
  357. stop_button.pack(side=tk.LEFT, padx=5)
  358.  
  359. capture_screenshot_button = tk.Button(button_frame, text="Capture Screenshots", command=capture_screenshots, bg="#5a5a5a", fg="white")
  360. capture_screenshot_button.pack(side=tk.LEFT, padx=5)
  361.  
  362. #toggle_mute_button = tk.Button(button_frame, text="Toggle Audio Mute", command=toggle_mute, bg="#5a5a5a", fg="white")
  363. #toggle_mute_button.pack(side=tk.LEFT, padx=5)
  364.  
  365. stop_button = tk.Button(button_frame, text="Close Preview", command=stop_preview, bg="#5a5a5a", fg="white")
  366. stop_button.pack(side=tk.LEFT, padx=5)
  367.  
  368. # YouTube search frame
  369. youtube_frame = tk.Frame(root, bg="#4a4a4a")
  370. youtube_frame.pack(pady=10)
  371.  
  372. search_label = tk.Label(youtube_frame, text="Enter search query:", bg="#4a4a4a", fg="white")
  373. search_label.pack(side=tk.LEFT, padx=5)
  374.  
  375. search_entry = tk.Entry(youtube_frame, width=80)
  376. search_entry.pack(side=tk.LEFT, padx=5)
  377.  
  378. search_button = tk.Button(youtube_frame, text="Search", command=search_youtube, bg="#FFA500", fg="white")
  379. search_button.pack(side=tk.LEFT, padx=5)
  380.  
  381. preview_frame = tk.Frame(root, bg="#4a4a4a", height=200)
  382. preview_frame.pack(fill="both", expand=True)
  383. preview_frame.pack_forget()
  384.  
  385. canvas = tk.Canvas(preview_frame, bg="#4a4a4a")
  386. canvas.pack(fill="both", expand=True)
  387. canvas.bind("<Configure>", on_configure)
  388.  
  389. slider = tk.Scale(preview_frame, from_=0, to=100, orient=tk.HORIZONTAL, command=set_position, bg="#4a4a4a", fg="white")
  390. slider.pack(fill="x", padx=5)
  391.  
  392. instance = vlc.Instance()
  393. player = instance.media_player_new()
  394.  
  395. channels_info = {}
  396. working_links = {}
  397.  
  398. root.mainloop()
  399.  
Add Comment
Please, Sign In to add comment