public CockpitViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                logger = new LoggerConfiguration()
                         .WriteTo.Logger(Log.Logger)
                         .WriteTo.ObservableCollection(Logs, Dispatcher.CurrentDispatcher)
                         .CreateLogger();

                beatSaver = new BeatSaver(new HttpOptions()
                {
                    ApplicationName  = "TwitchToSpeech",
                    Version          = Assembly.GetExecutingAssembly().GetName().Version,
                    HandleRateLimits = true
                });

                ConnectToTwitchCommand = new RelayCommand(ConnectToTwitch);
                dispatcher             = Dispatcher.CurrentDispatcher;
                taskQueue = new TaskQueue();
                speech    = new SpeechSynthesizer();

                Settings.PropertyChanged += (s, e) => SettingsChanged();
                SettingsChanged();
            }
        }
        public static Task <Page <SearchRequestOptions> > Serch(BeatSaver beatSaver, string quary, uint pagenum)
        {
            var op = new SearchRequestOptions(quary);

            op.Page = pagenum;
            return(beatSaver.Search(op));
        }
Esempio n. 3
0
        public virtual async void SetSelectedSongAsync(PlayerInfo sender, SongInfo song)
        {
            if (sender.Equals(roomHost))
            {
                selectedSong = song;

                NetOutgoingMessage outMsg = HubListener.ListenerServer.CreateMessage();

                if (selectedSong == null)
                {
                    switch (roomSettings.SelectionType)
                    {
                    case SongSelectionType.Manual:
                    {
                        roomState = RoomState.SelectingSong;

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

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

                    case SongSelectionType.Random:
                    {
                        roomState = RoomState.Preparing;
                        Random rand = new Random();

                        randomSongTask = BeatSaver.GetRandomSong();
                        selectedSong   = await randomSongTask;
                        randomSongTask = null;

                        outMsg.Write((byte)CommandType.SetSelectedSong);
                        selectedSong.AddToMessage(outMsg);

                        BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);
                        BroadcastWebSocket(CommandType.SetSelectedSong, selectedSong);
                        ReadyStateChanged(roomHost, true);
                    }
                    break;
                    }
                }
                else
                {
                    roomState = RoomState.Preparing;

                    outMsg.Write((byte)CommandType.SetSelectedSong);
                    selectedSong.AddToMessage(outMsg);

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);
                    BroadcastWebSocket(CommandType.SetSelectedSong, selectedSong);
                    ReadyStateChanged(roomHost, true);
                }
            }
            else
            {
                Logger.Instance.Warning($"{sender.playerName}:{sender.playerId} tried to select song, but he is not the host");
            }
        }
Esempio n. 4
0
        public void OnApplicationStart()
        {
            var steamDllPath = Path.Combine(
                UnityGame.InstallPath,
                "Beat Saber_Data",
                "Plugins",
                "steam_api64.dll");
            var hasSteamDll     = File.Exists(steamDllPath);
            var platform        = hasSteamDll ? "steam" : "oculus";
            var gameVersionFull = $"{UnityGame.GameVersion}-{platform}";
            var httpAgent       = new HttpAgent("BeatSaber", gameVersionFull);
            var agentList       = new List <HttpAgent> {
                httpAgent
            };
            var httpOptions = new HttpOptions(
                "BeatSaverDownloader",
                Assembly.GetExecutingAssembly().GetName().Version,
                agents: agentList
                );

            BeatSaver = new BeatSaver(httpOptions);

            PluginConfig.LoadConfig();
            Sprites.ConvertToSprites();
            PluginUI.instance.Setup();

            BSEvents.earlyMenuSceneLoadedFresh += OnMenuSceneLoadedFresh;
            SceneManager.activeSceneChanged    += OnActiveSceneChanged;
            SceneManager.sceneLoaded           += OnSceneLoaded;
        }
        public void DefaultOptions()
        {
            _ = new BeatSaver();

            var options = new HttpOptions();

            _ = new BeatSaver(options);
        }
        public static async Task <Page <PagedRequestOptions> > GetLatestPage(BeatSaver beatSaver, uint count)
        {
            var op = PagedRequestOptions.Default;

            op.Page = count;
            var page = await beatSaver.Latest(op);

            return(page);
        }
        static RequestBot()
        {
            var http = new HttpOptions()
            {
                ApplicationName = "MultiSongRequestManager",
                Version         = Assembly.GetCallingAssembly().GetName().Version
            };

            _current = new BeatSaver(http);
        }
        public void ApplicationNameAndVersion()
        {
            var options = new HttpOptions()
            {
                ApplicationName = "TestApp",
                Version         = new Version(1, 0),
            };

            _ = new BeatSaver(options);
        }
