Example #1
0
 public Song(string songPath, int trackCount)
 {
     this.info = new SongInfo("no title", "no artist", "no album", "no year", "normal", GameRegistry.GetString("UserName"));
     this.songPath = songPath;
     this.trackCount = trackCount;
     FillTracks(trackCount);
 }
Example #2
0
 public Song(SongInfo info, string songPath, List<Track> tracks)
 {
     this.info = info;
     this.songPath = songPath;
     this.trackCount = tracks.Count;
     this.tracks = tracks;
 }
Example #3
0
        public override bool ParseTitle(SongInfo si, string title)
        {
            try
            {
                var alsongFormat = Registry.GetValue(@"HKEY_CURRENT_USER\Software\ESTsoft\ALSong\Param\Option\Title", "DescFormat", null) as string;
                if (alsongFormat == null) return false;

                alsongFormat = alsongFormat.Replace("%가수%", "(?<가수>.+)");
                alsongFormat = alsongFormat.Replace("%제목%", "(?<제목>.+)");
                alsongFormat = alsongFormat.Replace("%앨범%", "(?<앨범>.+)");
                alsongFormat = alsongFormat.Replace("%년도%", ".+");
                alsongFormat = alsongFormat.Replace("%설명%", ".+");
                alsongFormat = alsongFormat.Replace("%장르%", ".+");
                alsongFormat = alsongFormat.Replace("%파일%", ".+");
                alsongFormat = alsongFormat.Replace("%경로%", ".+");
                alsongFormat = alsongFormat.Replace("%트랙%", ".+");

                var regex = new Regex(alsongFormat, RegexOptions.IgnoreCase | RegexOptions.Singleline);

                var match = regex.Match(title);
                if (!match.Success) return false;

                Group g;
                si.Artist   = (g = match.Groups["가수"]) != null ? g.Value : null;
                si.Title    = (g = match.Groups["제목"]) != null ? g.Value : null;
                si.Album    = (g = match.Groups["앨범"]) != null ? g.Value : null;

                return true;
            }
            catch
            { }

            return false;
        }
Example #4
0
        public override bool ParseManual(SongInfo si, IntPtr hwnd)
        {
            if (!this.Init()) return false;

            try
            {
                if (Get(si, hwnd, this.m_itunes.CurrentTrack))
                    return true;
                else if (!string.IsNullOrWhiteSpace(this.m_itunes.CurrentStreamTitle))
                {
                    si.Title = this.m_itunes.CurrentStreamTitle;
                    if (!string.IsNullOrWhiteSpace(this.m_itunes.CurrentStreamURL))
                    {
                        try
                        {
                            var uri = new Uri(this.m_itunes.CurrentStreamURL);
                            si.Url = this.m_itunes.CurrentStreamURL;
                        }
                        catch
                        { }
                    }

                    return true;
                }
            }
            catch
            { }

            return false;
        }
Example #5
0
        public void TestAddingListOfSongs()
        {
            EZPlaylist playlist = new EZPlaylist("My Awesome Playlist");
            MediaLibrary lib = new MediaLibrary();
            if (lib.Songs.Count > 1)
            {
                List<SongInfo> list = new List<SongInfo>();

                Song song = lib.Songs[0];
                SongInfo si1 = new SongInfo(song.Artist.Name, song.Album.Name, song.Name, song.Duration, song.TrackNumber);
                list.Add(si1);

                song = lib.Songs[1];
                SongInfo si2 = new SongInfo(song.Artist.Name, song.Album.Name, song.Name, song.Duration, song.TrackNumber);
                list.Add(si2);

                playlist.AddList(list.AsReadOnly());

                Assert.IsTrue(playlist.Count == 2);
                Assert.IsTrue(playlist.Songs.Contains(si1));
                Assert.IsTrue(playlist.Songs.Contains(si2));
            }
            else
            {
                Assert.Fail("Can't test adding a song because there are no songs to add or there is only one song.");
            }
        }
Example #6
0
 public Song(SongInfo info, string songPath, int trackCount)
 {
     this.info = info;
     this.songPath = songPath;
     this.trackCount = trackCount;
     FillTracks(trackCount);
 }
Example #7
0
        /// <summary>
        /// Retrieve a list of all song contained in the archive.
        /// Returned info includes song title, artist, album and year,
        /// as well as the available arrangements.
        /// </summary>
        /// <returns>List of included songs.</returns>
        public IList<SongInfo> GetSongList()
        {
            // Each song has a corresponding .json file within the archive containing
            // information about it.
            var infoFiles = archive.Entries.Where(x => x.Name.StartsWith("manifests/songs")
                && x.Name.EndsWith(".json")).OrderBy(x => x.Name);

            var songList = new List<SongInfo>();
            SongInfo currentSong = null;

            foreach (var entry in infoFiles)
            {
                // the entry's filename is identifier_arrangement.json
                var fileName = Path.GetFileNameWithoutExtension(entry.Name);
                var splitPoint = fileName.LastIndexOf('_');
                var identifier = fileName.Substring(0, splitPoint);
                var arrangement = fileName.Substring(splitPoint + 1);
                
                // temporary: exclude vocals from list until we can actually deal with them
                if (arrangement.ToLower().StartsWith("vocals") || arrangement.ToLower().StartsWith("jvocals"))
                    continue;

                if (currentSong == null || currentSong.Identifier != identifier)
                {
                    // extract song info from the .json file
                    using (var reader = new StreamReader(entry.Data.OpenStream()))
                    {
                        try
                        {
                            JObject o = JObject.Parse(reader.ReadToEnd());
                            var attributes = o["Entries"].First.Last["Attributes"];

                            currentSong = new SongInfo()
                            {
                                Title = attributes["SongName"].ToString(),
                                Artist = attributes["ArtistName"].ToString(),
                                ArtistSort = attributes["ArtistNameSort"].ToString(),
                                Album = attributes["AlbumName"].ToString(),
                                Year = attributes["SongYear"].ToString(),
                                Identifier = identifier,
                                Arrangements = new List<string>()
                            };
                            songList.Add(currentSong);
                        }
                        catch (NullReferenceException)
                        {
                            // It appears the vocal arrangements don't contain all the track
                            // information. Just ignore this.
                        }
                    }
                }

                currentSong.Arrangements.Add(arrangement);
            }

            return songList;
        }
Example #8
0
 public ReportedSong(BasicInfo Reporter, SongInfo Song, string ReportDate, 
     string ReportType, string Comment)
 {
     this.Reporter = Reporter;
     this.Song = Song;
     this.ReportDate = ReportDate;
     this.ReportType = ReportType;
     this.Comment = Comment;
 }
 public void Set(string header)
 {
     _songInfo = SongEditor.SONG_EDITOR.curSong.info;
     songNameField.text = _songInfo.title;
     artistNameField.text = _songInfo.artist;
     albumNameField.text = _songInfo.album;
     releasedYearField.text = _songInfo.year;
     creatorNameField.text = _songInfo.creator;
     SetHeader(header);
 }
Example #10
0
        public override void Edit(SongInfo si)
        {
            if (!string.IsNullOrWhiteSpace(si.Url))
            {
                var m = this.UrlRegex.Match(si.Url);
                if (!m.Success) return;

                if (si.Url.IndexOf("live") >= 0)
                    si.Url = "http://live.nicovideo.jp/watch/" + m.Groups[1].Value;
                else
                    si.Url = "http://nico.ms/" + m.Groups[1].Value;
            }
        }
Example #11
0
    AudioClip GetSong(SongInfo songInfo)
    {
        if (songInfo.entranceClip == null || songInfo.entrancePlayed) {

            source1.loop = true;
            source2.loop = true;
            return songInfo.loopClip;
        } else {

            source1.loop = false;
            source2.loop = false;
            currentSongInfo.entrancePlayed = true;// assuming currentSongInfo is set before calling this
            return songInfo.entranceClip;
        }
    }
Example #12
0
    void Awake()
    {
        sortArray (songs);
        currentSong = source1;
        nextSong = source2;
        currentSongInfo = songs [0];
        currentSong.clip = GetSong(currentSongInfo);
        currentSong.Play ();
        maxVolume = currentSong.volume;
        currentAreaThreatLvl = EnemyManager.instance.areaThreatLvl;

        DontDestroyOnLoad (gameObject);
        if (singleton != null) //seperate from the singleton class to allow deletion of gameobject rather than script
            Destroy(gameObject);
        else
            singleton = this;
    }
Example #13
0
 public void TestAddingSong()
 {
     EZPlaylist playlist = new EZPlaylist("My Awesome Playlist");
     MediaLibrary lib = new MediaLibrary();
     if (lib.Songs.Count > 0)
     {
         Song song = lib.Songs[0];
         SongInfo si = new SongInfo(song.Artist.Name, song.Album.Name, song.Name, song.Duration, song.TrackNumber);
         playlist.Add(si);
         Assert.IsTrue(playlist.Count == 1);
         Assert.IsTrue(playlist.Songs.Contains(si));
     }
     else
     {
         Assert.Fail("Can't test adding a song because there are no songs to add.");
     }
 }
Example #14
0
    void sortArray(SongInfo[] array)
    {
        SongInfo[] arrayCopy = (SongInfo[])array.Clone ();
        int[] sortedArray = new int[array.Length];
        int[] index = new int[array.Length];

        for (int i = 0; i < array.Length; i++)
            sortedArray[i] = array[i].activationLevel;
        Array.Sort(sortedArray);

        for (int i = 0; i < array.Length; i++) {
            index[i] = Array.IndexOf(sortedArray, array[i].activationLevel);
        }

        for (int i = 0; i < array.Length; i++)
            array[index[i]] = arrayCopy[i];
    }
Example #15
0
        public override void Edit(SongInfo si)
        {
            if (!string.IsNullOrWhiteSpace(si.Url))
            {
                try
                {
                    // 플레이 리스트인지 확인한다
                    var ml = this.m_playlist.Match(new Uri(si.Url).Query);
                    var v  = this.UrlRegex.Match(si.Url).Groups[1].Value;

                    if (ml.Success)
                    {
                        var list = ml.Groups[1].Value;

                        // 공개 플레이리스트 확인
                        var req = WebRequest.Create("https://www.youtube.com/playlist?list=" + list) as HttpWebRequest;
                        req.Timeout = req.ReadWriteTimeout = 2000;

                        using (var res = req.GetResponse())
                        using (var stm = new StreamReader(res.GetResponseStream()))
                        {
                            var body = stm.ReadToEnd();
                            if (!this.m_checkPublic.IsMatch(body))
                            {
                                // 비공개 플레이 리스트
                                // 링크를 단일 링크로 재작성
                                si.Url = "https://youtu.be/" + v;
                            }
                            else
                            {
                                // 공개 플레이 리스트
                                // youtu.be 링크로 재작성
                                si.Url = string.Format("https://youtu.be/{0}?list={1}", v, list);
                            }
                        }
                    }
                    else
                    {
                        si.Url = "https://youtu.be/" + v;
                    }
                }
                catch
                { }
            }
        }
