From 1761f8f38f5725db75840f242e507d4168a557f1 Mon Sep 17 00:00:00 2001
From: Cristiano Pires <cpires@labsxd.com>
Date: Thu, 31 Aug 2023 15:27:01 +0100
Subject: [PATCH] fixed possible wrongly typed youtube channels on channel feed

---
 controller/api.js      |  21 ++++++
 lib.js                 |   5 ++
 public/js/dashboard.js |  26 ++++++-
 routes/routes.js       |   1 +
 test.js                | 164 +----------------------------------------
 5 files changed, 53 insertions(+), 164 deletions(-)

diff --git a/controller/api.js b/controller/api.js
index 96da790..012933a 100644
--- a/controller/api.js
+++ b/controller/api.js
@@ -324,6 +324,27 @@ exports.getChannelName = async (req,res)=>
     res.json(payload);
     
 }
+exports.checkChannel = async (req, res)=>
+{
+    var isValid = await fetch('https://www.youtube.com/'+req.headers.id,
+    {
+        method: "GET",
+        mode: "cors", 
+    })
+    .then(response=>
+        {
+            if(response.ok) return response.text();
+        })
+    .then(data=>
+        {
+            return data ? true :false
+        })
+    .catch(error=>
+        {
+            return error;
+        });
+    res.json(isValid)
+}
 
 exports.addFeed = (bot)=>
 {
diff --git a/lib.js b/lib.js
index 0003341..d87c662 100644
--- a/lib.js
+++ b/lib.js
@@ -175,6 +175,8 @@ class _Client extends Client
         for(var feed of feeds)
         {
             (async (feed)=>{
+                if(!feed.YTChannelId) return
+                if(feed.YTChannelId=='false') return
                 var res = await fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${feed.YTChannelId}`)
                                 .then(handleResponse)
                                 .then(handleData)
@@ -211,6 +213,7 @@ class _Client extends Client
                 if(!res) return false;
                 const channel = this.channels.cache.get(feed.ChannelId);
                 if(!channel) return false;
+                // console.log('Res from',feed,res)
                 var aux = res;
                 const lastSentMessage= await channel.messages.fetch().then(res=>
                     {
@@ -222,6 +225,7 @@ class _Client extends Client
                                 {
                                     var fields = item[1].embeds[0].fields.filter(x=>x.name === 'PublishedTimeStamp');
                                     var isFeed = fields.length>0;
+                                    if(!aux.author) return null;
                                     if(isFeed && item[1].embeds[0].title == aux.author.name) return item[1].embeds[0];
                                 }
                             }
@@ -236,6 +240,7 @@ class _Client extends Client
         }
         function sendMessage(res, feed, channel)
         {
+            console.log('Lib, res on sendMessage method', res)
             const embed = new EmbedBuilder()
             embed.setFooter({text:'Rem-chan on ', iconURL:"https://i.imgur.com/g6FSNhL.png"})
             embed.setAuthor({name:"Rem-chan", iconURL:"https://i.imgur.com/g6FSNhL.png",url:'https://rem.wordfights.com/addtodiscord'}); 
diff --git a/public/js/dashboard.js b/public/js/dashboard.js
index 1a639ea..6ed17ae 100644
--- a/public/js/dashboard.js
+++ b/public/js/dashboard.js
@@ -503,13 +503,15 @@ function deleteFeed(element)
     .catch(console.error);
 }
 
-function _updateFeed(element)
+async function _updateFeed(element)
 {
     feedID = document.getElementById('ChannelName').classList.value;
     var gid = document.getElementsByClassName('guildname')[0].id;
     var DCchannelID = document.getElementById('DCchannelID').value;
     var YTchannelID = document.getElementById('YTchannelID').value;
     var CostumMessageI = document.getElementById('CostumMessageI').value;
+    var YTValid = await channelCheck(YTchannelID); 
+    if(!YTValid) return document.getElementById('YTchannelID').style = "border: 2px solid red" //! COMPLETE THIS WITH A ERROR POPUP 
     fetch(`${window.location.origin}/api/addFeed`, 
     {
         method: "POST",
@@ -530,3 +532,25 @@ function _updateFeed(element)
 
     
 }
+async function channelCheck(yt)
+{
+    var res =  await fetch(`${window.location.origin}/api/checkChannel`, 
+    {
+        method: "GET",
+        mode: "cors", 
+        headers: {id:yt},
+    })
+    .then(response=>
+        {
+            if(response.ok) return response.text();
+        })
+    .then(data=>
+        {
+            return data.replaceAll('"','')
+        })
+    .catch(error=>
+        {
+            return error;
+        });
+    return res=='true'?true:false;
+}
\ No newline at end of file
diff --git a/routes/routes.js b/routes/routes.js
index 646a67f..3098050 100644
--- a/routes/routes.js
+++ b/routes/routes.js
@@ -16,6 +16,7 @@ module.exports = (io, bot)=>
     router.route('/api/updateFeed').post(api.addFeed(bot));
     router.route('/api/getMessage').get(api.getMessage(bot));
     router.route('/api/getChannelName').get(api.getChannelName);
+    router.route('/api/checkChannel').get(api.checkChannel);
     router.route('/api/updateRule').post(api.updateRule(bot));
     router.route('/api/deleteRule').post(api.deleteRule);
     router.route('/dashboard').get(dash.get(io))
diff --git a/test.js b/test.js
index beca58c..d148bc8 100644
--- a/test.js
+++ b/test.js
@@ -1,164 +1,2 @@
-// works on script of a page
 
-// async function getGameData()
-// {
-//     return await fetch('https://127.0.0.1:2999/GetLiveclientdataAllgamedata',
-//     {
-//         method:"GET",
-//         mode:"cors",
-//         headers:
-//         {
-//             "Access-Control-Allow-Methods": "*"
-//         }
-//     }).then(handleRes).catch(handleFailure)
-//     async function handleRes(res)
-//     {
-//         console.log(res)
-//         return await res.json();
-        
-//     }
-//     function handleFailure()
-//     {
-//         return 'Failed to fetch'
-//     }
-// }
-
-
-// setInterval(async () => {
-//     console.log(await getGameData())
-// }, 1000);
-
-
-// var skinURL = `http://ddragon.leagueoflegends.com/cdn/img/champion/splash/${championName}_${skinID}.jpg`;
-var coiso = [
-{
-    "championName": "Caitlyn",
-    "scores": {
-        "creepScore": 100,
-        "deaths": 0,
-        "kills": 8,
-    },
-    "skinID": 20,
-    "summonerName": "hc12",
-    "summonerSpells": {
-        "summonerSpellOne": {
-            "displayName": "Barrier",
-        },
-        "summonerSpellTwo": {
-            "displayName": "Flash",
-        }
-    },
-    "team": "ORDER"
-},
-{
-    "championName": "Lux",
-    "scores": {
-        "assists": 0,
-        "creepScore": 10,
-        "deaths": 8,
-        "kills": 0,
-    },
-    "skinID": 0,
-    "summonerName": "Lux Bot",
-    "summonerSpells": {
-        "summonerSpellOne": {
-            "displayName": "Heal",
-        },
-        "summonerSpellTwo": {
-            "displayName": "Exhaust",
-        }
-    },
-    "team": "CHAOS"
-}
-]
-var events =
-[
-    [
-        {
-            "EventID": 0,
-            "EventName": "GameStart",
-            "EventTime": 0.04342550039291382
-        },
-        {
-            "EventID": 1,
-            "EventName": "MinionsSpawning",
-            "EventTime": 65.07691955566406
-        },
-        {
-            "EventID": 3,
-            "EventName": "FirstBlood",
-            "EventTime": 209.65553283691406,
-            "Recipient": "hc12"
-        },
-               {
-            "EventID": 16,
-            "EventName": "FirstBrick",
-            "EventTime": 605.8714599609375,
-            "KillerName": "hc12"
-        }
-    ]
-]
-
-var id = 'coiso'
-var a = 
-{
-    coiso:
-    [
-        {
-            gId:'coiso'
-        },
-        {
-            gId: 'coisa'
-        }
-    ]
-}
-var replacement = {gId:'coisada'}
-const index = a.coiso.findIndex(x=>x.gId=id);
-a.coiso[index] = replacement;
-console.log(a.coiso)
-
-
-var b = {
-    _id: new ObjectId("642359f907f5cbd1bfba7646"),
-    Players: [
-      {
-        Name: 1,
-        Points: 2,
-        PlayedPoints: 0,
-        Kills: 2,
-        Deaths: 0,
-        CreepScore: 0,
-        PointsPlayed: NaN
-      },
-      {
-        Name: 'Ezreal Bot',
-        Points: 0,
-        PlayedPoints: 0,
-        Kills: 0,
-        Deaths: 0,
-        CreepScore: 0
-      }
-    ],
-    Games: [
-      {
-        _id: new ObjectId("642359f907f5cbd1bfba7642"),
-        Winner: 'hc12',
-        WinCondition: 'FirstBlood',
-        Played: true,
-        PlayedTimeStamp: '1680125543862',
-        __v: 0
-      },
-      {
-        PA: [Object],
-        PB: [Object],
-        Winner: '',
-        WinCondition: '',
-        Played: false,
-        PlayedTimeStamp: '',
-        gId: '642359f907f5cbd1bfba7642'
-      }
-    ],
-    Name: 'test',
-    Owner: '186540961650835456',
-    __v: 0
-  }
\ No newline at end of file
+