From a4aa383119d18ab82293686d52364f228ad0c18f Mon Sep 17 00:00:00 2001
From: tholimet <tholimet@localhost>
Date: Mon, 4 Mar 2024 15:34:33 +0100
Subject: [PATCH] =?UTF-8?q?Transf=C3=A9rer=20les=20fichiers=20vers=20'ScdL?=
 =?UTF-8?q?iv'?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 ScdLiv/main.py         | 264 +++++++++++++++++++++++++++++++++++++++++
 ScdLiv/mysqlco.py      | 108 +++++++++++++++++
 ScdLiv/obs_project.sql | 129 ++++++++++++++++++++
 3 files changed, 501 insertions(+)
 create mode 100644 ScdLiv/main.py
 create mode 100644 ScdLiv/mysqlco.py
 create mode 100644 ScdLiv/obs_project.sql

diff --git a/ScdLiv/main.py b/ScdLiv/main.py
new file mode 100644
index 0000000..dbf3380
--- /dev/null
+++ b/ScdLiv/main.py
@@ -0,0 +1,264 @@
+from tkinter import *
+from tkinter import messagebox
+import mysql.connector
+from obswebsocket import obsws, requests
+from twitch.helix.api import TwitchHelix
+from twitchAPI.helper import first
+import asyncio
+import twitchAPI
+import webbrowser
+    
+class NouvelleFenetre:
+
+    oauth_authorization_url = f"https://id.twitch.tv/oauth2/authorize?client_id={'6h883my3p6ndqozotnl6nsbllyyr3h'}&redirect_uri={'http://localhost'}&response_type=code&scope={'user_read'}"
+    
+    # Fonction permettant de fermer la deuxième fenetre créee et la première fenetre de connexion de se réafficher tout en se déconnecctant d'OBS
+    def fermer_et_reafficher(self):
+        self.root.destroy()
+        self.ws.disconnect()
+        self.root.master.deiconify()
+
+    # Fonction permettant de récupérer la valeur de la clé twitch qui a été renseignée
+    def get_key_twitch(self):
+        self.twitch = self.entry_twitch.get()
+        print (self.twitch)
+
+    # Fonction permettant de récupérer la valeur de la clé youtube qui a été renseignée
+    def get_key_youtube(self):
+        self.youtube = self.entry_youtube.get()
+        print (self.youtube)
+
+    def set_key_twitch(self, username):
+        try:
+            # Paramètres du serveur
+            cnx = mysql.connector.connect(user='root', password='',
+                                        host='127.0.0.1',
+                                        database='obs_project')
+            cur = cnx.cursor()
+
+            # On lance une requête pour vérifier si l'utilisateur correspond à la base de données
+            query = "SELECT * FROM utilisateurs WHERE username = %s"
+            cur.execute(query, (username,))
+
+            # Renvoie la première ligne de la base de données qui correspond
+            user = cur.fetchone()
+
+            if user:
+                # Utilisateur trouvé, on met à jour la clé Twitch
+                new_twitch_key = self.entry_twitch.get()
+                update_query = "UPDATE twitch SET twitch_key = %s WHERE username = %s"
+                cur.execute(update_query, (new_twitch_key, username))
+                cnx.commit()
+                print(f"La clé a été mis à jour pour {username} avec la clé {new_twitch_key}")
+            else:
+                print(f"Utilisateur {username} non trouvée")
+
+        except mysql.connector.Error as err:
+            print(f"Erreur: {err}")
+            messagebox.showerror("Erreur", "Une erreur a eu lieu pour mettre à jour votre clé")
+
+        finally:
+            # On ferme le tout, la connexion etc...
+            cur.close()
+            cnx.close()
+
+    def set_key_youtube(self, username):
+        try:
+            # Paramètres du serveur
+            cnx = mysql.connector.connect(user='root', password='',
+                                        host='127.0.0.1',
+                                        database='obs_project')
+            cur = cnx.cursor()
+
+            # On lance une requête pour vérifier si l'utilisateur correspond à la base de données
+            query = "SELECT * FROM utilisateurs WHERE username = %s"
+            cur.execute(query, (username,))
+
+            # Renvoie la première ligne de la base de données qui correspond
+            user = cur.fetchone()
+
+            if user:
+                # Utilisateur trouvé, on met à jour la clé Twitch
+                new_youtube_key = self.entry_youtube.get()
+                update_query = "UPDATE youtube SET youtube_key = %s WHERE username = %s"
+                cur.execute(update_query, (new_youtube_key, username))
+                cnx.commit()
+                print(f"La clé a été mis à jour pour {username} avec la clé {new_youtube_key}")
+            else:
+                print(f"Utilisateur {username} non trouvée")
+
+        except mysql.connector.Error as err:
+            print(f"Erreur: {err}")
+            messagebox.showerror("Erreur", "Une erreur a eu lieu pour mettre à jour votre clé")
+
+        finally:
+            # On ferme le tout, la connexion etc...
+            cur.close()
+            cnx.close()
+
+    def get_twitch_key_from_database(self, username):
+        try:
+            # Paramètres du serveur
+            cnx = mysql.connector.connect(user='root', password='',
+                                        host='127.0.0.1',
+                                        database='obs_project')
+            cur = cnx.cursor()
+
+            # On lance une requête pour récupérer la clé Twitch de l'utilisateur
+            query = "SELECT twitch_key FROM twitch WHERE username = %s"
+            cur.execute(query, (username,))
+            twitch_key = cur.fetchone()
+
+            if twitch_key:
+                return twitch_key[0]
+            else:
+                print(f"Clé Twitch non trouvée pour l'utilisateur {username}")
+                return None
+
+        except mysql.connector.Error as err:
+            print(f"Erreur: {err}")
+            messagebox.showerror("Erreur", "Une erreur a eu lieu pour récupérer la clé Twitch")
+
+        finally:
+            # On ferme le tout, la connexion etc...
+            cur.close()
+            cnx.close()
+
+    # On configure OBS pour Twitch
+    def configure_obs_for_twitch(self, twitch_stream_key):
+        # Utilisez la clé Twitch pour configurer OBS
+        self.ws.call(requests.StartStreaming(stream=twitch_stream_key))
+
+    def boutondediffusiontwitch_callback(self):
+        # Avec la variable is_twitch_streaming passé à False au commencement, on vérifie son état pour diffuser ou stoper le streaming
+        if self.is_twitch_streaming:
+            self.ws.call(requests.StopStreaming())
+            self.is_twitch_streaming = False
+        else:
+            self.ws.call(requests.StartStreaming(stream= self.twitch_key_from_database))
+            self.is_twitch_streaming = True
+
+    client_id = '6h883my3p6ndqozotnl6nsbllyyr3h'
+    oauth_token ='r4l2v9bgvlb0uh6cqqgw9j85tlojvd'
+    login = 'iSeralestis'
+
+    async def get_twitch_user(self, client_id, oauth_token, login):
+        twitch = TwitchHelix(client_id, oauth_token)
+    
+        user = await first (twitch.get_users(login_names= login))
+    
+        return user
+        
+    async def initialize_twitch(self):
+        twitch_user = await self.get_twitch_user(self.client_id, self.oauth_token, self.login)
+        if twitch_user:
+            print("Twitch user found:")
+            print("ID:", twitch_user.id)
+            print("Username:", twitch_user.display_name)
+        else:
+            print("Twitch user not found.")
+      
+
+    # Création de la nouvelle fenetre une fois l'authentification faite
+    async def initialize_window(self, root, username, password):
+        self.root = Toplevel(root)
+        self.root.title("OBS Extension Multistreaming")
+        self.root.geometry("1920x1080")
+
+        self.lancer_auth_twitch()
+        await self.initialize_twitch()
+
+    def __init__(self, root, username, password):
+        asyncio.run(self.initialize_window(root, username, password))
+
+        self.root.grid_rowconfigure(0, weight=0)
+        self.root.grid_rowconfigure(1, weight=0)
+        self.root.grid_rowconfigure(2, weight=0)
+        self.root.grid_rowconfigure(3, weight=0)
+        self.root.grid_rowconfigure(4, weight=0)
+        self.root.grid_rowconfigure(5, weight=0)
+        self.root.grid_rowconfigure(6, weight=0)
+        self.root.grid_rowconfigure(7, weight=0)
+        self.root.grid_rowconfigure(8, weight=0)
+        self.root.grid_rowconfigure(9, weight=0)
+        self.root.grid_rowconfigure(10, weight=0)
+        self.root.grid_rowconfigure(11, weight=0)
+        self.root.grid_rowconfigure(12, weight=0)
+        self.root.grid_rowconfigure(13, weight=0)
+        self.root.grid_rowconfigure(14, weight=0)
+        self.root.grid_columnconfigure(0, weight=1)
+        self.root.grid_columnconfigure(1, weight=0)
+        self.root.grid_columnconfigure(2, weight=0)
+        self.root.grid_columnconfigure(3, weight=0)
+
+        # Créer un bouton pour lancer le processus d'authentification Twitch
+        bouton_auth_twitch = Button(self.root, text="Autoriser l'accès à Twitch", command=self.lancer_auth_twitch)
+        bouton_auth_twitch.grid(row=15, column=0)
+
+        # C'est mon id de ma chaine twitch identifiant Alexis
+        self.client_id = '6h883my3p6ndqozotnl6nsbllyyr3h'
+        self.oauth_token ='r4l2v9bgvlb0uh6cqqgw9j85tlojvd'
+        self.login = 'iSeralestis'
+
+        self.twitch_client = TwitchHelix(client_id = self.client_id, oauth_token = self.oauth_token)
+
+        # On récupère la clé Twitch depuis la base de données
+        self.twitch_key_from_database = self.get_twitch_key_from_database(username)
+
+
+        # Initialisez la connexion OBS WebSocket
+        self.ws = obsws("localhost", 4455, "MPcZLZfViZihHqmg")
+        self.ws.connect()
+
+        # Configurez les paramètres de diffusion pour Twitch (remplacez 'stream_key' par le nom correct de votre champ)
+        twitch_stream_key = self.get_twitch_key_from_database(username)  # Variable qui récupére la key
+        self.configure_obs_for_twitch(twitch_stream_key)
+
+        # On affiche bienvenue à la personne s'étant identifiée, en récupérant la variable lastname
+        label = Label(self.root, text=f"Bienvenue, {username}!")
+        label.grid(row = 0, column = 0)
+
+        label = Label(self.root, text = "Clé Twitch :")
+        label.grid(row = 2, column = 0)
+
+        self.entry_twitch = Entry(self.root)
+        self.entry_twitch.grid(row= 3, column = 0)
+
+
+        # On met un bouton de validation pour garder les valeurs qu'on a rentré précédement
+        boutonvalidation = Button(self.root, text="Envoyé", command= lambda : self.set_key_twitch(username))
+        boutonvalidation.grid(row = 4, column = 0)
+
+        # On met d'office cette variable à False pour dire qu'on ne stream pas au lancement de l'application
+        self.is_twitch_streaming = False
+
+        # On met un bouton de diffusion pour twitch
+        boutondediffusiontwitch = Button(self.root, text="Diffusion de Twitch On/Off", command=self.boutondediffusiontwitch_callback)
+        boutondediffusiontwitch.grid(row = 4, column = 3)
+
+        label = Label(self.root, text = "Clé Youtube :")
+        label.grid(row = 5, column = 0)
+
+        self.entry_youtube = Entry(self.root)
+        self.entry_youtube.grid(row = 6, column = 0)
+
+        # On met un bouton pour envoyer les valeurs remplies du dessus
+        boutonvalidation2 = Button(self.root, text="Envoyé", command= lambda :self.set_key_youtube(username))
+        boutonvalidation2.grid(row = 7, column = 0)
+
+        # On met un bouton de diffusion pour twitch
+        boutondediffusionyoutube = Button(self.root, text="Diffusion de YouTube On/Off")
+        boutondediffusionyoutube.grid(row = 7, column = 3)
+
+        # On met un boutton fermer, pour pouvoir fermer la page main, et repasser sur la fenetre de connexion
+        bouton_fermer = Button(self.root, text="Fermer", command=self.fermer_et_reafficher)
+        bouton_fermer.grid(row = 13, column = 0)
+
+    def lancer_auth_twitch(self):
+        # Ouvrir le lien dans le navigateur Web par défaut
+        webbrowser.open(self.oauth_authorization_url)
+
+        # Afficher un message indiquant que l'utilisateur doit autoriser l'accès à Twitch dans le navigateur
+        messagebox.showinfo("Authentification Twitch", "Veuillez autoriser l'accès à Twitch dans le navigateur Web qui s'est ouvert.")
+
+        
\ No newline at end of file
diff --git a/ScdLiv/mysqlco.py b/ScdLiv/mysqlco.py
new file mode 100644
index 0000000..fbd04c3
--- /dev/null
+++ b/ScdLiv/mysqlco.py
@@ -0,0 +1,108 @@
+from main import *
+from tkinter import *
+from tkinter import messagebox
+import mysql.connector
+    
+class Mysql:
+    # On initialise une première fenêtre d'identification et de mot de passe
+    def __init__(self, root):
+        self.root = root
+        self.root.title("Launcher OBS Extension Multistreaming")
+        self.root.geometry("400x300")
+        self.root.grid_rowconfigure(0, weight=1)
+        self.root.grid_rowconfigure(1, weight=1)
+        self.root.grid_rowconfigure(2, weight=1)
+        self.root.grid_rowconfigure(3, weight=1)
+        self.root.grid_columnconfigure(0, weight=1)
+        self.root.grid_columnconfigure(1, weight=0)
+        self.root.grid_columnconfigure(2, weight=0)
+        self.root.grid_columnconfigure(3, weight=0)
+
+    # On vérifie sur le serveur si l'identification correspond à des utilisateurs sur le serveur
+    def authenticate_user(self, username, password):
+        try:
+            # Paramètres du serveur
+            cnx = mysql.connector.connect(user='root', password='',
+                                          host='127.0.0.1',
+                                          database='obs_project')
+            cur = cnx.cursor()
+
+            # On lance une requête pour vérifier si le lastname et le service correspond à la base de donnée
+            query = "SELECT * FROM utilisateurs WHERE username = %s  AND password = %s"
+            cur.execute(query, (username, password))
+
+            # Renvoie la première ligne de la base de donnée qui correspond
+            user = cur.fetchone()
+
+            # Si c'est le cas, on affiche le message suivant et on ouvre une nouvelle fenêtre
+            if user:
+                messagebox.showinfo("Validé", "Authentification réussi")
+                self.ouvrir_nouvelle_fenetre(username, password)
+
+            # Sinon on affiche un message d'erreur
+            else:
+                messagebox.showerror("Erreur", "Authentification erroné")
+
+        # Message si une erreur innatendue
+        except mysql.connector.Error as err:
+            messagebox.showerror("Erreur", f"Erreur: {err}")
+
+        # On ferme le tout, la connexion etc...
+        finally:
+            cur.close()
+            cnx.close()
+
+    # On va initialiser une nouvelle fenêtre après la connexion tout en fermant la première
+    def ouvrir_nouvelle_fenetre(self, username, password):
+        if self.root.winfo_exists():  # Vérifie si la fenêtre principale existe toujours
+            self.root.withdraw()  # Fermer la fenêtre actuelle
+        NouvelleFenetre(self.root, username, password) # Création de la nouvelle fenêtre avec toutes les infos, utilitées etc...
+        
+            
+    # Lorsqu'on clique sur la case identifiant, le texte se supprime pour pouvoir taper le sien
+    def click_identifiant(self, event):
+        entry_identifiant.configure(state=NORMAL)
+        entry_identifiant.delete(0, END)
+        entry_identifiant.unbind('<Button-1>', self.click_identifiant)
+
+    # Lorsqu'on clique sur la case password, le texte se supprime pour pouvoir taper le sien
+    def click_pass(self, event):
+        entry_pass.configure(state=NORMAL)
+        entry_pass.delete(0, END)
+        entry_pass.unbind('<Button-1>', self.click_pass)
+
+    # On test voir si le username et le password que l'on récupére, correspond pour s'identifier
+    def msg_call_back(self):
+        username = entry_identifiant.get()
+        password = entry_pass.get()
+        self.authenticate_user(username, password)
+
+# Creation de la fenetre principale
+fenetre = Tk()
+obj = Mysql(fenetre)
+
+# Ajout des boutons sur la fenêtre
+label = Label(fenetre, text="Connexion")
+label.grid(row = 0, column= 0)
+
+# Entrée du champs identifiant
+entry_identifiant = Entry(fenetre)
+entry_identifiant.grid(row = 1, column=0)
+entry_identifiant.focus()
+entry_identifiant.insert(0, "Admin")
+
+entry_identifiant.bind('<Button-1>', obj.click_identifiant)
+
+# Entrée du champs password
+entry_pass = Entry(fenetre, show='*')
+entry_pass.grid(row = 2, column=0)
+entry_pass.insert(0, "Admin")
+
+entry_pass.bind('<Button-1>', obj.click_pass)
+
+# Bouton de connexion avec la fonction msg_call_back
+boutonconnexion = Button(fenetre, text="Connexion", command=obj.msg_call_back, activebackground = "green")
+boutonconnexion.grid(row = 3, column = 0)
+
+# Lancer l'application
+fenetre.mainloop()
diff --git a/ScdLiv/obs_project.sql b/ScdLiv/obs_project.sql
new file mode 100644
index 0000000..fa4b53c
--- /dev/null
+++ b/ScdLiv/obs_project.sql
@@ -0,0 +1,129 @@
+-- phpMyAdmin SQL Dump
+-- version 5.2.1
+-- https://www.phpmyadmin.net/
+--
+-- Hôte : 127.0.0.1
+-- Généré le : ven. 19 jan. 2024 à 18:36
+-- Version du serveur : 10.4.32-MariaDB
+-- Version de PHP : 8.2.12
+
+SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
+START TRANSACTION;
+SET time_zone = "+00:00";
+
+
+/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
+/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
+/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
+/*!40101 SET NAMES utf8mb4 */;
+
+--
+-- Base de données : `obs_project`
+--
+
+-- --------------------------------------------------------
+
+--
+-- Structure de la table `twitch`
+--
+
+CREATE TABLE `twitch` (
+  `id` int(255) NOT NULL,
+  `username` varchar(15) NOT NULL,
+  `twitch_key` varchar(100) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+--
+-- Déchargement des données de la table `twitch`
+--
+
+INSERT INTO `twitch` (`id`, `username`, `twitch_key`) VALUES
+(1, 'Admin', '');
+
+-- --------------------------------------------------------
+
+--
+-- Structure de la table `utilisateurs`
+--
+
+CREATE TABLE `utilisateurs` (
+  `id` int(255) NOT NULL,
+  `username` varchar(15) NOT NULL,
+  `password` varchar(20) NOT NULL,
+  `mail` varchar(30) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+--
+-- Déchargement des données de la table `utilisateurs`
+--
+
+INSERT INTO `utilisateurs` (`id`, `username`, `password`, `mail`) VALUES
+(1, 'admin', 'admin', 'admin@gmail.com');
+
+-- --------------------------------------------------------
+
+--
+-- Structure de la table `youtube`
+--
+
+CREATE TABLE `youtube` (
+  `id` int(255) NOT NULL,
+  `username` varchar(15) NOT NULL,
+  `youtube_key` varchar(100) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+
+--
+-- Déchargement des données de la table `youtube`
+--
+
+INSERT INTO `youtube` (`id`, `username`, `youtube_key`) VALUES
+(1, 'Admin', 'gdrthdrtbdfgbdd84');
+
+--
+-- Index pour les tables déchargées
+--
+
+--
+-- Index pour la table `twitch`
+--
+ALTER TABLE `twitch`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- Index pour la table `utilisateurs`
+--
+ALTER TABLE `utilisateurs`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- Index pour la table `youtube`
+--
+ALTER TABLE `youtube`
+  ADD PRIMARY KEY (`id`);
+
+--
+-- AUTO_INCREMENT pour les tables déchargées
+--
+
+--
+-- AUTO_INCREMENT pour la table `twitch`
+--
+ALTER TABLE `twitch`
+  MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
+
+--
+-- AUTO_INCREMENT pour la table `utilisateurs`
+--
+ALTER TABLE `utilisateurs`
+  MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
+
+--
+-- AUTO_INCREMENT pour la table `youtube`
+--
+ALTER TABLE `youtube`
+  MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
+COMMIT;
+
+/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
+/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
+/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;