Example #16
0
        public override bool ParseManual(SongInfo si, IntPtr hwnd)
        {
            // Finding the WMP window
            hwnd = NativeMethods.FindWindow("WMPlayerApp", "Windows Media Player");
            if (hwnd == IntPtr.Zero) return false;

            var walker          = TreeWalker.ControlViewWalker;
            // Whole WMP window
            var wmpPlayer       = AutomationElement.FromHandle(hwnd);
            var wmpAppHost      = walker.GetFirstChild(wmpPlayer);
            var wmpSkinHost     = walker.GetFirstChild(wmpAppHost);
            // All elements in WMP window
            var wmpContainer    = walker.GetFirstChild(wmpSkinHost);
            // Container with song information
            var wmpSongInfo     = walker.GetFirstChild(wmpContainer);

            // 전체화면이 아님
            if (wmpSongInfo == null) return false;

            // Iterating through all components in container - searching for container with song information
            while (wmpSongInfo.Current.ClassName != "CWmpControlCntr")
            {
                wmpSongInfo = walker.GetNextSibling(wmpSongInfo);

                if (wmpSongInfo == null)
                    return false;
            }

            // Walking through children (image, hyperlink, song info etc.)
            var info = GetChildren(wmpSongInfo);
            info = GetChildren(info[0]);
            info = GetChildren(info[1]);
            info = GetChildren(info[2]);

            // Obtaining elements with desired information
            si.Title  = info[0].Current.Name;
            si.Album  = info[3].Current.Name;
            si.Artist = info[4].Current.Name;
            si.Handle = hwnd;

            return true;
        }
Example #17
0
        private void ExportSong(string currentDir, SongInfo cur)
        {
            string srcName = Path.GetFileNameWithoutExtension(cur.File.Name);
            Song song = songEditor.ReadSong(srcName);
            if (song == null) {
                Log("Skipped unknown song: " + cur.File.FullName);
                return;
            }

            string vol = "0";
            if (song.DefaultVolume.HasValue) {
                vol = song.DefaultVolume.Value.ToString();
            }
            string title = FileOperations.SantizeFilename(song.DefaultName);
            string destFilename = srcName + "." + vol + "." + title + cur.File.Extension;
            string dest = Path.Combine(currentDir, destFilename);

            if (cur.File.Exists) {
                File.Copy(cur.File.FullName, dest, true);
            } else {
                // Create an empty placeholder file.
                File.Create(dest).Dispose();
            }
        }
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x4A)
            {
                COPYDATASTRUCT cds = (COPYDATASTRUCT)m.GetLParam(typeof(COPYDATASTRUCT));
                string Message = ReceiveMessage.GetMessageString(cds);
                //Console.WriteLine("Debug: " + Message);

                if (Message.StartsWith("ZUNE"))
                {
                    string[] Split = Message.Split(new string[] { "\\0" }, StringSplitOptions.None);

                    if (Split.Length >= 7)
                    {
                        string ZuneRunning = Split[2];
                        string ZuneTrack = Split[4];
                        string ZuneArtist = Split[5];
                        string ZuneAlbum = Split[6];

                        SongInfo SongInfo = new SongInfo();
                        SongInfo.ZuneRunning = 1;
                        SongInfo.ZuneTrack = ZuneTrack;
                        SongInfo.ZuneArtist = ZuneArtist;
                        SongInfo.ZuneAlbum = ZuneAlbum;
                        SongInfo.SendSongInfo();
                    }
                    else
                    {
                        SongInfo SongInfo = new SongInfo();
                        SongInfo.ZuneRunning = 0;
                        SongInfo.SendSongInfo();
                    }
                }
            }
            base.WndProc(ref m);
        }
Example #19
0
        public void GetInfo(string filename)
        {
            toolStripProgressBar1.Value = 10;
            SongInfo si = new SongInfo();
            File.Copy(filename,@"C:\codegen\test.mp3",true );
            toolStripStatusLabel1.Text = "Анализирование трека ...";
            run(@"C:\codegen\codegen.exe", " \"" + filename + "\" 20 45");
            toolStripProgressBar1.Value = 30;
            //run(@"C:\codegen\codegen.exe", @" C:\codegen\test.mp3 20 45");


            //richTextBox1.Text = "";

            

           //ResourceManager resourceManager = new ResourceManager("AssemblyName.Resources", Assembly.GetExecutingAssembly());
            //System.Diagnostics.Process proc2 = new System.Diagnostics.Process();
            //proc2.StartInfo.WorkingDirectory = @"C:\codegen\";
            ///proc2.StartInfo.FileName = @"C:\codegen\curl.exe";
            //proc2.StartInfo.Arguments = "-F \"api_key=K6ESC9GPDLWQNERPZ\" -F \"query=@C:\\codegen\\json_string.json\" \"http://developer.echonest.com/api/v4/song/identify\" >result.inf";
            //proc2.Start();
            //proc2.WaitForExit();

        }
        public string GenerateManifest(string dlcName, IList<Arrangement> arrangements, SongInfo songInfo, Platform platform)
        {
            var manifest = Manifest;
            manifest.Entries = new Dictionary<string, Dictionary<string, Attributes>>();
            bool firstarrangset = false;

            Arrangement vocal = null;
            if (arrangements.Any<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal))
                vocal = arrangements.Single<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal);

            var manifestFunctions = new ManifestFunctions(platform.version);
            var songPartition = new SongPartition();

            foreach (var x in arrangements)
            {
                var isVocal = x.ArrangementType == Sng.ArrangementType.Vocal;
                var song = (isVocal) ? null : Song.LoadFromFile(x.SongXml.File);

                var attribute = new Attributes();
                attribute.AlbumArt = String.Format("urn:llid:{0}", AggregateGraph.AlbumArt.LLID);
                attribute.AlbumNameSort = attribute.AlbumName = songInfo.Album;
                attribute.ArrangementName = x.Name.ToString();
                attribute.ArtistName = songInfo.Artist;
                attribute.ArtistNameSort = songInfo.ArtistSort;
                attribute.AssociatedTechniques = new List<string>();
                //Should be 51 for bass, 49 for vocal and guitar
                attribute.BinaryVersion = x.ArrangementType == Sng.ArrangementType.Bass ? 51 : 49;
                attribute.BlockAsset = String.Format("urn:emergent-world:{0}", AggregateGraph.XBlock.Name);
                attribute.ChordTemplates = null;
                attribute.DISC_DLC_OTHER = "Disc";
                attribute.DisplayName = songInfo.SongDisplayName;
                attribute.DLCPreview = false;
                attribute.EffectChainMultiplayerName = string.Empty;
                attribute.EffectChainName = isVocal ? "" : (dlcName + "_" + x.ToneBase == null ? "Default" : x.ToneBase.Replace(' ', '_'));
                attribute.EventFirstTimeSortOrder = 9999;
                attribute.ExclusiveBuild = new List<object>();
                attribute.FirstArrangementInSong = false;
                if (isVocal && !firstarrangset)
                {
                    firstarrangset = true;
                    attribute.FirstArrangementInSong = true;
                }
                attribute.ForceUseXML = true;
                attribute.Tag = "PLACEHOLDER Tag";
                attribute.InputEvent = isVocal ? "Play_Tone_Standard_Mic" : "Play_Tone_";
                attribute.IsDemoSong = false;
                attribute.IsDLC = true;
                attribute.LastConversionDateTime = "";
                int masterId = isVocal ? 1 : x.MasterId;
                attribute.MasterID_PS3 = masterId;
                attribute.MasterID_Xbox360 = masterId;
                attribute.MaxPhraseDifficulty = 0;
                attribute.PersistentID = x.Id.ToString().Replace("-", "").ToUpper();
                attribute.PhraseIterations = new List<PhraseIteration>();
                attribute.Phrases = new List<Phrase>();
                attribute.PluckedType = x.PluckedType == Sng.PluckedType.Picked ? "Picked" : "Not Picked";
                attribute.RelativeDifficulty = isVocal ? 0 : song.Levels.Count();
                attribute.RepresentativeArrangement = false;
                attribute.Score_MaxNotes = 0;
                attribute.Score_PNV = 0;
                attribute.Sections = new List<Section>();
                attribute.Shipping = true;
                attribute.SongAsset = String.Format("urn:llid:{0}", x.SongFile.LLID);
                attribute.SongEvent = String.Format("Play_{0}", dlcName);
                attribute.SongKey = dlcName;
                attribute.SongLength = 0;
                attribute.SongName = songInfo.SongDisplayName;
                attribute.SongNameSort = songInfo.SongDisplayNameSort;
                attribute.SongXml = String.Format("urn:llid:{0}", x.SongXml.LLID);
                attribute.SongYear = songInfo.SongYear;
                attribute.TargetScore = 0;
                attribute.ToneUnlockScore = 0;
                attribute.TwoHandTapping = false;
                attribute.UnlockKey = "";
                attribute.Tuning = x.Tuning;
                attribute.VocalsAssetId = x.ArrangementType == Sng.ArrangementType.Vocal ? "" : (vocal != null) ? String.Format("{0}|GRSong_{1}", vocal.Id, vocal.Name) : "";
                attribute.ChordTemplates = new List<ChordTemplate>();
                manifestFunctions.GenerateDynamicVisualDensity(attribute, song, x);

                if (!isVocal)
                {
                    #region "Associated Techniques"

                    attribute.PowerChords = song.HasPowerChords();
                    if (song.HasPowerChords()) AssociateTechniques(x, attribute, "PowerChords");
                    attribute.BarChords = song.HasBarChords();
                    if (song.HasBarChords()) AssociateTechniques(x, attribute, "BarChords");
                    attribute.OpenChords = song.HasOpenChords();
                    if (song.HasOpenChords()) AssociateTechniques(x, attribute, "ChordIntro");
                    attribute.DoubleStops = song.HasDoubleStops();
                    if (song.HasDoubleStops()) AssociateTechniques(x, attribute, "DoubleStops");
                    attribute.Sustain = song.HasSustain();
                    if (song.HasSustain()) AssociateTechniques(x, attribute, "Sustain");
                    attribute.Bends = song.HasBends();
                    if (song.HasBends()) AssociateTechniques(x, attribute, "Bends");
                    attribute.Slides = song.HasSlides();
                    if (song.HasSlides()) AssociateTechniques(x, attribute, "Slides");
                    attribute.Tremolo = song.HasTremolo();
                    if (song.HasTremolo()) AssociateTechniques(x, attribute, "Tremolo");
                    attribute.SlapAndPop = song.HasSlapAndPop();
                    if (song.HasSlapAndPop()) AssociateTechniques(x, attribute, "Slap");
                    attribute.Harmonics = song.HasHarmonics();
                    if (song.HasHarmonics()) AssociateTechniques(x, attribute, "Harmonics");
                    attribute.PalmMutes = song.HasPalmMutes();
                    if (song.HasPalmMutes()) AssociateTechniques(x, attribute, "PalmMutes");
                    attribute.HOPOs = song.HasHOPOs();
                    if (song.HasHOPOs()) AssociateTechniques(x, attribute, "HOPOs");
                    attribute.FretHandMutes = song.HasFretHandMutes();
                    if (song.HasFretHandMutes()) AssociateTechniques(x, attribute, "FretHandMutes");
                    attribute.DropDPowerChords = song.HasDropDPowerChords();
                    if (song.HasDropDPowerChords()) AssociateTechniques(x, attribute, "DropDPowerChords");
                    attribute.Prebends = song.HasPrebends();
                    if (song.HasPrebends()) AssociateTechniques(x, attribute, "Prebends");
                    attribute.Vibrato = song.HasVibrato();
                    if (song.HasVibrato()) AssociateTechniques(x, attribute, "Vibrato");

                    //Bass exclusive
                    attribute.TwoFingerPlucking = song.HasTwoFingerPlucking();
                    if (song.HasTwoFingerPlucking()) AssociateTechniques(x, attribute, "Plucking");
                    attribute.FifthsAndOctaves = song.HasFifthsAndOctaves();
                    if (song.HasFifthsAndOctaves()) AssociateTechniques(x, attribute, "Octave");
                    attribute.Syncopation = song.HasSyncopation();
                    if (song.HasSyncopation()) AssociateTechniques(x, attribute, "Syncopation");

                    #endregion

                    attribute.AverageTempo = songInfo.AverageTempo;
                    attribute.RepresentativeArrangement = true;
                    attribute.SongPartition = songPartition.GetSongPartition(x.Name, x.ArrangementType);
                    attribute.SongLength = (float)Math.Round((decimal)song.SongLength, 3, MidpointRounding.AwayFromZero); //rounded
                    attribute.LastConversionDateTime = song.LastConversionDateTime;
                    attribute.TargetScore = 100000;
                    attribute.ToneUnlockScore = 70000;
                    attribute.SongDifficulty = (float)song.PhraseIterations.Average(it => song.Phrases[it.PhraseId].MaxDifficulty);
                    manifestFunctions.GenerateChordTemplateData(attribute, song);
                    manifestFunctions.GeneratePhraseData(attribute, song);
                    manifestFunctions.GenerateSectionData(attribute, song);
                    manifestFunctions.GeneratePhraseIterationsData(attribute, song, platform.version);
                }
                var attrDict = new Dictionary<string, Attributes> { { "Attributes", attribute } };
                manifest.Entries.Add(attribute.PersistentID, attrDict);
            }
            manifest.ModelName = "GRSong_Asset";
            manifest.IterationVersion = 2;
            return JsonConvert.SerializeObject(manifest, Formatting.Indented);
        }
