"Rewritting" WebNowPlaying

Status
Not open for further replies.

SirZontax

New member
Joined
May 9, 2020
Messages
4
Programming Experience
1-3
Hey,

I started to edit the code of the Rainmeter Plugin "WebNowPlaying" because I want it to write the current song infos to a file. It gets the song information from its WebExtension which uses a WebSocket. I, obviously, copy pasted the code and tried to implement it into the Form, so you press a button and it tells you your current song title.
Now my problem: I tried now for 4 hours to make it but the messagebox is always empty because it doesnt run the check and the stuff around it. I can't figure out how to do it, I tried a lot and asked some people if they can help me but no one could.

I hope someone can help me because I'm tired of this thing but I can't give up now.

Thanks in advance!

C#:
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Threading;

using System.Windows.Forms;
using System.Collections.Concurrent;

namespace DeezerSongCatcher
{

    class DeezerCatcher
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new global::DeezerSongCatcher.DeezerSongCatcher());
        }
    }

    internal class Measure
    {
        public class MusicInfo
        {
            private string _Title;
            private int _State;

            public MusicInfo()
            {
                Player = "";
                _Title = "";
                Artist = "";
                Album = "";
                Cover = "";
                CoverWebAddress = "";
                CoverByteArr = new byte[0];
                Duration = "0:00";
                DurationSec = 0;
                Position = "0:00";
                PositionSec = 0;
                Progress = 0.0;
                Volume = 100;
                Rating = 0;
                Repeat = 0;
                Shuffle = 0;
                _State = 0;
                TimeStamp = 0;
                TrackID = "";
                AlbumID = "";
                ArtistID = "";
                ID = "";
            }

            public string Player { get; set; }
            public string Title
            {
                get { return this._Title; }

                set
                {
                    this._Title = value;

                    if(value != "")
                    {
                        this.TimeStamp = DateTime.Now.Ticks / (decimal)TimeSpan.TicksPerMillisecond;
                    }
                    else
                    {
                        this.TimeStamp = 0;
                    }
                }
            }
            public string Artist { get; set; }
            public string Album { get; set; }
            public string Cover { get; set; }
            public string CoverWebAddress { get; set; }
            public byte[] CoverByteArr { get; set; }
            public string Duration { get; set; }
            public int DurationSec { get; set; }
            public string Position { get; set; }
            public int PositionSec { get; set; }
            public double Progress { get; set; }
            public int Volume { get; set; }
            public int Rating { get; set; }
            public int Repeat { get; set; }
            public int Shuffle { get; set; }
            public string TrackID { get; set; }
            public string AlbumID { get; set; }
            public string ArtistID { get; set; }
            public int State
            {
                get { return this._State; }
       
                set
                {
                    this._State = value;
                    this.TimeStamp = DateTime.Now.Ticks / (decimal)TimeSpan.TicksPerMillisecond;
                }
            }
            public decimal TimeStamp { get; private set; }
            public string ID { get; set; }
        }

        enum InfoTypes
        {
            Status,
            Player,
            Title,
            Artist,
            Album,
            Cover,
            CoverWebAddress,
            Duration,
            Position,
            Progress,
            Volume,
            State,
            Rating,
            Repeat,
            Shuffle,
            TrackID,
            AlbumID,
            ArtistID
        }

        public static WebSocketServer wssv;

        public static ConcurrentDictionary<string, MusicInfo> musicInfo = new ConcurrentDictionary<string, MusicInfo>();
        public static MusicInfo displayedMusicInfo = new MusicInfo();

        private static string CoverOutputLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/DeezerSongInfo/cover.png";
        private static string CoverDefaultLocation = "";

        private static InfoTypes playerType = InfoTypes.Status;

        public class DeezerSongCatcher : WebSocketBehavior
        {
            protected override void OnMessage(MessageEventArgs arg)
            {
                try
                {
                    string type = arg.Data.Substring(0, arg.Data.IndexOf(":"));
                    string info = arg.Data.Substring(arg.Data.IndexOf(":") + 1);

                    MusicInfo currMusicInfo = new MusicInfo();
                    if(!musicInfo.TryGetValue(this.ID, out currMusicInfo))
                    {
                        currMusicInfo = new MusicInfo();
                        musicInfo.GetOrAdd(this.ID, currMusicInfo);
                    }

                    if(currMusicInfo == null)
                    {
                        currMusicInfo = new MusicInfo();
                    }

                    currMusicInfo.ID = this.ID;

                    if(type.ToUpper() == InfoTypes.Player.ToString().ToUpper())
                    {
                        currMusicInfo.Player = info;
                    }
                    else
                    {
                        if(type.ToUpper() == InfoTypes.Title.ToString().ToUpper())
                        {
                            currMusicInfo.Title = info;
                        }
                        else if (type.ToUpper() == InfoTypes.Artist.ToString().ToUpper())
                        {
                            currMusicInfo.Artist = info;
                        }
                        else if (type.ToUpper() == InfoTypes.Album.ToString().ToUpper())
                        {
                            currMusicInfo.Album = info;
                        }
                        else if (type.ToUpper() == InfoTypes.Cover.ToString().ToUpper())
                        {
                            if (info.Length > 0)
                            {
                                Thread imageDownload = new Thread(() => GetImageFromUrl(this.ID, info));
                                imageDownload.Start();
                            }
                        }
                        else if (type.ToUpper() == InfoTypes.Duration.ToString().ToUpper())
                        {
                         
                            currMusicInfo.Duration = info;

                            try
                            {
                                string[] durArr = currMusicInfo.Duration.Split(':');

                               
                                int durSec = Convert.ToInt16(durArr[durArr.Length - 1]);
                                int durMin = durArr.Length > 1 ? Convert.ToInt16(durArr[durArr.Length - 2]) * 60 : 0;
                                int durHour = durArr.Length > 2 ? Convert.ToInt16(durArr[durArr.Length - 3]) * 60 * 60 : 0;


                                currMusicInfo.DurationSec = durHour + durMin + durSec;
                                currMusicInfo.Progress = 0;
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine(e.ToString());
                            }
                        }
                        else if (type.ToUpper() == InfoTypes.Position.ToString().ToUpper())
                        {
                            currMusicInfo.Position = info;

                            try
                            {
                                string[] posArr = currMusicInfo.Position.Split(':');

                                //Duration will always have seconds and minutes
                                int posSec = Convert.ToInt16(posArr[posArr.Length - 1]);
                                int posMin = posArr.Length > 1 ? Convert.ToInt16(posArr[posArr.Length - 2]) * 60 : 0;
                                int posHour = posArr.Length > 2 ? Convert.ToInt16(posArr[posArr.Length - 3]) * 60 * 60 : 0;


                                currMusicInfo.PositionSec = posHour + posMin + posSec;

                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine(e.ToString());
                            }


                            if (currMusicInfo.DurationSec > 0)
                            {
                                currMusicInfo.Progress = (double)currMusicInfo.PositionSec / currMusicInfo.DurationSec * 100.0;
                            }
                            else
                            {
                                currMusicInfo.Progress = 100;
                            }

                        }
                        else if (type.ToUpper() == InfoTypes.State.ToString().ToUpper())
                        {
                            try
                            {
                                currMusicInfo.State = Convert.ToInt16(info);
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine(e.ToString());
                            }
                        }
                        else if (type.ToUpper() == InfoTypes.Volume.ToString().ToUpper())
                        {
                            try
                            {
                                //For some odd reason toInt can not take a string containing a decimal directly so convert to decimal first
                                currMusicInfo.Volume = Convert.ToInt16(Convert.ToDecimal(info));
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine(e.ToString());
                            }
                        }
                        else if (type.ToUpper() == InfoTypes.Rating.ToString().ToUpper())
                        {
                            try
                            {
                                currMusicInfo.Rating = Convert.ToInt16(info);
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine(e.ToString());
                            }
                        }
                        else if (type.ToUpper() == InfoTypes.Repeat.ToString().ToUpper())
                        {
                            try
                            {
                                currMusicInfo.Repeat = Convert.ToInt16(info);
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine(e.ToString());
                            }
                        }
                        else if (type.ToUpper() == InfoTypes.Shuffle.ToString().ToUpper())
                        {
                            try
                            {
                                currMusicInfo.Shuffle = Convert.ToInt16(info);
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine(e.ToString());
                            }
                        }
                        else if (type.ToUpper() == InfoTypes.TrackID.ToString().ToUpper())
                        {
                            currMusicInfo.TrackID = info;
                        }
                        else if (type.ToUpper() == InfoTypes.AlbumID.ToString().ToUpper())
                        {
                            currMusicInfo.AlbumID = info;
                        }
                        else if (type.ToUpper() == InfoTypes.ArtistID.ToString().ToUpper())
                        {
                            currMusicInfo.ArtistID = info;
                        }
                        else if (type.ToUpper() == "ERROR")
                        {
                            System.Diagnostics.Debug.WriteLine("Web Side Error:" + info);
                        }
                        else if (type.ToUpper() == "ERRORD")
                        {
                            System.Diagnostics.Debug.WriteLine("Web Error:" + info);
                        }


                        if (type.ToUpper() != InfoTypes.Position.ToString().ToUpper() && currMusicInfo.Title != "")
                        {
                            updateDisplayedInfo();
                        }
                    }

                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(arg.Data);
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                }
            }
            protected override void OnOpen()
            {
                base.OnOpen();

                musicInfo.GetOrAdd(this.ID, new MusicInfo());
            }

            protected override void OnClose(CloseEventArgs e)
            {
                base.OnClose(e);

                MusicInfo temp;

                musicInfo.TryRemove(this.ID, out temp);
                if(displayedMusicInfo.ID == temp.ID)
                {
                    updateDisplayedInfo();
                }
            }

            public void SendMessage(string stringToSend)
            {
                Sessions.Broadcast(stringToSend);
            }
        }

        public static void updateDisplayedInfo()
        {
            try
            {
                var iterableDictionary = musicInfo.OrderByDescending(key => key.Value.TimeStamp);
                bool suitableMatch = false;

                foreach(KeyValuePair<string, MusicInfo> item in iterableDictionary)
                {
                    if (item.Value.State == 1 && item.Value.Volume >= 1)
                    {
                        if (displayedMusicInfo.ID != item.Value.ID)
                        {
                            if (item.Value.CoverByteArr.Length > 0)
                            {
                                Thread t = new Thread(() => WriteStream(item.Value.ID, item.Value.CoverByteArr));
                                t.Start();
                            }
                        }
                        displayedMusicInfo = item.Value;
                        suitableMatch = true;
                        break;
                    }
                }

                if(!suitableMatch)
                {
                    MusicInfo fallBackInfo = iterableDictionary.FirstOrDefault().Value;
                    {
                        if(fallBackInfo == null)
                        {
                            fallBackInfo = new MusicInfo();
                        }

                        if(displayedMusicInfo.ID != fallBackInfo.ID)
                        {
                            if(fallBackInfo.CoverByteArr.Length > 0)
                            {
                                Thread t = new Thread(() => WriteStream(fallBackInfo.ID, fallBackInfo.CoverByteArr));
                                t.Start();
                            }
                        }
                        displayedMusicInfo = fallBackInfo;
                    }
                }
            }
            catch(Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }
        }

        public static void GetImageFromUrl(string id, string url)
        {
            try
            {
                // Create http request
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
                {

                    // Read as stream
                    using (Stream stream = httpWebReponse.GetResponseStream())
                    {
                        Byte[] image = ReadStream(stream);

                        MusicInfo currMusicInfo;
                        if (musicInfo.TryGetValue(id, out currMusicInfo))
                        {
                            //@TODO is this null set needed?
                            currMusicInfo.Cover = null;
                            currMusicInfo.CoverByteArr = image;
                        }

                        //If this image comes from the same ID as the current displayed image go on ahead and write to disk
                        if (id == displayedMusicInfo.ID)
                        {
                            WriteStream(id, image);
                        }

                        //Only set web address after image has been written to disk
                        if (currMusicInfo != null)
                        {
                            currMusicInfo.CoverWebAddress = url;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }
        }

        private static byte[] ReadStream(Stream input)
        {
            byte[] buffer = new byte[1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        private static void WriteStream(string id, Byte[] image)
        {
            try
            {
                if(CoverOutputLocation == Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/DeezerSongInfo/cover.png")
                {
                    System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/DeezerSongInfo");
                }

                FileStream fs = new FileStream(CoverOutputLocation, FileMode.Create, FileAccess.Write, FileShare.Read);
                BinaryWriter bw = new BinaryWriter(fs);
                try
                {
                    bw.Write(image);
                }
                catch (Exception e)
                {
                    bw.Close();
                    fs.Close();
                    throw e;
                }
                finally
                {
                    bw.Close();
                    fs.Close();
                }

                MusicInfo lastUpdateMusicInfo;
                if(musicInfo.TryGetValue(id, out lastUpdateMusicInfo))
                {
                    lastUpdateMusicInfo.Cover = CoverOutputLocation;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }
        }

        static int measureCount = 0;

        internal Measure(string s)
        {
            measureCount++;
            try
            {
                if(wssv == null)
                {
                    wssv = new WebSocketServer(8974);
                }

                if(wssv.IsListening == false)
                {
                    wssv.AddWebSocketService<DeezerSongCatcher>("/");
                    wssv.Start();
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }
        }

        internal virtual void Dispose()
        {
            measureCount--;
            if(wssv.IsListening && measureCount == 0)
            {
                wssv.Stop();
            }
        }
       


        internal virtual double Update()
        {
            try
            {
                switch (playerType)
                {
                    case InfoTypes.State:
                        return displayedMusicInfo.State;
                    case InfoTypes.Status:
                        //@TODO have this possibly be per website
                        return wssv.WebSocketServices.SessionCount > 0 ? 1 : 0;
                    case InfoTypes.Volume:
                        return displayedMusicInfo.Volume;
                    case InfoTypes.Rating:
                        return displayedMusicInfo.Rating;
                    case InfoTypes.Repeat:
                        return displayedMusicInfo.Repeat;
                    case InfoTypes.Shuffle:
                        return displayedMusicInfo.Shuffle;
                    case InfoTypes.Progress:
                        return displayedMusicInfo.Progress;
                    case InfoTypes.Position:
                        return displayedMusicInfo.PositionSec;
                    case InfoTypes.Duration:
                        return displayedMusicInfo.DurationSec;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }

            return 0.0;
        }

        public string GetString()
        {
            try
            {
                switch (playerType)
                {
                    case InfoTypes.Player:
                        return displayedMusicInfo.Player;
                    case InfoTypes.Title:
                        return displayedMusicInfo.Title;
                    case InfoTypes.Artist:
                        return displayedMusicInfo.Artist;
                    case InfoTypes.Album:
                        return displayedMusicInfo.Album;
                    case InfoTypes.Cover:
                        if (displayedMusicInfo.Cover != null && displayedMusicInfo.Cover.Length > 0)
                        {
                            return displayedMusicInfo.Cover;
                        }
                        else if (CoverDefaultLocation != null && CoverOutputLocation.Length > 0)
                        {
                            return CoverDefaultLocation;
                        }
                        return CoverOutputLocation;
                    case InfoTypes.CoverWebAddress:
                        return displayedMusicInfo.CoverWebAddress;
                    case InfoTypes.Position:
                        return displayedMusicInfo.Position;
                    case InfoTypes.Duration:
                        return displayedMusicInfo.Duration;
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());  
            }
            return null;
        }
    }
}
 
Last edited:
The Problem is that I dont run the check (DeezerSongCatcher : WebSocketBehavior) for the informations etc. and my question is how to do that.
 
That doesn't negate the fact that there's too much code there. Post only the code that is relevant to the question. If you need to create a separate test application and isolate specific functionality in order to isolate the relevant code then do that.
 
Okay, than I ask with a diffrent way. I got an internal class there and I want to run it in my main class. How can I do that?
 
There is too much code there for any question, asked any way. If it's too much trouble for you to narrow down the code to only what's relevant so that we don't have to waste our time wading through it, you're not going to make too many friends. If you're not prepared to help us help you, we're unlikely to help you. Make an effort to help us and we will likely return the favour. We want to help but we're not here to waste our time or be taken advantage of. Your time is not more valuable than ours so spend some of it paring down that code to what's actually relevant to your question.
 
You don't understand it. Ignore the code. It's a general question about c#. How can I run an Internal class with few other classes inside in the main or other methods.
Or like you want it:
How to run this:
C#:
internal class Measure
{
    //CODE
}
In this:
C#:
    class DeezerCatcher
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new DeezerSongCatcher());
          
        }
    }
 
I'm closing this thread because you apparently no longer want the question you asked to be answered. If you now have a different question, please start a new thread with content and a title that relate to that new question. Changing your question mid-thread is not conducive to clarity.
 
Status
Not open for further replies.

Latest posts

Back
Top Bottom