Esempio n. 9
0
        public async void StartChannel(int newChannelId)
        {
            channelId = newChannelId;

            channelInfo = new ChannelInfo()
            {
                channelId = channelId, name = Settings.Instance.Radio.RadioChannels[channelId].ChannelName, currentSong = null, currentLevelOptions = new LevelOptionsInfo(Settings.Instance.Radio.RadioChannels[channelId].PreferredDifficulty, new GameplayModifiers()
                {
                    noFail = true
                }, "Standard"), playerCount = 0, iconUrl = Settings.Instance.Radio.RadioChannels[channelId].ChannelIconUrl, state = ChannelState.NextSong, ip = "", port = 0
            };

            if (File.Exists($"RadioQueue{channelId}.json"))
            {
                try
                {
                    Queue <SongInfo> queue = JsonConvert.DeserializeObject <Queue <SongInfo> >(File.ReadAllText($"RadioQueue{channelId}.json"));
                    if (queue != null)
                    {
                        radioQueue = queue;
                    }
                }
                catch (Exception e)
                {
                    Logger.Instance.Warning("Unable to load radio queue! Exception: " + e);
                }
            }

            if (radioQueue.Count > 0)
            {
                channelInfo.currentSong = radioQueue.Dequeue();
                try
                {
                    File.WriteAllText($"RadioQueue{channelId}.json", JsonConvert.SerializeObject(radioQueue, Formatting.Indented));
                }
                catch
                {
                }
            }
            else
            {
                if (Settings.Instance.Radio.RadioChannels[channelId].DefaultSongIDs.Count > 0)
                {
                    defaultSongs = await BeatSaver.ConvertSongIDsAsync(Settings.Instance.Radio.RadioChannels[channelId].DefaultSongIDs);

                    channelInfo.currentSong = defaultSongs.Random();
                }
                else
                {
                    channelInfo.currentSong = await BeatSaver.GetRandomSong();
                }
            }

            HighResolutionTimer.LoopTimer.Elapsed += RadioLoop;
        }
        public static async void AddSongToQueueByHash(string hash, int channelId)
        {
            SongInfo info = await BeatSaver.InfoFromHash(hash);

            if (info != null)
            {
                radioChannels[channelId].radioQueue.Enqueue(info);
                Logger.Instance.Log("Successfully added songs to the queue!");
                File.WriteAllText($"RadioQueue{channelId}.json", JsonConvert.SerializeObject(radioChannels[channelId].radioQueue, Formatting.Indented));
            }
        }
Esempio n. 11
0
        public void ApplicationNameWithoutVersion()
        {
            var options = new HttpOptions()
            {
                ApplicationName = "TestApp",
            };

            Assert.ThrowsException <ArgumentException>(() =>
            {
                _ = new BeatSaver(options);
            });
        }
Esempio n. 12
0
        public Plugin(IPALogger logger, Config conf, Zenjector zenjector, PluginMetadata pluginMetadata)
        {
            Instance       = this;
            PluginMetadata = pluginMetadata;
            Log            = logger;
            Config         = conf.Generated <PluginConfig>();
            zenjector.OnApp <MPCoreInstaller>();
            zenjector.OnMenu <MPMenuInstaller>();
            HttpOptions options = new HttpOptions("MultiplayerExtensions", new Version(pluginMetadata.Version.ToString()));

            BeatSaver = new BeatSaver(options);
        }
Esempio n. 13
0
        private void InitApp(object sender, StartupEventArgs e)
        {
            // Setup the client's HTTP User Agent
            var options = new HttpOptions(
                "BeatLibrary",
                new Version(0, 1, 0)
                );

            // Use this to interact with the API
            BeatSaverApi = new BeatSaver(options);

            Settings.Instance.Load();
        }
Esempio n. 14
0
        public Form1()
        {
            InitializeComponent();
            _playlistDownloading = new List <string>();

            var options = new HttpOptions
            {
                ApplicationName  = "Beatsaber Playlist Missing Songs Downloader",
                Version          = new Version(1, 0, 0),
                HandleRateLimits = true,
            };

            _beatSaver = new BeatSaver(options);
        }