Example #21
0
 public void newSong(SongInfo song)
 {
     UnityEngine.Debug.Log("new song");
 }
Example #22
0
        private static void HubLoop(object sender, HighResolutionTimerElapsedEventArgs e)
        {
            if (_ticksLength.Count > 30)
            {
                _ticksLength.RemoveAt(0);
            }
            _ticksLength.Add(DateTime.UtcNow.Subtract(_lastTick).Ticks / (float)TimeSpan.TicksPerMillisecond);
            _lastTick = DateTime.UtcNow;
            List <RoomInfo> roomsList = RoomsController.GetRoomInfosList();

            string titleBuffer = $"ServerHub v{Assembly.GetEntryAssembly().GetName().Version}: {roomsList.Count} rooms, {hubClients.Count} clients in lobby, {roomsList.Select(x => x.players).Sum() + hubClients.Count} clients total {(Settings.Instance.Server.ShowTickrateInTitle ? $", {Tickrate.ToString("0.0")} tickrate" : "")}";

            if (_currentTitle != titleBuffer)
            {
                _currentTitle = titleBuffer;
                Console.Title = _currentTitle;
            }

            List <Client> allClients = hubClients.Concat(RoomsController.GetRoomsList().SelectMany(x => x.roomClients)).Concat(RadioController.radioChannels.SelectMany(x => x.radioClients)).ToList();

            NetIncomingMessage msg;

            while (ListenerServer.ReadMessage(out msg))
            {
                try
                {
                    Program.networkBytesInNow += msg.LengthBytes;

                    switch (msg.MessageType)
                    {
                    case NetIncomingMessageType.ConnectionApproval:
                    {
                        byte[] versionBytes = msg.PeekBytes(4);
                        byte[] version      = msg.ReadBytes(4);

                        if (version[0] == 0 && version[1] == 0)
                        {
                            uint versionUint       = BitConverter.ToUInt32(version, 0);
                            uint serverVersionUint = ((uint)Assembly.GetEntryAssembly().GetName().Version.Major).ConcatUInts((uint)Assembly.GetEntryAssembly().GetName().Version.Minor).ConcatUInts((uint)Assembly.GetEntryAssembly().GetName().Version.Build).ConcatUInts((uint)Assembly.GetEntryAssembly().GetName().Version.Revision);
                            msg.SenderConnection.Deny($"Version mismatch!\nServer:{serverVersionUint}\nClient:{versionUint}");
                            Logger.Instance.Log($"Client version v{versionUint} tried to connect");
                            break;
                        }

                        byte[] serverVersion = new byte[4] {
                            (byte)Assembly.GetEntryAssembly().GetName().Version.Major, (byte)Assembly.GetEntryAssembly().GetName().Version.Minor, (byte)Assembly.GetEntryAssembly().GetName().Version.Build, (byte)Assembly.GetEntryAssembly().GetName().Version.Revision
                        };

                        if (version[0] != serverVersion[0] || version[1] != serverVersion[1] || version[2] != serverVersion[2])
                        {
                            msg.SenderConnection.Deny($"Version mismatch|{string.Join('.', serverVersion)}|{string.Join('.', version)}");
                            Logger.Instance.Log($"Client version v{string.Join('.', version)} tried to connect");
                            break;
                        }

                        PlayerInfo playerInfo = new PlayerInfo(msg);

                        if (Settings.Instance.Access.WhitelistEnabled)
                        {
                            if (!IsWhitelisted(msg.SenderConnection.RemoteEndPoint, playerInfo))
                            {
                                msg.SenderConnection.Deny("You are not whitelisted on this ServerHub!");
                                Logger.Instance.Warning($"Client {playerInfo.playerName}({playerInfo.playerId})@{msg.SenderConnection.RemoteEndPoint.Address} is not whitelisted!");
                                break;
                            }
                        }

                        if (IsBlacklisted(msg.SenderConnection.RemoteEndPoint, playerInfo))
                        {
                            msg.SenderConnection.Deny("You are banned on this ServerHub!");
                            Logger.Instance.Warning($"Client {playerInfo.playerName}({playerInfo.playerId})@{msg.SenderConnection.RemoteEndPoint.Address} is banned!");
                            break;
                        }

                        NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                        outMsg.Write(serverVersion);
                        outMsg.Write(Settings.Instance.Server.ServerHubName);

                        msg.SenderConnection.Approve(outMsg);

                        Client client = new Client(msg.SenderConnection, playerInfo);
                        client.playerInfo.updateInfo.playerState = PlayerState.Lobby;

                        client.ClientDisconnected += ClientDisconnected;

                        hubClients.Add(client);
                        allClients.Add(client);
                        Logger.Instance.Log($"{playerInfo.playerName} connected!");
                    };
                        break;

                    case NetIncomingMessageType.Data:
                    {
                        Client client = allClients.FirstOrDefault(x => x.playerConnection.RemoteEndPoint.Equals(msg.SenderEndPoint));

                        switch ((CommandType)msg.ReadByte())
                        {
                        case CommandType.Disconnect:
                        {
                            if (client != null)
                            {
                                allClients.Remove(client);
                                ClientDisconnected(client);
                            }
                        }
                        break;

                        case CommandType.UpdatePlayerInfo:
                        {
                            if (client != null)
                            {
                                if (msg.PeekByte() == 1 || !client.lastUpdateIsFull)
                                {
                                    client.UpdatePlayerInfo(msg);
                                }

                                if (Settings.Instance.Misc.PlayerColors.ContainsKey(client.playerInfo.playerId))
                                {
                                    client.playerInfo.updateInfo.playerNameColor = Settings.Instance.Misc.PlayerColors[client.playerInfo.playerId];
                                }
                            }
                        }
                        break;

                        case CommandType.UpdateVoIPData:
                        {
                            if (!Settings.Instance.Server.AllowVoiceChat)
                            {
                                return;
                            }

                            if (client != null)
                            {
                                UnityVOIP.VoipFragment data = new UnityVOIP.VoipFragment(msg);
                                if (data.playerId == client.playerInfo.playerId)
                                {
                                    client.playerVoIPQueue.Enqueue(data);
                                }
                            }
                        }
                        break;

                        case CommandType.JoinRoom:
                        {
                            if (client != null)
                            {
                                uint roomId = msg.ReadUInt32();

                                BaseRoom room = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == roomId);

                                if (room != null)
                                {
                                    if (room.roomSettings.UsePassword)
                                    {
                                        if (RoomsController.ClientJoined(client, roomId, msg.ReadString()))
                                        {
                                            if (hubClients.Contains(client))
                                            {
                                                hubClients.Remove(client);
                                            }
                                            client.joinedRoomID = roomId;
                                        }
                                    }
                                    else
                                    {
                                        if (RoomsController.ClientJoined(client, roomId, ""))
                                        {
                                            if (hubClients.Contains(client))
                                            {
                                                hubClients.Remove(client);
                                            }
                                            client.joinedRoomID = roomId;
                                        }
                                    }
                                }
                                else
                                {
                                    RoomsController.ClientJoined(client, roomId, "");
                                }
                            }
                        }
                        break;

                        case CommandType.LeaveRoom:
                        {
                            if (client != null)
                            {
                                RoomsController.ClientLeftRoom(client);
                                client.joinedRoomID = 0;
                                client.playerInfo.updateInfo.playerState = PlayerState.Lobby;
                                if (!hubClients.Contains(client))
                                {
                                    hubClients.Add(client);
                                }
                            }
                        }
                        break;

                        case CommandType.GetRooms:
                        {
                            NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                            outMsg.Write((byte)CommandType.GetRooms);
                            RoomsController.AddRoomListToMessage(outMsg);

                            msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                            Program.networkBytesOutNow += outMsg.LengthBytes;
                        }
                        break;

                        case CommandType.CreateRoom:
                        {
                            if (client != null)
                            {
                                uint roomId = RoomsController.CreateRoom(new RoomSettings(msg), client.playerInfo);

                                NetOutgoingMessage outMsg = ListenerServer.CreateMessage(5);
                                outMsg.Write((byte)CommandType.CreateRoom);
                                outMsg.Write(roomId);

                                msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                Program.networkBytesOutNow += outMsg.LengthBytes;
                            }
                        }
                        break;

                        case CommandType.GetRoomInfo:
                        {
                            if (client != null)
                            {
#if DEBUG
                                Logger.Instance.Log("GetRoomInfo: Client room=" + client.joinedRoomID);
#endif
                                if (client.joinedRoomID != 0)
                                {
                                    BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                    if (joinedRoom != null)
                                    {
                                        NetOutgoingMessage outMsg = ListenerServer.CreateMessage();

                                        outMsg.Write((byte)CommandType.GetRoomInfo);

                                        joinedRoom.GetRoomInfo().AddToMessage(outMsg);

                                        msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                        Program.networkBytesOutNow += outMsg.LengthBytes;
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.SetSelectedSong:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    if (msg.LengthBytes < 16)
                                    {
                                        joinedRoom.SetSelectedSong(client.playerInfo, null);
                                    }
                                    else
                                    {
                                        joinedRoom.SetSelectedSong(client.playerInfo, new SongInfo(msg));
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.RequestSong:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    if (msg.LengthBytes > 16)
                                    {
                                        joinedRoom.RequestSong(client.playerInfo, new SongInfo(msg));
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.RemoveRequestedSong:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    if (msg.LengthBytes > 16)
                                    {
                                        joinedRoom.RemoveRequestedSong(client.playerInfo, new SongInfo(msg));
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.SetLevelOptions:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.SetLevelOptions(client.playerInfo, new LevelOptionsInfo(msg));
                                }
                            }
                        }
                        break;

                        case CommandType.StartLevel:
                        {
#if DEBUG
                            Logger.Instance.Log("Received command StartLevel");
#endif

                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    LevelOptionsInfo options = new LevelOptionsInfo(msg);
                                    SongInfo         song    = new SongInfo(msg);
                                    song.songDuration += 2.5f;
                                    joinedRoom.StartLevel(client.playerInfo, options, song);
                                }
                            }
                        }
                        break;

                        case CommandType.DestroyRoom:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.DestroyRoom(client.playerInfo);
                                }
                            }
                        }
                        break;

                        case CommandType.TransferHost:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.TransferHost(client.playerInfo, new PlayerInfo(msg));
                                }
                            }
                        }
                        break;

                        case CommandType.PlayerReady:
                        {
                            if (client != null && client.joinedRoomID != 0)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    joinedRoom.ReadyStateChanged(client.playerInfo, msg.ReadBoolean());
                                }
                            }
                        }
                        break;

                        case CommandType.SendEventMessage:
                        {
                            if (client != null && client.joinedRoomID != 0 && Settings.Instance.Server.AllowEventMessages)
                            {
                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                if (joinedRoom != null)
                                {
                                    string header = msg.ReadString();
                                    string data   = msg.ReadString();

                                    joinedRoom.BroadcastEventMessage(header, data, new List <Client>()
                                            {
                                                client
                                            });
                                    joinedRoom.BroadcastWebSocket(CommandType.SendEventMessage, new EventMessage(header, data));

                                    EventMessageReceived?.Invoke(client, header, data);
#if DEBUG
                                    Logger.Instance.Log($"Received event message! Header=\"{header}\", Data=\"{data}\"");
#endif
                                }
                            }
                        }
                        break;

                        case CommandType.GetChannelInfo:
                        {
                            if (Settings.Instance.Radio.EnableRadio && RadioController.radioStarted)
                            {
                                int channelId = msg.ReadInt32();

                                NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                                outMsg.Write((byte)CommandType.GetChannelInfo);

                                if (RadioController.radioChannels.Count > channelId)
                                {
                                    RadioController.radioChannels[channelId].channelInfo.AddToMessage(outMsg);
                                }
                                else
                                {
                                    new ChannelInfo()
                                    {
                                        channelId = -1, currentSong = new SongInfo()
                                        {
                                            levelId = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
                                        }
                                    }.AddToMessage(outMsg);
                                }

                                msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                Program.networkBytesOutNow += outMsg.LengthBytes;
                            }
                        }
                        break;

                        case CommandType.JoinChannel:
                        {
                            int channelId = msg.ReadInt32();

                            NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                            outMsg.Write((byte)CommandType.JoinChannel);

                            if (RadioController.ClientJoinedChannel(client, channelId))
                            {
                                outMsg.Write((byte)0);
                                hubClients.Remove(client);
                            }
                            else
                            {
                                outMsg.Write((byte)1);
                            }

                            msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                            Program.networkBytesOutNow += outMsg.LengthBytes;
                        }
                        break;

                        case CommandType.GetSongDuration:
                        {
                            foreach (RadioChannel channel in RadioController.radioChannels)
                            {
                                if (channel.radioClients.Contains(client) && channel.requestingSongDuration)
                                {
                                    SongInfo info = new SongInfo(msg);
                                    if (info.levelId == channel.channelInfo.currentSong.levelId)
                                    {
                                        channel.songDurationResponses.TryAdd(client, info.songDuration);
                                    }
                                }
                            }
                        }
                        break;

                        case CommandType.LeaveChannel:
                        {
                            if (RadioController.radioStarted && client != null)
                            {
                                RadioController.ClientLeftChannel(client);
                            }
                        }; break;
                        }
                    };
                        break;



                    case NetIncomingMessageType.WarningMessage:
                        Logger.Instance.Warning(msg.ReadString());
                        break;

                    case NetIncomingMessageType.ErrorMessage:
                        Logger.Instance.Error(msg.ReadString());
                        break;

                    case NetIncomingMessageType.StatusChanged:
                    {
                        NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();

                        Client client = allClients.FirstOrDefault(x => x.playerConnection.RemoteEndPoint.Equals(msg.SenderEndPoint));

                        if (client != null)
                        {
                            if (status == NetConnectionStatus.Disconnected)
                            {
                                allClients.Remove(client);
                                ClientDisconnected(client);
                            }
                        }
                    }
                    break;

