"Rewritting" WebNowPlaying

状态
不打开进一步回复。

sirizontax.

新成员
加入
5月9日,2020年
消息
4
编程经验
1-3
嘿,

我开始编辑Rainmeter插件的代码"WebNowPlaying"因为我希望它将当前的歌曲信息写入文件。它从其WebExtension获取歌曲信息,它使用WebSocket。我显然,复制粘贴代码并试图将其实施到表单中,因此您按下一个按钮,它会告诉您您当前的歌曲标题。
现在我的问题:我现在尝试了4个小时来制作它,但消息框始终是空的,因为它不会运行检查和它周围的东西。我无法弄清楚如何做到这一点,我尝试了很多,如果他们可以帮助我,但没有人可以问一些人。

我希望有人可以帮助我,因为我厌倦了这件事,但我现在不能放弃。

提前致谢!

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:

jmplhinney.

C#论坛主持人
工作人员
加入
2011年4月23日
消息
3,553
地点
悉尼,澳大利亚
编程经验
10+
这并不能否定那里的代码太多了。仅发布与问题相关的代码。如果需要创建单独的测试应用程序并隔离特定功能,以便隔离相关代码,然后执行此操作。
 

jmplhinney.

C#论坛主持人
工作人员
加入
2011年4月23日
消息
3,553
地点
悉尼,澳大利亚
编程经验
10+
有任何问题有太多的代码,请问任何方式。如果你对你来说太麻烦了,只需缩小代码,只有什么是相关的,以便我们不必浪费我们的时间才能趟过它,你不会做太多朋友。如果您没有准备帮助我们帮助您,我们不太可能帮助您。努力帮助我们,我们可能会回报。我们想帮助,但我们不在这里浪费我们的时间或被利用。您的时间并不比我们更有价值,所以将其中一些折叠在该代码上,以便与您的问题实际相关的代码。
 

sirizontax.

新成员
加入
5月9日,2020年
消息
4
编程经验
1-3
你不明白。忽略代码。这是关于C#的一般问题。如何在主要或其他方法中使用其他其他类运行内部类。
或者喜欢你想要它:
如何运行这个:
C#:
internal class Measure
{
    //CODE
}
在这个:
C#:
    class DeezerCatcher
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new DeezerSongCatcher());
          
        }
    }
 

jmplhinney.

C#论坛主持人
工作人员
加入
2011年4月23日
消息
3,553
地点
悉尼,澳大利亚
编程经验
10+
我正在关闭这个帖子,因为你显然不再想要你要求回答的问题。如果您现在有不同的问题,请使用内容启动一个新的线程和与该新问题相关的标题。改变你的问题中线并不有利于清晰度。
 
状态
不打开进一步回复。
最佳 底部