Esempio n. 15
0
        public BeatSaverSource()
        {
            var version = typeof(BeatSaverSource).Assembly.GetName().Version;
            var options = new HttpOptions()
            {
                ApplicationName  = "ModMetaRelay",
                Version          = version,
                HandleRateLimits = true,
                Timeout          = System.TimeSpan.FromSeconds(4)
            };

            // Use this to interact with the API
            _client = new BeatSaver(options);
        }
Esempio n. 16
0
        public Plugin(IPALogger logger, Config conf, Zenjector zenjector, PluginMetadata pluginMetadata)
        {
            Instance       = this;
            PluginMetadata = pluginMetadata;
            Log            = logger;
            Config         = conf.Generated <PluginConfig>();
            BeatSaberMarkupLanguage.GameplaySetup.GameplaySetup.instance.AddTab("Multiplayer", "MultiplayerExtensions.UI.GameplaySetupPanel.bsml", GameplaySetupPanel.instance);
            zenjector.OnApp <MultiplayerInstaller>();
            HttpOptions options = new HttpOptions
            {
                ApplicationName = "MultiplayerExtensions",
                Version         = new Version(pluginMetadata.Version.ToString())
            };

            BeatSaver = new BeatSaver(options);
        }
Esempio n. 17
0
        public Plugin(IPALogger logger, Config conf, Zenjector zenjector, PluginMetadata pluginMetadata)
        {
            Instance       = this;
            PluginMetadata = pluginMetadata;
            Log            = logger;
            Config         = conf.Generated <PluginConfig>();
            zenjector.OnApp <MultiplayerInstaller>();
            zenjector.OnMenu <InterfaceInstaller>();
            HttpOptions options = new HttpOptions
            {
                ApplicationName = "MultiplayerExtensions",
                Version         = new Version(pluginMetadata.Version.ToString())
            };

            BeatSaver = new BeatSaver(options);
        }
Esempio n. 18
0
        public Plugin(IPALogger logger, Config conf, Zenjector zenjector, PluginMetadata pluginMetadata)
        {
            Instance       = this;
            PluginMetadata = pluginMetadata;
            Log            = logger;
            Config         = conf.Generated <PluginConfig>();

            zenjector.OnApp <MPCoreInstaller>();
            zenjector.OnMenu <MPMenuInstaller>();
            zenjector.OnGame <MPGameInstaller>().OnlyForMultiplayer();

            HttpOptions options = new HttpOptions("MultiplayerExtensions", new Version(pluginMetadata.Version.ToString()));

            BeatSaver  = new BeatSaver(options);
            HttpClient = new HttpClient();
            HttpClient.DefaultRequestHeaders.Add("User-Agent", Plugin.UserAgent);
        }
Esempio n. 19
0
        public SongInfo(NetIncomingMessage msg)
        {
            songName     = msg.ReadString();
            songSubName  = msg.ReadString();
            authorName   = msg.ReadString();
            key          = msg.ReadString();
            levelId      = BitConverter.ToString(msg.ReadBytes(16)).Replace("-", "");
            songDuration = msg.ReadFloat();

            if (string.IsNullOrEmpty(key))
            {
                Task.Run(async() =>
                {
                    var song = await BeatSaver.FetchByHash(levelId);
                    key      = song.Key;
                });
            }
        }