#if DEBUG
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.DebugMessage:
                        Logger.Instance.Log(msg.ReadString());
                        break;

                    default:
                        Logger.Instance.Log("Unhandled message type: " + msg.MessageType);
                        break;
#endif
                    }
                }catch (Exception ex)
                {
                    Logger.Instance.Log($"Exception on message received: {ex}");
                }
                ListenerServer.Recycle(msg);
            }
        }
Example #23
0
        private SongInfo GetFromPlayer(IList<SongInfo> result)
        {
            IntPtr hwnd = IntPtr.Zero;
            hwnd = this.GetWindowHandle(hwnd);
            if (hwnd == IntPtr.Zero) return null;

            SongInfo si = new SongInfo(this);
            si.Handle = hwnd;

            // 파이프 : 성공시 return
            if ((this.ParseFlag & ParseFlags.Pipe) == ParseFlags.Pipe)
            {
                App.Debug("Pipe Parse");

                if (this.GetTagsFromPipe(si))
                    if (IParseRule.AddToList(result, si))
                        return si;

                return null;
            }

            // 추가 파싱 : 성공하면 Return
            if ((this.ParseFlag & ParseFlags.ManualParse) == ParseFlags.ManualParse)
            {
                App.Debug("Manual Parse");
                if (this.ParseManual(si, hwnd))
                    if (IParseRule.AddToList(result, si))
                        return si;

                return null;
            }

            // 핸들 체크 (윈도우가 여러개 감지되면 각각 따로 작업합니다)
            if ((this.ParseFlag & ParseFlags.Title) == ParseFlags.Title)
            {
                bool first = true;
                do
                {
                    App.Debug("Handle : {0} : 0x{1:X8}", this.WndClass, hwnd);

                    if (!first)
                    {
                        si = new SongInfo(this);
                        si.Handle = hwnd;
                    }
                    first = false;

                    // 타이틀 파싱 : 성공하면 Return
                    if (this.GetTagsFromTitle(si, hwnd))
                        IParseRule.AddToList(result, si);

                }
                while ((hwnd = this.GetWindowHandle(hwnd)) != IntPtr.Zero);
            }

            return si;
        }
Example #24
0
        private static bool AddToList(IList<SongInfo> result, SongInfo si)
        {
            IParseRule.GetTagsFromFile(si);

            if (!string.IsNullOrWhiteSpace(si.Title))
            {
                if (result != null)
                    lock (result)
                        result.Add(si);
                return true;
            }
            return false;
        }
Example #25
0
 /// <summary>
 /// FindWindow 를 사용하지 않고 별도의 작업을 통해 재생정보를 가져옵니다
 /// 주로 SDK나 API를 이용할 때 사용합니다
 /// ParseFlag 에 ParseFlags.Get 플래그가 지정되야 합니다
 /// </summary>
 /// <param name="hwnd">찾은 윈도우 핸들 (선택)</param>
 public virtual bool ParseManual(SongInfo si, IntPtr hwnd)
 {
     return false;
 }
