Najeebsk

IPTV-VIDEO-PLAYER2.0.pyw

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