Esempio n. 20
0
        private static async Task Main()
        {
            while (true)
            {
                try
                {
                    Console.WriteLine("Enter map link (or key): ");
                    var link = Console.ReadLine();
                    if (link is null)
                    {
                        Console.WriteLine("Invalid link!");
                        continue;
                    }
                    if (link.Contains("://"))
                    {
                        var innerLink = link.Split('/').LastOrDefault(item => !string.IsNullOrEmpty(item));
                        if (innerLink is null)
                        {
                            Console.WriteLine($"Could not parse beatsaver key from: {link}!");
                            Console.WriteLine("Try providing the key instead.");
                            continue;
                        }
                        link = innerLink;
                    }

                    var client = new BeatSaver(new HttpOptions
                    {
                        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name,
                        Version         = Assembly.GetExecutingAssembly().GetName().Version
                    });
                    Console.WriteLine($"Creating temporary folder: {Path.GetFullPath(link)}");
                    Directory.CreateDirectory(link);
                    var dataPath = Path.Combine(link, "data");
                    Console.WriteLine("Downloading from beatsaver...");
                    Beatmap res;
                    using (var progress = new ProgressBar())
                    {
                        res = await client.Key(link, progress);
                    }
                    byte[] bytes;
                    using (var progress = new ProgressBar())
                        bytes = await res.DownloadZip(progress : progress);
                    using (var s = new MemoryStream(bytes))
                    {
                        var z = new ZipArchive(s);
                        z.ExtractToDirectory(dataPath, true);
                        var info = z.GetEntry("Info.dat");
                        if (info is null)
                        {
                            info = z.GetEntry("info.dat");
                        }
                        if (info is null)
                        {
                            Console.WriteLine($"Could not load 'Info.dat' or 'info.dat' from song: {Path.GetFullPath(dataPath)}!");
                            continue;
                        }
                        var infoJson = await JsonDocument.ParseAsync(info.Open());

                        if (!TryParseJson(infoJson.RootElement, "_songName", out var dstString))
                        {
                            continue;
                        }
                        await File.WriteAllTextAsync(Path.Combine(link, "songName.txt"), dstString);

                        if (!TryParseJson(infoJson.RootElement, "_songAuthorName", out dstString))
                        {
                            continue;
                        }
                        await File.WriteAllTextAsync(Path.Combine(link, "songAuthorName.txt"), dstString);

                        if (!TryParseJson(infoJson.RootElement, "_levelAuthorName", out dstString))
                        {
                            continue;
                        }
                        await File.WriteAllTextAsync(Path.Combine(link, "levelAuthorName.txt"), dstString);

                        if (!TryParseJson(infoJson.RootElement, "_songFilename", out dstString))
                        {
                            continue;
                        }
                        await File.WriteAllTextAsync(Path.Combine(link, "songFilename.txt"), dstString);

                        if (!TryParseJson(infoJson.RootElement, "_beatsPerMinute", out dstString))
                        {
                            continue;
                        }
                        await File.WriteAllTextAsync(Path.Combine(link, "beatsPerMinute.txt"), dstString);

                        if (!TryParseJson(infoJson.RootElement, "_coverImageFilename", out dstString))
                        {
                            continue;
                        }
                        await File.WriteAllTextAsync(Path.Combine(link, "coverImageFilename.txt"), dstString);

                        // Copy over cover image
                        var coverImage = z.GetEntry(dstString);
                        if (coverImage is not null)
                        {
                            coverImage.ExtractToFile(Path.Combine(link, dstString));
                        }
                        else
                        {
                            Console.WriteLine($"Could not load cover image from path: {dstString}");
                            continue;
                        }
                        if (infoJson.RootElement.TryGetProperty("_difficultyBeatmapSets", out var difficultySets))
                        {
                            foreach (var item in difficultySets.EnumerateArray())
                            {
                                if (item.TryGetProperty("_beatmapCharacteristicName", out var charNameE) && "Standard" == charNameE.GetString())
                                {
                                    var diffCount = item.GetProperty("_difficultyBeatmaps").GetArrayLength();
                                    await File.WriteAllTextAsync(Path.Combine(link, "difficultyCount.txt"), diffCount.ToString(CultureInfo.InvariantCulture));

                                    break;
                                }
                            }
                        }
                    }
                    Console.WriteLine($"Complete with download of key: {link} to: {Path.GetFullPath(link)}");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"An exception ocurred: {e}");
                }
            }
        }
Esempio n. 21
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;
            }

            outMsg.Write(radioClients.Count);

            radioClients.ForEach(x => x.playerInfo.AddToMessage(outMsg));

            BroadcastPacket(outMsg, NetDeliveryMethod.UnreliableSequenced);

            if (radioClients.Count > 0)
            {
                BroadcastWebSocket(CommandType.UpdatePlayerInfo, radioClients.Select(x => x.playerInfo).ToArray());
            }
        }