Example #26
0
        public MenuContext(ServerContextBase previousContext, PPDServer server)
            : base(previousContext)
        {
            this.server = server;
            version     = FileVersionInfo.GetVersionInfo(Assembly.GetAssembly(this.GetType()).Location).FileVersion;

            kickedIPs   = new List <string>();
            userList    = new List <UserInfo>();
            currentRule = new GameRule();

            stopWatch = new Stopwatch();
            stopWatch.Start();

            AddProcessor <AddUserNetworkData>(networkData =>
            {
                if (networkData.Version != version)
                {
                    Host.Write(MessagePackSerializer.Serialize(new CloseConnectNetworkData {
                        Reason = CloseConnectReason.VersionDifference
                    }), networkData.Id);
                    return;
                }
                else if (userList.Count == 16)
                {
                    Host.Write(MessagePackSerializer.Serialize(new CloseConnectNetworkData {
                        Reason = CloseConnectReason.MaximumCapacity
                    }), networkData.Id);
                    return;
                }
                else if (kickedIPs.Contains(networkData.Ip))
                {
                    Host.Write(MessagePackSerializer.Serialize(new CloseConnectNetworkData {
                        Reason = CloseConnectReason.Kicked
                    }), networkData.Id);
                    return;
                }

                Host.Write(MessagePackSerializer.Serialize(new SendServerInfoNetworkData {
                    Id = networkData.Id, AllowedModIds = server.AllowedModIds
                }), networkData.Id);
                if (currentSong != null)
                {
                    Host.Write(MessagePackSerializer.Serialize(new ChangeSongNetworkData {
                        Hash = currentSong.Hash, Difficulty = currentSong.Difficulty
                    }), networkData.Id);
                }
                Host.Write(MessagePackSerializer.Serialize(new ChangeGameRuleNetworkData {
                    GameRule = currentRule
                }), networkData.Id);

                foreach (UserInfo tempUser in userList)
                {
                    Host.Write(MessagePackSerializer.Serialize(new AddUserNetworkData
                    {
                        Id        = tempUser.ID,
                        UserName  = tempUser.Name,
                        AccountId = tempUser.AccountId,
                        State     = tempUser.CurrentState,
                    }), networkData.Id);
                }

                var user = AddUser((AddUserNetworkData)networkData);
                Host.WriteExceptID(MessagePackSerializer.Serialize(new AddUserNetworkData
                {
                    Id        = user.ID,
                    UserName  = user.Name,
                    AccountId = user.AccountId,
                    State     = user.CurrentState,
                }), user.ID);
                Host.Write(MessagePackSerializer.Serialize(new ChangeLeaderNetworkData {
                    UserId = Leader.ID
                }), user.ID);
                if (ContextManager.Logger != null)
                {
                    ContextManager.Logger.AddLog(String.Format("{0}({1}) joined", user.Name, user.AccountId));
                }
            });
            AddProcessor <DeleteUserNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null)
                {
                    DeleteUser(user);
                    Host.Write(MessagePackSerializer.Serialize(new DeleteUserNetworkData {
                        Id = user.ID
                    }));
                    SendCommonSongInfo();
                    if (ContextManager.Logger != null)
                    {
                        ContextManager.Logger.AddLog(String.Format("{0}({1}) leaved", user.Name, user.AccountId));
                    }
                }
            });
            AddProcessor <AddMessageNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null)
                {
                    Host.WriteExceptID(MessagePackSerializer.Serialize(new AddMessageNetworkData {
                        Message = networkData.Message, Id = user.ID
                    }), user.ID);
                    if (ContextManager.Logger != null)
                    {
                        ContextManager.Logger.AddLog(String.Format("{0}({1}) said '{2}'", user.Name, user.AccountId, networkData.Message));
                    }
                }
            });
            AddProcessor <AddPrivateMessageNetworkData>(networkData =>
            {
                var user       = FindUser(networkData.Id);
                var targetUser = FindUser(networkData.UserId);
                if (user != null && targetUser != null)
                {
                    Host.Write(MessagePackSerializer.Serialize(new AddPrivateMessageNetworkData
                    {
                        Message = networkData.Message,
                        Id      = networkData.Id,
                        UserId  = networkData.UserId
                    }), networkData.UserId);
                    if (ContextManager.Logger != null)
                    {
                        ContextManager.Logger.AddLog(String.Format("{0}({1}) said to {2}({3}) '{4}'", user.Name, user.AccountId,
                                                                   targetUser.Name, targetUser.AccountId, networkData.Message));
                    }
                }
            });
            AddProcessor <ChangeUserStateNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null)
                {
                    user.CurrentState = networkData.State;
                    Host.WriteExceptID(MessagePackSerializer.Serialize(new ChangeUserStateNetworkData {
                        State = user.CurrentState, Id = user.ID
                    }), user.ID);
                }
            });
            AddProcessor <HasSongNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null)
                {
                    user.HasSong = true;
                    Host.WriteExceptID(MessagePackSerializer.Serialize(new HasSongNetworkData {
                        Id = networkData.Id
                    }), user.ID);
                }
            });
            AddProcessor <FailedToCreateRoomNetworkData>(networkData =>
            {
                ContextManager.OnFailedToCreateRoom();
                if (ContextManager.Logger != null)
                {
                    ContextManager.Logger.AddLog("Failed to create room");
                }
            });
            AddProcessor <ChangeGameRuleNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null && user.IsLeader)
                {
                    if (state == State.None)
                    {
                        currentRule = networkData.GameRule;
                        Host.Write(MessagePackSerializer.Serialize(new ChangeGameRuleNetworkData {
                            GameRule = currentRule
                        }));
                        if (ContextManager.Logger != null)
                        {
                            ContextManager.Logger.AddLog(String.Format("Rule was changed to {0}", currentRule));
                        }
                    }
                }
            });
            AddProcessor <ChangeSongNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null && user.IsLeader)
                {
                    if (state == State.None)
                    {
                        currentSong = new SongInfo {
                            Hash = networkData.Hash, Difficulty = networkData.Difficulty
                        };
                        foreach (var u in userList)
                        {
                            u.HasSong = false;
                        }
                        Host.Write(MessagePackSerializer.Serialize(new ChangeSongNetworkData {
                            Hash = networkData.Hash, Difficulty = networkData.Difficulty
                        }));
                        if (ContextManager.Logger != null)
                        {
                            ContextManager.Logger.AddLog(String.Format("Song was changed {0}({1})",
                                                                       GetStringArray(currentSong.Hash), currentSong.Difficulty));
                        }
                    }
                }
            });
            AddProcessor <PingNetworkData>(networkData =>
            {
                Host.Write(MessagePackSerializer.Serialize(new PingUserNetworkData {
                    Ping = (int)(stopWatch.ElapsedMilliseconds - networkData.Time), Id = networkData.Id
                }));
            });
            AddProcessor <ForceStartNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null && user.IsLeader)
                {
                    forceStart = true;
                    Host.Write(MessagePackSerializer.Serialize(new ForceStartNetworkData()));
                }
            });
            AddProcessor <SendScoreListNetworkData>(networkData =>
            {
                var user = FindUser(networkData.Id);
                if (user != null)
                {
                    user.SongInfos = networkData.SongInfos;
                    SendCommonSongInfo();
                }
            });
            AddProcessor <KickUserNetworkData>(networkData =>
            {
                var user       = FindUser(networkData.Id);
                var targetUser = FindUser(networkData.UserId);
                if (user != null && user.IsLeader && targetUser != null && targetUser != user)
                {
                    kickedIPs.Add(targetUser.Ip);
                    Host.Write(MessagePackSerializer.Serialize(new CloseConnectNetworkData {
                        Reason = CloseConnectReason.Kicked
                    }), targetUser.ID);
                    Host.WriteExceptID(MessagePackSerializer.Serialize(new KickUserNetworkData {
                        UserId = targetUser.ID
                    }), targetUser.ID);
                    DeleteUser(targetUser);
                    SendCommonSongInfo();
                    if (ContextManager.Logger != null)
                    {
                        ContextManager.Logger.AddLog(String.Format("{0}({1}) was kicked", targetUser.Name, targetUser.AccountId));
                    }
                }
            });
            AddProcessor <ChangeLeaderNetworkData>(networkData =>
            {
                var user       = FindUser(networkData.Id);
                var targetUser = FindUser(networkData.UserId);
                if (user != null && user.IsLeader && targetUser != null && targetUser != user)
                {
                    Host.Write(MessagePackSerializer.Serialize(new ChangeLeaderNetworkData {
                        UserId = targetUser.ID
                    }));
                    user.IsLeader       = false;
                    targetUser.IsLeader = true;
                    if (ContextManager.Logger != null)
                    {
                        ContextManager.Logger.AddLog(String.Format("Leader was changed to {0}({1})", targetUser.Name, targetUser.AccountId));
                    }
                }
            });
        }
Example #27
0
        protected override SongInfo Search(string keyword)
        {
            string result_str;

            try
            {
                result_str = Fetch(API_PROTOCOL, API_HOST, API_PATH + ServiceName + $"/search?keyword={HttpUtility.UrlEncode(keyword)}");
            }
            catch (Exception ex)
            {
                Log("搜索歌曲时网络错误:" + ex.Message);
                return(null);
            }

            JObject song = null;

            try
            {
                JObject info = JObject.Parse(result_str);
                if (info["code"].ToString() == "200")
                {
                    song = (info["result"] as JArray)?[0] as JObject;
                }
            }
            catch (Exception ex)
            {
                Log("搜索歌曲解析数据错误:" + ex.Message);
                return(null);
            }

            SongInfo songInfo;


            try
            {
                songInfo = new SongInfo(
                    this,
                    song["id"].ToString(),
                    song["name"].ToString(),
                    (song["artist"] as JArray).Select(x => x.ToString()).ToArray()
                    );
            }
            catch (Exception ex)
            { Log("歌曲信息获取结果错误:" + ex.Message); return(null); }

            try
            {
                JObject lobj = JObject.Parse(Fetch(API_PROTOCOL, API_HOST, API_PATH + ServiceName + $"/lyric?id={songInfo.Id}"));
                if (lobj["result"]["tlyric"] != null)
                {
                    songInfo.Lyric = lobj["result"]["tlyric"].ToString();
                }
                else if (lobj["result"]["lyric"] != null)
                {
                    songInfo.Lyric = lobj["result"]["lyric"].ToString();
                }
                else
                {
                    Log("歌词获取错误(id:" + songInfo.Id + ")");
                }
            }
            catch (Exception ex)
            { Log("歌词获取错误(ex:" + ex.ToString() + ",id:" + songInfo.Id + ")"); }

            return(songInfo);
        }
Example #28
0
        public async void RadioLoop(object sender, HighResolutionTimerElapsedEventArgs e)
        {
            if (randomSongTask != null)
            {
                return;
            }

            channelInfo.playerCount = radioClients.Count;
            channelInfo.name        = Settings.Instance.Radio.RadioChannels[channelId].ChannelName;
            channelInfo.iconUrl     = Settings.Instance.Radio.RadioChannels[channelId].ChannelIconUrl;

            if (radioClients.Count == 0)
            {
                channelInfo.state = ChannelState.NextSong;
                return;
            }

            NetOutgoingMessage outMsg = HubListener.ListenerServer.CreateMessage();

            switch (channelInfo.state)
            {
            case ChannelState.InGame:      //--> Results
            {
                if (DateTime.Now.Subtract(songStartTime).TotalSeconds >= channelInfo.currentSong.songDuration)
                {
                    channelInfo.state = ChannelState.Results;
                    resultsStartTime  = DateTime.Now;

                    outMsg.Write((byte)CommandType.GetChannelInfo);

                    outMsg.Write((byte)0);
                    channelInfo.AddToMessage(outMsg);

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);

                    if (radioClients.Count > 0)
                    {
                        BroadcastWebSocket(CommandType.GetChannelInfo, channelInfo);
                    }
                }
            }
            break;

            case ChannelState.Results:     //--> NextSong
            {
                if (DateTime.Now.Subtract(resultsStartTime).TotalSeconds >= Settings.Instance.Radio.ResultsShowTime)
                {
                    channelInfo.state = ChannelState.NextSong;

                    if (radioQueue.Count > 0)
                    {
                        channelInfo.currentSong = radioQueue.Dequeue();
                        try
                        {
                            File.WriteAllText($"RadioQueue{channelId}.json", JsonConvert.SerializeObject(radioQueue, Formatting.Indented));
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        if (defaultSongs.Count > 1)
                        {
                            channelInfo.currentSong = defaultSongs.Random(lastSong);
                        }
                        else
                        {
                            randomSongTask          = BeatSaver.GetRandomSong();
                            channelInfo.currentSong = await randomSongTask;
                            randomSongTask          = null;
                        }
                        lastSong = channelInfo.currentSong;
                    }

                    outMsg.Write((byte)CommandType.SetSelectedSong);
                    channelInfo.currentSong.AddToMessage(outMsg);

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);
                    nextSongScreenStartTime = DateTime.Now;

                    if (radioClients.Count > 0)
                    {
                        BroadcastWebSocket(CommandType.SetSelectedSong, channelInfo.currentSong);
                    }
                }
            }
            break;

            case ChannelState.NextSong:      //--> InGame
            {
                if (DateTime.Now.Subtract(nextSongScreenStartTime).TotalSeconds >= Settings.Instance.Radio.NextSongPrepareTime)
                {
                    channelInfo.state = ChannelState.InGame;

                    outMsg.Write((byte)CommandType.StartLevel);
                    //outMsg.Write((byte)Settings.Instance.Radio.RadioChannels[channelId].PreferredDifficulty);
                    channelInfo.currentLevelOptions.AddToMessage(outMsg);

                    channelInfo.currentSong.songDuration = Misc.Math.Median(songDurationResponses.Values.ToArray());
                    songDurationResponses.Clear();
                    requestingSongDuration = false;

                    channelInfo.currentSong.AddToMessage(outMsg);

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);
                    songStartTime = DateTime.Now;

                    if (radioClients.Count > 0)
                    {
                        BroadcastWebSocket(CommandType.StartLevel, new SongWithOptions(channelInfo.currentSong, channelInfo.currentLevelOptions));
                    }
                }
                else if (DateTime.Now.Subtract(nextSongScreenStartTime).TotalSeconds >= Settings.Instance.Radio.NextSongPrepareTime * 0.75 && !requestingSongDuration)
                {
                    outMsg.Write((byte)CommandType.GetSongDuration);
                    channelInfo.currentSong.AddToMessage(outMsg);
                    songDurationResponses.Clear();
                    requestingSongDuration = true;

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);

                    if (radioClients.Count > 0)
                    {
                        BroadcastWebSocket(CommandType.GetSongDuration, channelInfo.currentSong);
                    }
                }
            }
            break;
            }

            if (outMsg.LengthBytes > 0)
            {
                outMsg = HubListener.ListenerServer.CreateMessage();
            }

            outMsg.Write((byte)CommandType.UpdatePlayerInfo);

            switch (channelInfo.state)
            {
            case ChannelState.NextSong:
            {
                outMsg.Write((float)DateTime.Now.Subtract(nextSongScreenStartTime).TotalSeconds);
                outMsg.Write(Settings.Instance.Radio.NextSongPrepareTime);
            }
            break;

            case ChannelState.InGame:
            {
                outMsg.Write((float)DateTime.Now.Subtract(songStartTime).TotalSeconds);
                outMsg.Write(channelInfo.currentSong.songDuration);
            }
            break;

            case ChannelState.Results:
            {
                outMsg.Write((float)DateTime.Now.Subtract(resultsStartTime).TotalSeconds);
                outMsg.Write(Settings.Instance.Radio.ResultsShowTime);
            }
            break;
            }

            bool fullUpdate = false;

            int i = 0;

            for (i = 0; i < radioClients.Count; i++)
            {
                if (i < radioClients.Count)
                {
                    if (radioClients[i] != null)
                    {
                        fullUpdate |= radioClients[i].lastUpdateIsFull;
                        radioClients[i].lastUpdateIsFull = false;
                    }
                }
            }

            outMsg.Write(fullUpdate ? (byte)1 : (byte)0);

            outMsg.Write(radioClients.Count);

            if (fullUpdate)
            {
                for (i = 0; i < radioClients.Count; i++)
                {
                    if (i < radioClients.Count)
                    {
                        if (radioClients[i] != null)
                        {
                            outMsg.Write(radioClients[i].playerInfo.playerId);
                        }
                    }
                    radioClients[i].playerInfo.AddToMessage(outMsg);
                }
            }
            else
            {
                for (i = 0; i < radioClients.Count; i++)
                {
                    if (i < radioClients.Count)
                    {
                        if (radioClients[i] != null)
                        {
                            outMsg.Write(radioClients[i].playerInfo.playerId);
                            radioClients[i].playerInfo.updateInfo.AddToMessage(outMsg);
                            outMsg.Write((byte)radioClients[i].playerInfo.hitsLastUpdate.Count);
                            foreach (var hit in radioClients[i].playerInfo.hitsLastUpdate)
                            {
                                hit.AddToMessage(outMsg);
                            }
                            radioClients[i].playerInfo.hitsLastUpdate.Clear();
                        }
                    }
                }
            }

            BroadcastPacket(outMsg, NetDeliveryMethod.UnreliableSequenced);

            if (radioClients.Count > 0)
            {
                BroadcastWebSocket(CommandType.UpdatePlayerInfo, radioClients.Select(x => x.playerInfo).ToArray());
            }
        }
Example #29
0
        private bool GetTagsFromPipe(SongInfo si, string data = null)
        {
            App.Debug("Pipe");
            if (data == null)
                data = this.GetDataFromPipe();

            if (data != null)
            {
                App.Debug(data);

                var split = data.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);

                int sep;
                uint num;
                string key, val;
                for (int read = 0; read < split.Length; ++read)
                {
                    if ((sep = split[read].IndexOf('=')) > 0)
                    {
                        key = split[read].Substring(0, sep).Trim();
                        val = split[read].Substring(sep + 1).Trim();

                        if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(val) || key == "?")
                            continue;

                        switch (key.ToLower())
                        {
                            case "title":  si.Title  = val; break;
                            case "album":  si.Album  = val; break;
                            case "artist": si.Artist = val; break;

                            // 확장 태그들
                            case "track":  if (uint.TryParse(val, out num)) si.Track  = num; break;
                            case "ttrack": if (uint.TryParse(val, out num)) si.TTrack = num; break;
                            case "disc":   if (uint.TryParse(val, out num)) si.Disc   = num; break;
                            case "tdisc":  if (uint.TryParse(val, out num)) si.TDisc  = num; break;
                            case "year":   if (uint.TryParse(val, out num)) si.Year   = num; break;
                            case "genre":  si.Genre  = val; break;

                            case "path":   si.Local  = val; break;
                            case "cover":  si.Cover  = new MemoryStream(Convert.FromBase64String(val)); si.Cover.Position = 0; break;
                            case "handle": si.Handle = new IntPtr(long.Parse(val)); break;
                        }
                    }
                }
                return true;
            }

            return false;
        }
        private void MessageReceived(NetIncomingMessage msg)
        {
            if (msg == null)
            {
                InGameOnlineController.Instance.needToSendUpdates = false;

                PopAllViewControllers();
                InGameOnlineController.Instance.DestroyPlayerControllers();
                PreviewPlayer.CrossfadeToDefault();
                joined = false;

                _radioNavController.DisplayError("Lost connection to the ServerHub!");
                return;
            }

            CommandType commandType = (CommandType)msg.ReadByte();

            if (!joined)
            {
                if (commandType == CommandType.JoinChannel)
                {
                    switch (msg.ReadByte())
                    {
                    case 0:
                    {
                        Client.Instance.playerInfo.playerState = PlayerState.Room;
                        Client.Instance.RequestChannelInfo(channelId);
                        Client.Instance.SendPlayerInfo();
                        joined = true;
                        InGameOnlineController.Instance.needToSendUpdates = true;
                    }
                    break;

                    case 1:
                    {
                        _radioNavController.DisplayError("Unable to join channel!\nChannel not found");
                    }
                    break;

                    default:
                    {
                        _radioNavController.DisplayError("Unable to join channel!\nUnknown error");
                    }
                    break;
                    }
                }
            }
            else
            {
                try
                {
                    switch (commandType)
                    {
                    case CommandType.GetChannelInfo:
                    {
                        channelInfo      = new ChannelInfo(msg);
                        channelInfo.ip   = ip;
                        channelInfo.port = port;

                        UpdateUI(channelInfo.state);
                    }
                    break;

                    case CommandType.SetSelectedSong:
                    {
                        if (msg.LengthBytes > 16)
                        {
                            SongInfo song = new SongInfo(msg);
                            channelInfo.currentSong = song;
                            channelInfo.state       = ChannelState.NextSong;

                            UpdateUI(channelInfo.state);
                        }
                    }
                    break;

                    case CommandType.GetSongDuration:
                    {
                        SongInfo       requestedSong = new SongInfo(msg);
                        BeatmapLevelSO level         = SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(channelInfo.currentSong.levelId)) as BeatmapLevelSO;

                        if (level != null)
                        {
                            SongLoader.Instance.LoadAudioClipForLevel((CustomLevel)level,
                                                                      (loadedLevel) =>
                                {
                                    Client.Instance.SendSongDuration(new SongInfo(loadedLevel));
                                });
                        }
                    }
                    break;

                    case CommandType.StartLevel:
                    {
                        if (Client.Instance.playerInfo.playerState == PlayerState.DownloadingSongs)
                        {
                            return;
                        }

                        if (nextSongSkipped)
                        {
                            nextSongSkipped   = false;
                            channelInfo.state = ChannelState.InGame;
                            UpdateUI(channelInfo.state);
                            return;
                        }

                        LevelOptionsInfo levelInfo = new LevelOptionsInfo(msg);

                        BeatmapCharacteristicSO characteristic = _beatmapCharacteristics.First(x => x.serializedName == levelInfo.characteristicName);

                        SongInfo       songInfo = new SongInfo(msg);
                        BeatmapLevelSO level    = SongLoader.CustomBeatmapLevelPackCollectionSO.beatmapLevelPacks.SelectMany(x => x.beatmapLevelCollection.beatmapLevels).FirstOrDefault(x => x.levelID.StartsWith(songInfo.levelId)) as BeatmapLevelSO;

                        if (level == null)
                        {
                            Plugin.log.Error("Unable to start level! Level is null! LevelID=" + songInfo.levelId);
                            return;
                        }

                        SongLoader.Instance.LoadAudioClipForLevel((CustomLevel)level,
                                                                  (levelLoaded) =>
                            {
                                try
                                {
                                    BS_Utils.Gameplay.Gamemode.NextLevelIsIsolated("Beat Saber Multiplayer");
                                }
                                catch
                                {
                                }

                                StartLevel(levelLoaded, characteristic, levelInfo.difficulty, levelInfo.modifiers);
                            });
                    }
                    break;

                    case CommandType.LeaveRoom:
                    {
                        LeaveChannel();
                    }
                    break;

                    case CommandType.UpdatePlayerInfo:
                    {
                        if (channelInfo != null)
                        {
                            currentTime = msg.ReadFloat();
                            totalTime   = msg.ReadFloat();

                            switch (channelInfo.state)
                            {
                            case ChannelState.InGame:
                                UpdateInGameScreen();
                                break;

                            case ChannelState.NextSong:
                                UpdateNextSongScreen();
                                break;

                            case ChannelState.Results:
                            {
                                UpdateResultsScreen();

                                int playersCount = msg.ReadInt32();

                                List <PlayerInfo> playerInfos = new List <PlayerInfo>();

                                try
                                {
                                    for (int j = 0; j < playersCount; j++)
                                    {
                                        playerInfos.Add(new PlayerInfo(msg));
                                    }
                                }
                                catch (Exception e)
                                {
#if DEBUG
                                    Plugin.log.Critical($"Unable to parse PlayerInfo! Excpetion: {e}");
#endif
                                    return;
                                }

                                playerInfos = playerInfos.Where(x => x.playerScore > 0 && (x.playerState == PlayerState.Game || x.playerState == PlayerState.Room)).ToList();
                            }
                            break;
                            }
                        }
                    }
                    break;

                    case CommandType.Disconnect:
                    {
                        InGameOnlineController.Instance.needToSendUpdates = false;

                        if (msg.LengthBytes > 3)
                        {
                            string reason = msg.ReadString();

                            PopAllViewControllers();
                            InGameOnlineController.Instance.DestroyPlayerControllers();
                            PreviewPlayer.CrossfadeToDefault();
                            joined = false;

                            _radioNavController.DisplayError(reason);
                        }
                        else
                        {
                            _radioNavController.DisplayError("ServerHub refused connection!");
                        }
                    }
                    break;
                    }
                }
                catch (Exception e)
                {
                    Plugin.log.Error($"Unable to parse packet! Packet={commandType}, DataLength={msg.LengthBytes}\nException: {e}");
                }
            }
        }
Example #31
0
        private void LoadSong(SongInfo i_Song)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                progressBar1.Visibility = System.Windows.Visibility.Collapsed;
                TextBox_SongTitle.IsEnabled = true;
                Slider.IsEnabled = true;
                //slider2.IsEnabled = true;
                Button_PlayPause.IsEnabled = true;
                Button_Ringify.IsEnabled = true;
                Button_Cancel.IsEnabled = true;

                //Load Song
                WavFile WAV = new WavFile();
                MP3File MP3 = new MP3File();

                if (WAV.Initialize(Strings.Directory_Songs + "/" + App.ViewModel.SelectedSong.SongTitle))
                {
                    Song = WAV;
                }
                else if (MP3.Initialize(Strings.Directory_Songs + "/" + App.ViewModel.SelectedSong.SongTitle))
                {
                    Song = MP3;
                    if (MP3.m_MetaData != null && MP3.m_MetaData.m_Image != null)
                    {
                        BitmapImage Test = new BitmapImage();
                        Test.SetSource(MP3.m_MetaData.m_Image);
                        image1.Source = Test;
                        //image1.Visibility = System.Windows.Visibility.Visible;
                    }
                }
                else
                {
                    MessageBox.Show("The selected song is not supported as a Ringtone at the current time.");
                    Debugger.Trace("Unknown file format");
                }

                if (Song != null)
                {
                    string SongLength = Song.Length.Minutes + ":" + Song.Length.Seconds;
                    TextBlock_SongLength.Text = SongLength;
                    TextBox_EndPosition.Text = SongLength;
                    Slider.Maximum =  Song.Length.TotalSeconds;
                    Slider.RangeEnd = 39;
                }
                else
                {
                    NavigationService.GoBack();
                }
            });
        }