Esempio n. 22
0
        public virtual async void RoomLoopAsync(object sender, HighResolutionTimerElapsedEventArgs e)
        {
            if (randomSongTask != null)
            {
                return;
            }

            NetOutgoingMessage outMsg = HubListener.ListenerServer.CreateMessage();

            switch (roomState)
            {
            case RoomState.InGame:
            {
                if (DateTime.Now.Subtract(_songStartTime).TotalSeconds >= selectedSong.songDuration)
                {
                    roomState         = RoomState.Results;
                    _resultsStartTime = DateTime.Now;

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

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);

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

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

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

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

            case RoomState.SelectingSong:
            {
                switch (roomSettings.SelectionType)
                {
                case SongSelectionType.Random:
                {
                    roomState = RoomState.Preparing;
                    Random rand = new Random();

                    randomSongTask = BeatSaver.GetRandomSong();
                    selectedSong   = await randomSongTask;
                    randomSongTask = null;

                    outMsg.Write((byte)CommandType.SetSelectedSong);
                    selectedSong.AddToMessage(outMsg);

                    BroadcastPacket(outMsg, NetDeliveryMethod.ReliableOrdered);

                    BroadcastWebSocket(CommandType.SetSelectedSong, selectedSong);
                    ReadyStateChanged(roomHost, true);
                }
                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(resultsShowTime);
            }
            break;
            }

            outMsg.Write(roomClients.Count);

            for (int i = 0; i < roomClients.Count; i++)
            {
                if (i < roomClients.Count)
                {
                    if (roomClients[i] != null)
                    {
                        roomClients[i].playerInfo.AddToMessage(outMsg);
                    }
                }
            }

            BroadcastPacket(outMsg, NetDeliveryMethod.UnreliableSequenced);

            if (roomClients.Count > 0)
            {
                BroadcastWebSocket(CommandType.UpdatePlayerInfo, roomClients.Select(x => x.playerInfo).ToArray());
            }
        }
        static BeatSarverData()
        {
            var http = new HttpOptions("SongPlayListEditer", Assembly.GetExecutingAssembly().GetName().Version, new TimeSpan(0, 0, 30));

            BeatSaver = new BeatSaver(http);
        }
        public static async void AddPlaylistToQueue(string path, int channelId)
        {
            bool     remotePlaylist = path.ToLower().Contains("http://") || path.ToLower().Contains("https://");
            Playlist playlist       = null;

            if (remotePlaylist)
            {
                using (WebClient w = new WebClient())
                {
                    w.Headers.Add("user-agent", $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}/{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}");

                    try
                    {
                        string response = await w.DownloadStringTaskAsync(path);

                        playlist = JsonConvert.DeserializeObject <Playlist>(response);
                    }
                    catch (Exception e)
                    {
                        Logger.Instance.Error("Unable to add playlist to queue! Exception: " + e);
                        return;
                    }
                }
            }
            else
            {
                try
                {
                    string fullPath = Path.GetFullPath(path);
                    if (File.Exists(fullPath))
                    {
                        string content = await File.ReadAllTextAsync(fullPath);

                        playlist = JsonConvert.DeserializeObject <Playlist>(content);
                    }
                    else
                    {
                        Logger.Instance.Error($"Unable to add playlist to queue! File \"{path}\" does not exist!");
                        return;
                    }
                }
                catch (Exception e)
                {
                    Logger.Instance.Error("Unable to add playlist to queue! Exception: " + e);
                    return;
                }
            }

            try
            {
                foreach (PlaylistSong song in playlist.songs)
                {
                    if (song == null)
                    {
                        continue;
                    }

                    if (!string.IsNullOrEmpty(song.hash))
                    {
                        if (song.hash.Length >= 40)
                        {
                            radioChannels[channelId].radioQueue.Enqueue(new SongInfo()
                            {
                                levelId = song.hash.ToUpper().Substring((song.hash.Length - 40), 40), songName = song.songName, key = song.key
                            });
                            continue;
                        }
                    }

                    if (!string.IsNullOrEmpty(song.levelId))
                    {
                        if (song.levelId.Length >= 40)
                        {
                            radioChannels[channelId].radioQueue.Enqueue(new SongInfo()
                            {
                                levelId = song.levelId.ToUpper().Substring((song.hash.Length - 40), 40), songName = song.songName, key = song.key
                            });
                            continue;
                        }
                    }

                    if (!string.IsNullOrEmpty(song.key))
                    {
                        SongInfo info = await BeatSaver.InfoFromID(song.key);

                        if (info != null)
                        {
                            radioChannels[channelId].radioQueue.Enqueue(info);
                        }
                        continue;
                    }
                }
                Logger.Instance.Log("Successfully added all songs from playlist to the queue!");
                File.WriteAllText($"RadioQueue{channelId}.json", JsonConvert.SerializeObject(radioChannels[channelId].radioQueue, Formatting.Indented));
            }
            catch (Exception e)
            {
                Logger.Instance.Error("Unable to add playlist to queue! Exception: " + e);
                return;
            }
        }
Esempio n. 25
0
 internal LevelDataService(SiraLog siraLog, IPlatformUserModel platformUserModel, UBinder <Plugin, PluginMetadata> metadataBinder)
 {
     _siraLog           = siraLog;
     _platformUserModel = platformUserModel;
     _beatSaver         = new BeatSaver("DiTails", Version.Parse(metadataBinder.Value.HVersion.ToString()));
 }