Example #32
0
 /// <summary>
 /// SongInfo 포메팅 전에 호출됩니다.
 /// </summary>
 public virtual void Edit(SongInfo si)
 {
 }
        public virtual void RoomLoop(object sender, HighResolutionTimerElapsedEventArgs e)
        {
            NetOutgoingMessage outMsg = HubListener.ListenerServer.CreateMessage();

            switch (roomState)
            {
            case RoomState.InGame:
            {
                if ((DateTime.Now.Subtract(_songStartTime).TotalSeconds >= selectedSong.songDuration) ||
                    (DateTime.Now.Subtract(_songStartTime).TotalSeconds >= 10f && roomClients.All(x => x.playerInfo.updateInfo.playerState != PlayerState.Game)))
                {
                    roomState         = RoomState.Results;
                    _resultsStartTime = DateTime.Now;

                    outMsg.Write((byte)CommandType.GetRoomInfo);
                    GetRoomInfo().AddToMessage(outMsg);

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered, 0);

                    if (roomClients.Count > 0)
                    {
                        BroadcastWebSocket(CommandType.GetRoomInfo, GetRoomInfo());
                    }
                }
            }
            break;

            case RoomState.Results:
            {
                if (DateTime.Now.Subtract(_resultsStartTime).TotalSeconds >= roomSettings.ResultsShowTime)
                {
                    roomState    = RoomState.SelectingSong;
                    selectedSong = null;

                    outMsg.Write((byte)CommandType.SetSelectedSong);
                    outMsg.Write((int)0);

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                    BroadcastWebSocket(CommandType.SetSelectedSong, null);
                }
            }
            break;

            case RoomState.SelectingSong:
            {
                switch (roomSettings.SelectionType)
                {
                case SongSelectionType.Random:
                {
                    if (!requestedRandomSong && roomClients.Count > 0 && roomClients.Any(x => roomHost.Equals(x.playerInfo)))
                    {
                        requestedRandomSong = true;

                        outMsg.Write((byte)CommandType.GetRandomSongInfo);

                        roomClients.First(x => roomHost.Equals(x.playerInfo)).playerConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);

                        BroadcastWebSocket(CommandType.GetRandomSongInfo, null);
                    }
                }
                break;
                }
            }
            break;
            }

            if (outMsg.LengthBytes > 0)
            {
                outMsg = HubListener.ListenerServer.CreateMessage();
            }

            outMsg.Write((byte)CommandType.UpdatePlayerInfo);

            switch (roomState)
            {
            case RoomState.SelectingSong:
            {
                outMsg.Write((float)0);
                outMsg.Write((float)0);
            }
            break;

            case RoomState.Preparing:
            {
                outMsg.Write((float)0);
                outMsg.Write((float)0);
            }
            break;

            case RoomState.InGame:
            {
                outMsg.Write((float)DateTime.Now.Subtract(_songStartTime).TotalSeconds);
                outMsg.Write(selectedSong.songDuration);
            }
            break;

            case RoomState.Results:
            {
                outMsg.Write((float)DateTime.Now.Subtract(_resultsStartTime).TotalSeconds);
                outMsg.Write(roomSettings.ResultsShowTime);
            }
            break;
            }


            bool fullUpdate = false;

            int i = 0;

            for (i = 0; i < roomClients.Count; i++)
            {
                if (i < roomClients.Count)
                {
                    if (roomClients[i] != null)
                    {
                        if (roomClients[i].playerInfo.Equals(roomHost) && roomClients[i].playerInfo.updateInfo.playerNameColor.Equals(Color32.defaultColor))
                        {
                            roomClients[i].playerInfo.updateInfo.playerNameColor = Color32.roomHostColor;
                        }
                        fullUpdate |= roomClients[i].lastUpdateIsFull;
                        roomClients[i].lastUpdateIsFull = false;
                    }
                }
            }

            outMsg.Write(fullUpdate ? (byte)1 : (byte)0);

            outMsg.Write(roomClients.Count);

            if (fullUpdate)
            {
                for (i = 0; i < roomClients.Count; i++)
                {
                    if (i < roomClients.Count)
                    {
                        if (roomClients[i] != null)
                        {
                            outMsg.Write(roomClients[i].playerInfo.playerId);
                        }
                    }
                    roomClients[i].playerInfo.AddToMessage(outMsg);
                }
            }
            else
            {
                for (i = 0; i < roomClients.Count; i++)
                {
                    if (i < roomClients.Count)
                    {
                        if (roomClients[i] != null)
                        {
                            outMsg.Write(roomClients[i].playerInfo.playerId);
                            roomClients[i].playerInfo.updateInfo.AddToMessage(outMsg);
                            outMsg.Write((byte)roomClients[i].playerInfo.hitsLastUpdate.Count);
                            foreach (var hit in roomClients[i].playerInfo.hitsLastUpdate)
                            {
                                hit.AddToMessage(outMsg);
                            }
                            roomClients[i].playerInfo.hitsLastUpdate.Clear();
                        }
                    }
                }
            }

            if (roomClients.Count > 0)
            {
                BroadcastPacket(outMsg, NetDeliveryMethod.UnreliableSequenced, 1);

                BroadcastWebSocket(CommandType.UpdatePlayerInfo, roomClients.Select(x => x.playerInfo).ToArray());

                spectatorInRoom = roomClients.Any(x => x.playerInfo.updateInfo.playerState == PlayerState.Spectating);
                if (spectatorInRoom)
                {
                    outMsg = HubListener.ListenerServer.CreateMessage();

                    outMsg.Write((byte)CommandType.GetPlayerUpdates);

                    outMsg.Write(roomClients.Count(x => x.playerInfo.updateInfo.playerState == PlayerState.Game && x.playerUpdateHistory.Count > 0));

                    for (i = 0; i < roomClients.Count; i++)
                    {
                        if (i < roomClients.Count)
                        {
                            if (roomClients[i] != null && roomClients[i].playerInfo.updateInfo.playerState == PlayerState.Game && roomClients[i].playerUpdateHistory.Count > 0)
                            {
                                outMsg.Write(roomClients[i].playerInfo.playerId);

                                int historyLength = roomClients[i].playerUpdateHistory.Count;
                                outMsg.Write((byte)historyLength);

                                for (int j = 0; j < historyLength; j++)
                                {
                                    roomClients[i].playerUpdateHistory.Dequeue().AddToMessage(outMsg);
                                }
                                roomClients[i].playerUpdateHistory.Clear();

                                int hitCount = roomClients[i].playerHitsHistory.Count;
                                outMsg.Write((byte)hitCount);

                                for (int j = 0; j < hitCount; j++)
                                {
                                    roomClients[i].playerHitsHistory[i].AddToMessage(outMsg);
                                }
                                roomClients[i].playerHitsHistory.Clear();
                            }
                        }
                    }

                    BroadcastPacket(outMsg, NetDeliveryMethod.UnreliableSequenced, 2, roomClients.Where(x => x.playerInfo.updateInfo.playerState != PlayerState.Spectating).ToList());
                }
            }
        }
Example #34
0
 /// <summary>
 /// 정규식을 사용하지 않고 별도로 파싱작업을 진행합니다
 /// </summary>
 /// <param name="title">창 타이틀</param>
 public virtual bool ParseTitle(SongInfo si, string title)
 {
     return false;
 }
Example #35
0
 public virtual void SetSelectable(SongInfo songInfo)
 {
 }
Example #36
0
        private static void GetTagsFromFile(SongInfo si)
        {
            // front.jpg
            // cover.jpg
            // (filename).jpg
            // (album).jpg

            if (!string.IsNullOrWhiteSpace(si.Local) && File.Exists(si.Local))
            {
                // From MP3Tag
                using (var abs = new Abstraction(si.Local))
                {
                    try
                    {
                        using (var file = TagLib.File.Create(abs))
                        {
                            var tag = file.Tag;

                            if (string.IsNullOrWhiteSpace(si.Album)  && !string.IsNullOrWhiteSpace(tag.Album)) si.Album  = tag.Album.Trim();
                            if (string.IsNullOrWhiteSpace(si.Title)  && !string.IsNullOrWhiteSpace(tag.Title)) si.Title  = tag.Title.Trim();
                            if (string.IsNullOrWhiteSpace(si.Artist))
                            {
                                // 아티스트 순서 변경
                                     if (!string.IsNullOrWhiteSpace(tag.JoinedPerformers))   si.Artist = tag.JoinedPerformers  .Trim(); // Track Artist
                                else if (!string.IsNullOrWhiteSpace(tag.JoinedAlbumArtists)) si.Artist = tag.JoinedAlbumArtists.Trim(); // Album Artist
                                else if (!string.IsNullOrWhiteSpace(tag.JoinedComposers))    si.Artist = tag.JoinedComposers   .Trim(); // Composers
                            }

                            // 추가 태그들
                            if (si.Track  == 0 && tag.Track      > 0) si.Track  = tag.Track;
                            if (si.TTrack == 0 && tag.TrackCount > 0) si.TTrack = tag.TrackCount;
                            if (si.Disc   == 0 && tag.Disc       > 0) si.Disc   = tag.Disc;
                            if (si.TDisc  == 0 && tag.DiscCount  > 0) si.TDisc  = tag.DiscCount;
                            if (si.Year   == 0 && tag.Year       > 0) si.Year   = tag.Year;
                            if (string.IsNullOrWhiteSpace(si.Genre) && !string.IsNullOrWhiteSpace(tag.JoinedGenres)) si.Genre = tag.JoinedGenres.Trim();

                            if (file.Tag.Pictures.Length > 0 && si.Cover == null)
                            {
                                si.Cover = new MemoryStream(file.Tag.Pictures[0].Data.Data, false);
                                si.Cover.Position = 0;
                            }
                        }
                    }
                    catch
                    { }
                }

                if (si.Cover == null)
                {
                    // From Directory
                    var path = Path.GetDirectoryName(si.Local);
                    var dirName = Path.GetFileName(path).ToLower();
                    var files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly);
                    string filename;

                    for (var i = 0; i < files.Length; ++i)
                    {
                        switch (Path.GetExtension(files[i]).ToLower())
                        {
                            case ".jpg":
                            case ".png":
                                break;
                            default:
                                continue;
                        }

                        filename = Path.GetFileNameWithoutExtension(files[i]).ToLower();
                        if (filename.IndexOf("cover") >= 0  ||
                            filename.IndexOf("front") >= 0  ||
                            filename.IndexOf(dirName) >= 0  ||
                            (!string.IsNullOrWhiteSpace(si.Title) && filename.IndexOf(si.Title) >= 0) ||
                            (!string.IsNullOrWhiteSpace(si.Album) && filename.IndexOf(si.Album) >= 0))
                            si.Cover = new FileStream(files[i], FileMode.Open, FileAccess.Read, FileShare.Read);
                    }
                }
            }
        }
        public string GenerateManifest(string dlcName, IList <Arrangement> arrangements, SongInfo songInfo, Platform platform)
        {
            var manifest = Manifest;

            manifest.Entries = new Dictionary <string, Dictionary <string, Attributes> >();
            bool firstarrangset = false;

            Arrangement vocal = null;

            if (arrangements.Any <Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal))
            {
                vocal = arrangements.Single <Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal);
            }

            var manifestFunctions = new ManifestFunctions(platform.version);
            var songPartition     = new SongPartition();

            foreach (var x in arrangements)
            {
                var isVocal = x.ArrangementType == Sng.ArrangementType.Vocal;
                var song    = (isVocal) ? null : Song.LoadFromFile(x.SongXml.File);

                var attribute = new Attributes();
                attribute.AlbumArt             = String.Format("urn:llid:{0}", AggregateGraph.AlbumArt.LLID);
                attribute.AlbumNameSort        = attribute.AlbumName = songInfo.Album;
                attribute.ArrangementName      = x.Name.ToString();
                attribute.ArtistName           = songInfo.Artist;
                attribute.ArtistNameSort       = songInfo.ArtistSort;
                attribute.AssociatedTechniques = new List <string>();
                //Should be 51 for bass, 49 for vocal and guitar
                attribute.BinaryVersion              = x.ArrangementType == Sng.ArrangementType.Bass ? 51 : 49;
                attribute.BlockAsset                 = String.Format("urn:emergent-world:{0}", AggregateGraph.XBlock.Name);
                attribute.ChordTemplates             = null;
                attribute.DISC_DLC_OTHER             = "Disc";
                attribute.DisplayName                = songInfo.SongDisplayName;
                attribute.DLCPreview                 = false;
                attribute.EffectChainMultiplayerName = string.Empty;
                attribute.EffectChainName            = isVocal ? "" : (dlcName + "_" + x.ToneBase == null ? "Default" : x.ToneBase.Replace(' ', '_'));
                attribute.EventFirstTimeSortOrder    = 9999;
                attribute.ExclusiveBuild             = new List <object>();
                attribute.FirstArrangementInSong     = false;
                if (isVocal && !firstarrangset)
                {
                    firstarrangset = true;
                    attribute.FirstArrangementInSong = true;
                }
                attribute.ForceUseXML            = true;
                attribute.Genre                  = "PLACEHOLDER Genre";
                attribute.InputEvent             = isVocal ? "Play_Tone_Standard_Mic" : "Play_Tone_";
                attribute.IsDemoSong             = false;
                attribute.IsDLC                  = true;
                attribute.LastConversionDateTime = "";
                int masterId = isVocal ? 1 : x.MasterId;
                attribute.MasterID_PS3              = masterId;
                attribute.MasterID_Xbox360          = masterId;
                attribute.MaxPhraseDifficulty       = 0;
                attribute.PersistentID              = x.Id.ToString().Replace("-", "").ToUpper();
                attribute.PhraseIterations          = new List <PhraseIteration>();
                attribute.Phrases                   = new List <Phrase>();
                attribute.PluckedType               = x.PluckedType == Sng.PluckedType.Picked ? "Picked" : "Not Picked";
                attribute.RelativeDifficulty        = isVocal ? 0 : song.Levels.Length;
                attribute.RepresentativeArrangement = false;
                attribute.Score_MaxNotes            = 0;
                attribute.Score_PNV                 = 0;
                attribute.Sections                  = new List <Section>();
                attribute.Shipping                  = true;
                attribute.SongAsset                 = String.Format("urn:llid:{0}", x.SongFile.LLID);
                attribute.SongEvent                 = String.Format("Play_{0}", dlcName);
                attribute.SongKey                   = dlcName;
                attribute.SongLength                = 0;
                attribute.SongName                  = songInfo.SongDisplayName;
                attribute.SongNameSort              = songInfo.SongDisplayNameSort;
                attribute.SongXml                   = String.Format("urn:llid:{0}", x.SongXml.LLID);
                attribute.SongYear                  = songInfo.SongYear;
                attribute.TargetScore               = 0;
                attribute.ToneUnlockScore           = 0;
                attribute.TwoHandTapping            = false;
                attribute.UnlockKey                 = "";
                attribute.Tuning         = x.Tuning;
                attribute.VocalsAssetId  = x.ArrangementType == Sng.ArrangementType.Vocal ? "" : (vocal != null) ? String.Format("{0}|GRSong_{1}", vocal.Id, vocal.Name) : "";
                attribute.ChordTemplates = new List <ChordTemplate>();
                manifestFunctions.GenerateDynamicVisualDensity(attribute, song, x, GameVersion.RS2012);

                if (!isVocal)
                {
                    #region "Associated Techniques"

                    attribute.PowerChords = song.HasPowerChords();
                    if (song.HasPowerChords())
                    {
                        AssociateTechniques(x, attribute, "PowerChords");
                    }
                    attribute.BarChords = song.HasBarChords();
                    if (song.HasBarChords())
                    {
                        AssociateTechniques(x, attribute, "BarChords");
                    }
                    attribute.OpenChords = song.HasOpenChords();
                    if (song.HasOpenChords())
                    {
                        AssociateTechniques(x, attribute, "ChordIntro");
                    }
                    attribute.DoubleStops = song.HasDoubleStops();
                    if (song.HasDoubleStops())
                    {
                        AssociateTechniques(x, attribute, "DoubleStops");
                    }
                    attribute.Sustain = song.HasSustain();
                    if (song.HasSustain())
                    {
                        AssociateTechniques(x, attribute, "Sustain");
                    }
                    attribute.Bends = song.HasBends();
                    if (song.HasBends())
                    {
                        AssociateTechniques(x, attribute, "Bends");
                    }
                    attribute.Slides = song.HasSlides();
                    if (song.HasSlides())
                    {
                        AssociateTechniques(x, attribute, "Slides");
                    }
                    attribute.Tremolo = song.HasTremolo();
                    if (song.HasTremolo())
                    {
                        AssociateTechniques(x, attribute, "Tremolo");
                    }
                    attribute.SlapAndPop = song.HasSlapAndPop();
                    if (song.HasSlapAndPop())
                    {
                        AssociateTechniques(x, attribute, "Slap");
                    }
                    attribute.Harmonics = song.HasHarmonics();
                    if (song.HasHarmonics())
                    {
                        AssociateTechniques(x, attribute, "Harmonics");
                    }
                    attribute.PalmMutes = song.HasPalmMutes();
                    if (song.HasPalmMutes())
                    {
                        AssociateTechniques(x, attribute, "PalmMutes");
                    }
                    attribute.HOPOs = song.HasHOPOs();
                    if (song.HasHOPOs())
                    {
                        AssociateTechniques(x, attribute, "HOPOs");
                    }
                    attribute.FretHandMutes = song.HasFretHandMutes();
                    if (song.HasFretHandMutes())
                    {
                        AssociateTechniques(x, attribute, "FretHandMutes");
                    }
                    attribute.DropDPowerChords = song.HasDropDPowerChords();
                    if (song.HasDropDPowerChords())
                    {
                        AssociateTechniques(x, attribute, "DropDPowerChords");
                    }
                    attribute.Prebends = song.HasPrebends();
                    if (song.HasPrebends())
                    {
                        AssociateTechniques(x, attribute, "Prebends");
                    }
                    attribute.Vibrato = song.HasVibrato();
                    if (song.HasVibrato())
                    {
                        AssociateTechniques(x, attribute, "Vibrato");
                    }

                    //Bass exclusive
                    attribute.TwoFingerPlucking = song.HasTwoFingerPlucking();
                    if (song.HasTwoFingerPlucking())
                    {
                        AssociateTechniques(x, attribute, "Plucking");
                    }
                    attribute.FifthsAndOctaves = song.HasFifthsAndOctaves();
                    if (song.HasFifthsAndOctaves())
                    {
                        AssociateTechniques(x, attribute, "Octave");
                    }
                    attribute.Syncopation = song.HasSyncopation();
                    if (song.HasSyncopation())
                    {
                        AssociateTechniques(x, attribute, "Syncopation");
                    }

                    #endregion

                    attribute.AverageTempo = songInfo.AverageTempo;
                    attribute.RepresentativeArrangement = true;
                    attribute.SongPartition             = songPartition.GetSongPartition(x.Name, x.ArrangementType);
                    attribute.SongLength             = (float)Math.Round((decimal)song.SongLength, 3, MidpointRounding.AwayFromZero); //rounded
                    attribute.LastConversionDateTime = song.LastConversionDateTime;
                    attribute.TargetScore            = 100000;
                    attribute.ToneUnlockScore        = 70000;
                    attribute.SongDifficulty         = (float)song.PhraseIterations.Average(it => song.Phrases[it.PhraseId].MaxDifficulty);
                    manifestFunctions.GenerateChordTemplateData(attribute, song);
                    manifestFunctions.GeneratePhraseData(attribute, song);
                    manifestFunctions.GenerateSectionData(attribute, song);
                    manifestFunctions.GeneratePhraseIterationsData(attribute, song, platform.version);
                }
                var attrDict = new Dictionary <string, Attributes> {
                    { "Attributes", attribute }
                };
                manifest.Entries.Add(attribute.PersistentID, attrDict);
            }
            manifest.ModelName        = "GRSong_Asset";
            manifest.IterationVersion = 2;
            return(JsonConvert.SerializeObject(manifest, Formatting.Indented));
        }
Example #38
0
        private void GetFromWebBrowser(IList<SongInfo> result, IList<WBResult> webPages)
        {
            App.Debug("Web");

            string title;
            Match match;

            for (int i = 0; i < webPages.Count; ++i)
            {
                match = this.Regex.Match(webPages[i].Title);
                if (!match.Success) continue;

                App.Debug("Match : " + webPages[i].ToString());

                title = match.Groups["title"].Value.Trim();
                if (!string.IsNullOrWhiteSpace(title))
                {
                    var si = new SongInfo(this);
                    si.Title = title;

                    if (webPages[i].Url != null && this.UrlRegex.IsMatch(webPages[i].Url))
                        si.Url = webPages[i].Url;

                    si.Handle = webPages[i].Handle;
                    si.MainTab = webPages[i].MainTab;

                    IParseRule.AddToList(result, si);
                }
            }
        }
Example #39
0
 //Player Actions Log / Set Player Data
 public void SetCurrentSong(SongInfo newSongInfo)
 {
     //Trigger From Level - Set Song Info Here
     _currentSongLoaded = newSongInfo;
 }
Example #40
0
        private bool GetTagsFromTitle(SongInfo si, IntPtr hwnd, string title = null)
        {
            if (title == null)
                title = NativeMethods.GetWindowTitle(hwnd);
            if (string.IsNullOrWhiteSpace(title) || this.Ignore.IsMatch(title)) return false;
            App.Debug("Title");
            App.Debug(title);

            if ((this.ParseFlag & ParseFlags.ManualTitle) == ParseFlags.ManualTitle)
            {
                if (this.ParseTitle(si, title))
                    return true;

                return false;
            }

            var match = this.Regex.Match(title);
            if (!match.Success) return false;

            Group g;
            if (string.IsNullOrWhiteSpace(si.Title)  && (g = match.Groups["title"])  != null) si.Title  = g.Value.Trim();
            if (string.IsNullOrWhiteSpace(si.Artist) && (g = match.Groups["artist"]) != null) si.Artist = g.Value.Trim();
            if (string.IsNullOrWhiteSpace(si.Album)  && (g = match.Groups["album"])  != null) si.Album  = g.Value.Trim();

            si.Handle = hwnd;
            return true;
        }
 public void DeleteData()
 {
     Info = new SongInfo();
     Invalidate();
 }