private void ExecuteSearch(bool newSearch) { if (searching) { return; } if (newSearch) { pageOffset = 0; canLoadMore = false; } searching = true; pWebRequest req = new pWebRequest(string.Format(Urls.DIRECT_SEARCH, ConfigManager.sUsername, ConfigManager.sPassword, (int)displayModeDropdown.SelectedObject, GeneralHelper.UrlEncodeParam(lastSearch), (int)displayOsuModeDropdown.SelectedObject, pageOffset)); req.Finished += req_onFinish; req.Perform(); searchInfo.Text = newSearch ? "Searching..." : "Loading..."; if (newSearch) { loadingText.FadeIn(200); Beatmaps.ForEach(b => b.Dim()); } }
internal bool EarnCoin() { if (!GameBase.HasLogin) { return(true); } pSprite coin = coinSingular.Clone(); coin.Position = InputManager.CursorPosition / GameBase.WindowManager.Ratio; coin.Depth = 0.99f; coin.FadeOut(1500); spriteManagerDialog.Add(coin); physics.Add(coin, new Vector2((float)RNG.NextDouble() * 100, (float)RNG.NextDouble() * -100)); pSprite coinShine = coinSingular.Clone(); coinShine.Additive = true; coinShine.OnUpdate += delegate { coinShine.Position = coin.Position; }; coinShine.FadeOut(500); spriteManagerDialog.Add(coinShine); AudioEngine.PlaySample(@"coins-earn", 80); Count++; pWebRequest snr = new pWebRequest(string.Format(General.WEB_ROOT + "/web/coins.php?action=earn&u={0}&h={1}&c={2}&cs={3}", ConfigManager.sUsername, ConfigManager.sPassword, Count, Checksum)); snr.Finished += snr_onFinish; snr.Perform(); return(true); }
internal override void Initialize() { base.Initialize(); spriteManager.Add(coinsBuyButton = new pSprite(@"coins-buy", new Vector2(-35, -10), SkinSource.All, Origins.Centre, Fields.TopCentre) { Depth = 0.88f }); spriteManager.Add(coinsBg = new pSprite(@"coins-bg", new Vector2(0, -10), SkinSource.All, Origins.Centre, Fields.TopCentre) { Depth = 0.9f }); spriteManager.Add(coinsFg = new pSprite(@"coins", new Vector2(0, -15), SkinSource.All, Origins.Centre, Fields.TopCentre) { Depth = 0.98f, Scale = 0.55f }); coinsBuyButton.OnClick += buyMore; coinsBuyButton.HandleInput = true; coinsBuyButton.HoverEffect = new Transformation(Color.White, Color.HotPink, 0, 100); spriteManager.Add(coinsCount = new pText(string.Empty, 16, new Vector2(0, 0), 1, true, Color.White) { Field = Fields.TopCentre, Origin = Origins.Centre, TextShadow = false }); spriteManager.SpriteList.ForEach(s => { s.Alpha = 0; }); pWebRequest snr = new pWebRequest(string.Format(General.WEB_ROOT + "/web/coins.php?action=check&u={0}&h={1}&c={2}&cs={3}", ConfigManager.sUsername, ConfigManager.sPassword, Count, Checksum)); snr.Finished += snr_onFinish; snr.Perform(); }
public static void LoadOnlineFavourites() { if (OnlineFavouritesLoaded) { return; } OnlineFavouritesLoaded = true; NotificationManager.ShowMessageMassive("Loading online favourites...", 1000); pWebRequest dnr = new pWebRequest(string.Format(Urls.GET_FAVOURITES, ConfigManager.sUsername, ConfigManager.sPassword)); dnr.Finished += delegate(pWebRequest r, Exception e) { foreach (string s in r.ResponseString.Split('\n')) { if (s.Length == 0) { continue; } int beatmapSetId = Int32.Parse(s); Beatmaps.FindAll(b => b.BeatmapSetId == beatmapSetId).ForEach(b => b.OnlineFavourite = true); } InvokeOnOnlineFavouritesLoaded(); }; dnr.Perform(); }
public ChangelogOverlay(Game game, bool fullscreen = false) : base(game) { if (fullscreen) { Width = GameBase.WindowManager.WidthScaled; Height = 226; startHeight = 0; } area = new pScrollableArea(new Rectangle(0, GameBase.WindowManager.HeightScaled - Height, Width, Height), Vector2.Zero, true); area.HeaderHeight = startHeight; int year = General.VERSION / 10000; int month = General.VERSION / 100 - year * 100; int day = General.VERSION - year * 10000 - month * 100; int version_dated = Int32.Parse(new DateTime(year, month, day).AddDays(-14).ToString("yyyyMMdd")); int version_current = Int32.Parse(new DateTime(year, month, day).ToString("yyyyMMdd")); pWebRequest snr = new pWebRequest(General.WEB_ROOT + "/p/changelog?updater=3" + (!string.IsNullOrEmpty(General.SUBVERSION) ? "&test=1" : "¤t=" + version_current + "&from=" + version_dated)); snr.Finished += snr_onFinish; snr.Perform(); pSprite bg = new pSprite(GameBase.WhitePixel, Vector2.Zero, 0.5f, true, Color.Black); bg.Scale = 1.6f; bg.ViewOffsetImmune = true; bg.VectorScale = new Vector2(Width, Height); bg.Alpha = 0.5f; area.ContentSpriteManager.Add(bg); if (!fullscreen) { pText t = new pText(LocalisationManager.GetString(OsuString.Update_RecentChanges), 10, new Vector2(3, 3), Vector2.Zero, 0.9992f, true, Color.White, false); t.ViewOffsetImmune = true; t.TextBold = true; area.ContentSpriteManager.Add(t); bg = new pSprite(GameBase.WhitePixel, Vector2.Zero, 0.9991f, true, SkinManager.NEW_SKIN_COLOUR_SECONDARY); bg.Scale = 1.6f; bg.ViewOffsetImmune = true; bg.VectorScale = new Vector2(Width, startHeight); bg.Alpha = 0.8f; bg.HandleInput = true; bg.HoverEffect = new Transformation(Color.DarkBlue, Color.LightBlue, 0, 50); bg.OnClick += delegate { area.ContentSpriteManager.SpriteList.ForEach(s => s.FadeOut(100)); GameBase.Scheduler.AddDelayed(delegate { area.Hide(); }, 100); }; area.ContentSpriteManager.Add(bg); } }
internal void GetReplayData() { pWebRequest dnr = new pWebRequest(string.Format(General.WEB_ROOT + @"/web/osu-getreplay.php?c={0}&m={1}&u={2}&h={3}", OnlineId, (int)PlayMode, ConfigManager.sUsername, ConfigManager.sPassword)); dnr.Finished += dnr_onFinish; dnr.Perform(); }
public override void Initialize() { //background baseSpriteManager.Add(new pSprite(GameBase.WhitePixel, Fields.Native, Origins.TopLeft, Clocks.Game, Vector2.Zero, 0, true, c_background) { VectorScale = new Vector2(GameBase.WindowManager.Width, GameBase.WindowManager.Height) }); //header pText textCharts = new pText("Charts" + @" /", 28, new Vector2(PADDING, 60), 1, true, Color.White) { Origin = Origins.BottomLeft }; baseSpriteManager.Add(textCharts); t_currentCategory = new pText("All Charts", 20, new Vector2(120f, 58), 1, true, new Color(254, 220, 97)) { Origin = Origins.BottomLeft }; baseSpriteManager.Add(t_currentCategory); searchBox = new pSearchBox(18, new Vector2(PADDING, 33), 20, Graphics.Renderers.TextAlignment.Right); searchBox.OnChange += searchBox_OnChange; baseSpriteManager.Add(searchBox.SpriteCollection); baseSpriteManager.Add(new pBox(new Vector2(PADDING, 62), new Vector2(GameBase.WindowManager.WidthScaled - (PADDING * 2), 1), 1, Color.White)); t_categorySelection = new pText("All / Monthly / Themed / Special", 14, new Vector2(PADDING, 70), 1, true, Color.White) { Origin = Origins.TopLeft }; baseSpriteManager.Add(t_categorySelection); //list sa_chartList = new pScrollableArea(new RectangleF(PADDING / 2, 90, GameBase.WindowManager.WidthScaled - PADDING, GameBase.WindowManager.HeightScaled - PADDING - 90), Vector2.Zero, true); pWebRequest req = new pWebRequest("https://osu.ppy.sh/web/osu-getcharts.php?u={0}&h={1}", ConfigManager.sUsername, ConfigManager.sPassword); req.Finished += delegate(pWebRequest r, Exception e) { charts = JsonConvert.DeserializeObject <List <Chart> >(r.ResponseString); DoLayout(); }; req.Perform(); //footer backButton = new BackButton(delegate { GameBase.ChangeMode(OsuModes.Menu); }); spriteManagerTop.Add(backButton.SpriteCollection); KeyboardHandler.OnKeyPressed += onKeyPressed; base.Initialize(); }
private void dnr_onFinish(pWebRequest r, Exception e) { ReplayCompressed = r.ResponseData; ReadReplayData(); if (GotReplayData != null) { GotReplayData(this); } }
private void submission_ForumSubmission(object sender, DoWorkEventArgs e) { string textSubject; if (beatmaps[0].Artist.Length == 0) { textSubject = beatmaps[0].Title; } else { textSubject = beatmaps[0].SortTitle; } List <PlayModes> modes = new List <PlayModes>(); foreach (Beatmap b in beatmaps) { if (!modes.Contains(b.PlayMode)) { modes.Add(b.PlayMode); } } if (modes.Count > 1 || modes[0] != PlayModes.Osu) { string modeString = string.Empty; foreach (PlayModes p in modes) { modeString = modeString + p + "|"; } modeString = modeString.TrimEnd('|'); textSubject += " [" + modeString + "]"; } UpdateStatus(LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_PostingToForums)); activeWebRequest = new pWebRequest(Urls.OSZ2_SUBMIT_FORUM); activeWebRequest.Timeout *= 2; activeWebRequest.AddParameter("u", ConfigManager.sUsername); activeWebRequest.AddParameter("p", ConfigManager.sPassword); activeWebRequest.AddParameter("b", newBeatmapSetID.ToString()); activeWebRequest.AddParameter("subject", textSubject); activeWebRequest.AddParameter("message", newMessage + textMessage.Text.Replace("\r", "")); activeWebRequest.AddParameter("complete", (radioButtonPending.Checked ? "1" : "0")); if (checkNotify.Checked) { activeWebRequest.AddParameter("notify", "1"); } activeWebRequest.BlockingPerform(); threadId = Int32.Parse(activeWebRequest.ResponseString); }
internal static void Submit(OsuError err) { if (lastSubmission > 0 && GameBase.Time - lastSubmission < 10000) { return; } lastSubmission = GameBase.Time; try { Logger.Log($@"ERROR (hard crash): {err.Feedback}", LoggingTarget.Runtime, LogLevel.Error); Logger.Log($@"ERROR (hard crash): {err.Exception}", LoggingTarget.Runtime, LogLevel.Error); } catch { } try { pWebRequest r = new pWebRequest(General.WEB_ROOT + "/web/osu-error.php"); r.AddParameter("u", ConfigManager.sUsername); if (GameBase.User != null) { r.AddParameter("i", GameBase.User.Id.ToString()); } r.AddParameter("osumode", ((int)GameBase.Mode).ToString()); r.AddParameter("gamemode", ((int)Player.Mode).ToString()); r.AddParameter("gametime", GameBase.Time.ToString()); r.AddParameter("audiotime", AudioEngine.Time.ToString()); r.AddParameter("culture", Thread.CurrentThread.CurrentCulture.Name); r.AddParameter("b", BeatmapManager.Current != null ? BeatmapManager.Current.BeatmapId.ToString() : ""); r.AddParameter("bc", BeatmapManager.Current != null ? BeatmapManager.Current.BeatmapChecksum : ""); r.AddParameter("exception", err.Exception); r.AddParameter("feedback", err.Feedback); r.AddParameter("stacktrace", err.StackTrace); r.AddParameter("iltrace", err.ILTrace); r.AddParameter("version", General.BUILD_NAME); r.AddParameter("exehash", GameBase.ExeHash(Path.GetFileName(OsuMain.FullPath))); r.AddParameter("config", File.ReadAllText(Path.Combine(OsuMain.UserPath, ConfigManager.UserConfigFilename))); if (err.Screenshot != null) { r.AddFile(@"ss", err.Screenshot); } r.Timeout = 6000; r.BlockingPerform(); } catch { } }
internal bool Recharge() { if (!GameBase.HasLogin) { return(true); } pWebRequest snr = new pWebRequest(string.Format(General.WEB_ROOT + "/web/coins.php?action=recharge&u={0}&h={1}&c={2}&cs={3}", ConfigManager.sUsername, ConfigManager.sPassword, Count, Checksum)); snr.Finished += snr_onFinish; snr.Finished += delegate { AudioEngine.PlaySample(@"coins-recharge"); }; snr.Perform(); return(true); }
static void snr_onFinish(pWebRequest r, Exception e) { if (e != null) { return; } try { switch (Int32.Parse(r.ResponseString)) { case -3: shouldContinueSending = false; break; } } catch { } }
internal bool UseCoin() { if (!GameBase.HasLogin) { return(true); } Count--; pWebRequest snr = new pWebRequest(string.Format(General.WEB_ROOT + "/web/coins.php?action=use&u={0}&h={1}&c={2}&cs={3}", ConfigManager.sUsername, ConfigManager.sPassword, Count, Checksum)); snr.Finished += snr_onFinish; snr.Perform(); return(true); }
private static void sendCurrentTrack(bool scrobble) { #if DEBUG return; #endif if (last == null) { return; } string url = General.WEB_ROOT + "/web/lastfm.php?b=" + last.BeatmapId + "&action=" + (scrobble ? "scrobble" : "np") + "&us=" + ConfigManager.sUsername + "&ha=" + ConfigManager.sPassword; pWebRequest snr = new pWebRequest(url); snr.Finished += snr_onFinish; snr.Perform(); }
void comment_IncomingCommentInfo(pWebRequest r, Exception e) { if (e != null) { return; } GameBase.Scheduler.Add(delegate { if (processed < 0) { foreach (string line in r.ResponseString.Split('\n')) { if (line.Length == 0) { continue; } string[] split = line.Split('\t'); if (split.Length < 4) { continue; } int time; Int32.TryParse(split[0], System.Globalization.NumberStyles.Integer, GameBase.nfi, out time); if (time == 0) { continue; } CommentTargets target = (CommentTargets)Enum.Parse(typeof(CommentTargets), split[1], true); string formatString = split[2]; string comment = split[3]; comments.AddInPlace(new Comment(time, target, formatString, comment)); } processed = 0; GameBase.Scheduler.Add(processComments, true); } }); }
private void RequestComments() { if (commentsRequested) { return; } commentsRequested = true; pWebRequest fnr = new pWebRequest(General.WEB_ROOT + "/web/osu-comment.php"); fnr.AddParameter("u", ConfigManager.sUsername); fnr.AddParameter("p", ConfigManager.sPassword); fnr.AddParameter("b", BeatmapManager.Current.BeatmapId.ToString()); fnr.AddParameter("s", BeatmapManager.Current.BeatmapSetId.ToString()); fnr.AddParameter("r", InputManager.ReplayScore.OnlineId.ToString(GameBase.nfi)); fnr.AddParameter("m", ((int)InputManager.ReplayScore.PlayMode).ToString(GameBase.nfi)); fnr.AddParameter("a", "get"); fnr.Finished += comment_IncomingCommentInfo; fnr.Perform(); }
void textBox_OnCommit(pTextBox sender, bool newText) { if (commentTarget == CommentTargets.None && newText) { NotificationManager.ShowMessageMassive("Select a target for your comment first!", 1500); commentInputTextbox.Select(); return; } if (newText && commentInputTextbox.Text.Length > 0) { pWebRequest fnr = new pWebRequest(General.WEB_ROOT + "/web/osu-comment.php"); fnr.AddParameter("u", ConfigManager.sUsername); fnr.AddParameter("p", ConfigManager.sPassword); fnr.AddParameter("s", BeatmapManager.Current.BeatmapSetId.ToString()); fnr.AddParameter("b", BeatmapManager.Current.BeatmapId.ToString(GameBase.nfi)); fnr.AddParameter("m", ((int)InputManager.ReplayScore.PlayMode).ToString(GameBase.nfi)); fnr.AddParameter("r", InputManager.ReplayScore.OnlineId.ToString(GameBase.nfi)); fnr.AddParameter("target", commentTarget.ToString().ToLower()); //append colour here if (commentColourPicker.InitialColour != Color.White && commentColourPicker.InitialColour != Color.TransparentWhite) { string colour = ColourHelper.Color2Hex(commentColourPicker.InitialColour); fnr.AddParameter("f", colour); } fnr.AddParameter("a", "post"); fnr.AddParameter("starttime", commitStartTime.ToString()); fnr.AddParameter("comment", commentInputTextbox.Text); fnr.Finished += delegate { GameBase.Scheduler.Add(delegate { increaseCount(commentTarget); updateCounts(); commentInputTextbox.Text = "Please wait before commenting again..."; NotificationManager.ShowMessage("Your comment has been submitted!", Color.Orange, 3000); }); }; fnr.Perform(); commentInputTextbox.Enabled = false; commentInputTextbox.Text = "Sending..."; } if (commentInputTextbox.Text.Length == 0) { commentInputTextbox.Text = DEFAULT_MESSAGE; } UpdateCommentWindowSizing(); if (Player.Paused) { AudioEngine.TogglePause(); Player.Paused = false; } }
private void submit(object sender, DoWorkEventArgs e) { #if ARCADE //Don't submit scores yet, no matter what. return; #endif #if NO_SCORE_SUBMIT NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.Score_SubmissionDisabled)); return; #endif GameBase.User.spriteInfo.Text = LocalisationManager.GetString(OsuString.Score_SubmittingScore); try { byte[] zipped = new byte[0]; if (Pass) { if (BeatmapManager.Current.onlinePersonalScore != null && TotalScore > BeatmapManager.Current.onlinePersonalScore.TotalScore) { BeatmapManager.Current.Scores.Clear(); } //We should re-retrieve online scores no matter what, otherwise when clicking 'retry' the personal score won't be updated. ReplayCompressed = SevenZipHelper.Compress(new ASCIIEncoding().GetBytes(ReplayString)); #if DEBUG if (ReplayCompressed.Length < 100) { LoadLocalData(); } #endif zipped = ReplayCompressed; } pWebRequest req = new pWebRequest(General.WEB_ROOT + @"/web/osu-submit-modular.php"); req.AddFile(@"score", zipped); string iv = null; #if SUBMISSION_DEBUG File.AppendAllText(@"DEBUG.txt", @"Debug at " + DateTime.Now + @"\n"); #endif if (Pass) { Process[] procs = GameBase.Processes; GameBase.Processes = null; if (procs == null || procs.Length == 0) { procs = Process.GetProcesses(); } StringBuilder b = new StringBuilder(); foreach (Process p in procs) { string filename = string.Empty; try { filename = p.MainModule.FileName; FileInfo fi = new FileInfo(filename); if (fi != null) { filename = CryptoHelper.GetMd5String(fi.Length.ToString()) + @" " + filename; } } catch { } b.AppendLine(filename + @" | " + p.ProcessName + @" (" + p.MainWindowTitle + @")"); } #if SUBMISSION_DEBUG File.AppendAllText(@"DEBUG.txt", @"Running Processes:\n" + b + @"\n\n"); #endif req.AddParameter(@"pl", CryptoHelper.EncryptString(b.ToString(), Secrets.GetScoreSubmissionKey(), ref iv)); } else { req.AddParameter(@"x", Exit ? @"1" : @"0"); req.AddParameter(@"ft", FailTime.ToString()); } #if SUBMISSION_DEBUG File.AppendAllText(@"DEBUG.txt", @"\n1:" + onlineFormatted + @"\n"); File.AppendAllText(@"DEBUG.txt", @"\n2:" + GameBase.clientHash + @"\n"); File.AppendAllText(@"DEBUG.txt", @"\n3:" + iv + @"\n"); #endif req.AddParameter(@"score", CryptoHelper.EncryptString(onlineFormatted, Secrets.GetScoreSubmissionKey(), ref iv)); req.AddParameter(@"fs", CryptoHelper.EncryptString(visualSettingsString, Secrets.GetScoreSubmissionKey(), ref iv)); req.AddParameter(@"c1", GameBase.CreateUniqueId()); req.AddParameter(@"pass", ConfigManager.sPassword); req.AddParameter(@"osuver", General.VERSION.ToString()); req.AddParameter(@"s", CryptoHelper.EncryptString(GameBase.ClientHash, Secrets.GetScoreSubmissionKey(), ref iv)); try { if (Pass && ExtraData != null) { req.AddFile(@"i", ExtraData.ToArray()); } else { req.AddParameter(@"i", string.Empty); } } catch { } GameBase.ChangeAllowance++; ExtraData = null; req.AddParameter(@"iv", iv); int retryCount = Pass ? 10 : 2; int retryDelay = 7500; bool didError = false; while (retryCount-- > 0) { try { req.BlockingPerform(); SubmissionResponseString = req.ResponseString; #if SUBMISSION_DEBUG Debug.Print(SubmissionResponseString); File.AppendAllText(@"DEBUG.txt", @"\nres:" + SubmissionResponseString + @"\n\n\n\n\n-------------------\n\n\n\n"); #endif if (SubmissionResponseString.Contains(@"error:")) { switch (SubmissionResponseString.Replace(@"error: ", string.Empty)) { case @"reset": BanchoClient.HandlePasswordReset(); break; case @"verify": BanchoClient.RequireVerification(); break; case @"nouser": NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.Score_ErrorNoUser)); break; case @"pass": NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.Score_ErrorPassword)); break; case @"inactive": case @"ban": NotificationManager.ShowMessage("ERROR: Your account is no longer active. Please send an email to [email protected] if you think this is a mistake."); break; case @"beatmap": if (Beatmap != null && Beatmap.SubmissionStatus > osu_common.SubmissionStatus.Pending) { NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.Score_ErrorBeatmap)); Beatmap.SubmissionStatus = osu_common.SubmissionStatus.Unknown; } break; case @"disabled": NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.Score_ErrorDisabled)); break; case @"oldver": NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.Score_ErrorVersion)); GameBase.CheckForUpdates(true); break; case @"no": break; } didError = true; } break; } catch { } if (retryDelay >= 60000) { NotificationManager.ShowMessage(string.Format(LocalisationManager.GetString(OsuString.Score_SubmissionFailed), (retryDelay / 60000))); } Thread.Sleep(retryDelay); retryDelay *= 2; } if (didError) { SubmissionStatus = ScoreSubmissionStatus.Complete; return; } } catch (Exception ex) { } if (SubmissionComplete != null) { SubmissionComplete(this); } SubmissionStatus = ScoreSubmissionStatus.Complete; if (!Pass) { GameBase.User.Refresh(); } }
private void submission_PackageAndUpload_Complete(pWebRequest r, Exception e) { backgroundWorker.DoWork -= submission_PackageAndUpload; string result = r == null ? "-1" : r.ResponseString; Debug.Print(result); if (uploadError || e != null || result != "0") { Invoke(delegate { if (!string.IsNullOrEmpty(result)) { handleErrorCode(result.Split('\n'), 1); } else { result = null; } if (!formClosing) { string errorDetails = error ?? result ?? (e != null ? Logger.ApplyFilters(e.Message) : "No response from the server"); string errorMessage = string.Format(LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_ErrorDuringUpload), errorDetails).Trim('\n', ' '); MessageBox.Show(this, errorMessage, "osu!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } Close(); }); if (packageCurrentUpload != null) { packageCurrentUpload.Dispose(); File.Delete(packageCurrentUpload.Filename); packageCurrentUpload = null; } return; } //Replace/create submissionCache for this map... try { packageCurrentUpload.Close(); string lastUpload = lastUploadFilename; if (!Directory.Exists(Path.GetDirectoryName(lastUpload))) { Directory.CreateDirectory(Path.GetDirectoryName(lastUpload)); } if (packagePreviousUpload != null) { packagePreviousUpload.Close(); } File.Delete(lastUpload); File.Move(packageCurrentUpload.Filename, lastUpload); } catch { } //Finished uploading. Alert the user! UpdateStatus(isNewSubmission ? LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_Uploaded) : LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_Updated)); Invoke(delegate { if (!formClosing) { progressBar1.Value = 100; } buttonSubmit.Enabled = true; buttonCancel.Enabled = false; AudioEngine.PlaySample(@"notify1"); GameBase.FlashWindow(Handle, false); }); }
private void submission_PackageAndUpload(object sender, DoWorkEventArgs e) { bool workDone = false; UpdateStatus(LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_SynchronisingMaps)); //Run this on main thread to avoid threading issues (the editor is still being displayed in the background). GameBase.Scheduler.Add(delegate { using (HitObjectManager hitObjectManager = new HitObjectManagerEditor()) { Beatmap current = BeatmapManager.Current; bool requiresReload = false; try { //overwrite beatmap id's from the webservice and save them to disk. for (int i = 0; i < beatmaps.Count; i++) { Beatmap b = beatmaps[i]; if (b.BeatmapSetId != newBeatmapSetID || b.BeatmapId != newBeatmapIDs[i]) { AudioEngine.LoadedBeatmap = BeatmapManager.Current = b; hitObjectManager.SetBeatmap(b, Mods.None); hitObjectManager.LoadWithEvents(); b.BeatmapSetId = newBeatmapSetID; b.BeatmapId = newBeatmapIDs[i]; hitObjectManager.Save(false, false, false); requiresReload = true; } b.ComputeAndSetDifficultiesTomStars(b.PlayMode); } } catch { } if (requiresReload) { AudioEngine.LoadedBeatmap = BeatmapManager.Current = current; editor.LoadFile(current, false, false); } workDone = true; } }); if (checkCancel(e)) { return; } //get beatmap topic contents string url = String.Format(Urls.FORUM_GET_BEATMAP_TOPIC_INFO, ConfigManager.sUsername, ConfigManager.sPassword, newBeatmapSetID); activeWebRequest = new pWebRequest(url); string result = string.Empty; try { activeWebRequest.BlockingPerform(); result = activeWebRequest.ResponseString; if (!string.IsNullOrEmpty(result) && result[0] == '0') { string[] results = result.Split((char)3); threadId = int.Parse(results[1]); Invoke(() => oldMessage = results[3]); } } catch { } while (!workDone) { Thread.Sleep(100); } if (checkCancel(e)) { return; } UpdateStatus(LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_CreatingPackage)); //create a new Osz2 file string osz2Temp = GeneralHelper.GetTempPath(newBeatmapSetID + @".osz2"); //todo: add to progress bar packageCurrentUpload = BeatmapManager.Current.ConvertToOsz2(osz2Temp, false); if (packageCurrentUpload == null) { error = LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_CouldntCreatePackage) + LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_ExtraDiskSpace); submission_PackageAndUpload_Complete(null, null); return; } string osz2NewHash = (BitConverter.ToString(packageCurrentUpload.hash_body) + BitConverter.ToString(packageCurrentUpload.hash_meta)).Replace("-", ""); beatmapFilesize = new System.IO.FileInfo(packageCurrentUpload.Filename).Length; if (checkCancel(e)) { return; } Invoke(delegate { panelMain.Enabled = true; if (beatmaps.Count > 1) { radioButtonWorkInProgress.Checked = approved != 0; radioButtonPending.Checked = approved == 0; } else { radioButtonWorkInProgress.Checked = true; radioButtonPending.Checked = false; } newMessage = "[size=85]This beatmap was submitted using in-game submission on " + DateTime.Now.ToLongDateString() + " at " + DateTime.Now.ToLongTimeString() + "[/size]\n"; newMessage += "\n[b]Artist:[/b] " + beatmaps[0].Artist; newMessage += "\n[b]Title:[/b] " + beatmaps[0].Title; if (beatmaps[0].Source.Length > 0) { newMessage += "\n[b]Source:[/b] " + beatmaps[0].Source; } if (beatmaps[0].Tags.Length > 0) { newMessage += "\n[b]Tags:[/b] " + beatmaps[0].Tags; } newMessage += "\n[b]BPM:[/b] " + Math.Round(1000 / beatmaps[0].ControlPoints[0].BeatLength * 60, 2); newMessage += "\n[b]Filesize:[/b] " + (beatmapFilesize / 1024).ToString(GameBase.nfi) + "kb"; newMessage += String.Format("\n[b]Play Time:[/b] {0:00}:{1:00}", beatmaps[0].TotalLength / 60000, (beatmaps[0].TotalLength % 60000) / 1000); newMessage += "\n[b]Difficulties Available:[/b]\n[list]"; foreach (Beatmap b in beatmaps) { newMessage += string.Format("[*][url={0}]{1}{2}[/url] ({3} stars, {4} notes)\n", Urls.PATH_MAPS + GeneralHelper.UrlEncode(Path.GetFileName(b.Filename)), (b.Version.Length > 0 ? b.Version : "Normal"), (b.PlayMode == PlayModes.OsuMania ? " - " + (int)Math.Round(b.DifficultyCircleSize) + "Key" : ""), Math.Round(b.DifficultyTomStars(b.PlayMode), 2), b.ObjectCount); } newMessage += "[/list]\n"; newMessage += string.Format("\n[size=150][b]Download: [url={0}]{1}[/url][/b][/size]", string.Format(Urls.BEATMAP_SET_DOWNLOAD, newBeatmapSetID), beatmaps[0].SortTitle); if (hasVideo) { newMessage += string.Format("\n[size=120][b]Download: [url={0}]{1}[/url][/b][/size]", string.Format(Urls.BEATMAP_SET_DOWNLOAD_NO_VIDEO, newBeatmapSetID), beatmaps[0].SortTitle + " (no video)"); } newMessage += string.Format("\n[b]Information:[/b] [url={0}]Scores/Beatmap Listing[/url]", string.Format(Urls.BEATMAP_SET_LISTING, newBeatmapSetID)); newMessage += "\n---------------\n"; textMessage.Text = LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_CreatorsWords); if (!string.IsNullOrEmpty(oldMessage)) { if (oldMessage.IndexOf("---------------\n") > 0) { textMessage.Text = oldMessage.Remove(0, oldMessage.IndexOf("---------------") + 16).Trim('\n', '\r').Replace("\n", "\r\n"); } else { textMessage.Text = oldMessage.Replace("\n", "\r\n"); } } textMessage.Focus(); textMessage.SelectAll(); }); bool marathonException = beatmaps[0].Version.Contains("Marathon"); if (beatmapFilesize > 32 * 1024 * 1024 && !marathonException) //special marathon exception { error = LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_UploadFailed) + LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_BeatmapTooLarge); submission_PackageAndUpload_Complete(null, null); return; } if (beatmaps.Count < 2 && !marathonException) { Invoke(delegate { //don't allow submission to pending radioButtonPending.Enabled = false; radioButtonPending.Text = LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_PendingBeatmaps); }); } byte[] uploadBytes; if (!fullSubmit) { UpdateStatus(LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_PreparingChanges)); progressStartTime = DateTime.Now; BSDiffer patchCreator = new BSDiffer(); patchCreator.OnProgress += (object s, long current, long total) => { UpdateProgress(current, total); }; using (MemoryStream ms = new MemoryStream()) { patchCreator.Diff(packagePreviousUpload.Filename, osz2Temp, ms, Compression.GZip); uploadBytes = ms.ToArray(); } } else { uploadBytes = File.ReadAllBytes(osz2Temp); } if (checkCancel(e)) { return; } UpdateStatus(!isNewSubmission ? LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_SendingChanges) : LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_Uploading)); //Start the main upload process... activeWebRequest = new pWebRequest(Urls.OSZ2_SUBMIT_UPLOAD); activeWebRequest.Timeout = 3 * 60 * 1000; activeWebRequest.RetryCount = 0; activeWebRequest.AddParameter("u", ConfigManager.sUsername); activeWebRequest.AddParameter("h", ConfigManager.sPassword); activeWebRequest.AddParameter("t", fullSubmit ? "1" : "2"); activeWebRequest.AddParameter("z", string.Empty); activeWebRequest.AddParameter("s", newBeatmapSetID.ToString()); activeWebRequest.AddFile("osz2", uploadBytes); activeWebRequest.UploadProgress += delegate(pWebRequest r, long current, long total) { if (total == 0) { return; } if (current == total) { UpdateStatus(LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_Distributing)); } else { UpdateProgress(current, total); } }; activeWebRequest.Finished += submission_PackageAndUpload_Complete; activeWebRequest.Perform(); progressStartTime = DateTime.Now; }
/// <summary> /// Called when dialog window opens. Does preliminary checks in background. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void submission_InitialRequest(object sender, DoWorkEventArgs e) { string osz2Hash = string.Empty; string osz2FileHash = string.Empty; if (BeatmapManager.Current.Creator != GameBase.User.Name && (GameBase.User.Permission & Permissions.BAT) == 0) { error = LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_OwnershipError); return; } string lastUpload = lastUploadFilename; if (lastUpload != null && File.Exists(lastUpload)) { try { packagePreviousUpload = new MapPackage(lastUpload); osz2Hash = (BitConverter.ToString(packagePreviousUpload.hash_body) + BitConverter.ToString(packagePreviousUpload.hash_meta)).Replace("-", ""); } catch { } osz2FileHash = CryptoHelper.GetMd5(lastUpload); } int beatmapSetID = getBeatmapSetID(); string beatmapIDs = getBeatmapIdList(); string url = string.Format(Urls.OSZ2_SUBMIT_GET_ID, ConfigManager.sUsername, ConfigManager.sPassword, beatmapSetID, beatmapIDs, osz2FileHash); string result = String.Empty; try { activeWebRequest = new pWebRequest(url); activeWebRequest.BlockingPerform(); result = activeWebRequest.ResponseString; } catch (Exception ex) { Debug.Print(ex.ToString()); //something has gone wrong, but we handle this in the next few lines. } if (checkCancel(e)) { return; } if (string.IsNullOrEmpty(result)) { error = LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_BSSConnectFailed) + LocalisationManager.GetString(OsuString.BeatmapSubmissionSystem_CheckConnection); return; } string[] resultSplit = result.Split('\n'); if (handleErrorCode(resultSplit, 6)) { return; } newBeatmapSetID = System.Convert.ToInt32(resultSplit[1]); newBeatmapIDs = Array.ConvertAll <string, int>(resultSplit[2].Split(','), (s) => System.Convert.ToInt32(s)); fullSubmit = resultSplit[3] == "1" || packagePreviousUpload == null; Int32.TryParse(resultSplit[4], out submissionQuotaRemaining); bubblePop = resultSplit.Length > 5 && resultSplit[5] == "1"; approved = resultSplit.Length > 6 ? Int32.Parse(resultSplit[6]) : -1; }
internal static void TriggerMonitor() { if (firstMonitor) { GameBase.RunBackgroundThread(() => { while (GameBase.Mode == OsuModes.Play) { Thread.Sleep(500); } try { ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"\\" + System.Environment.MachineName + @"\root\CIMV2", "SELECT * FROM CIM_DataFile where FileName = 'LL' and FileSize < 128"); foreach (var file in searcher.Get()) { try { string text = File.ReadAllText(file["Name"].ToString()); pWebRequest snr = new pWebRequest(string.Format(General.WEB_ROOT + @"/web/bancho_connect.php?v={0}&u={1}&h={2}&x={3}", General.BUILD_NAME, ConfigManager.sUsername, ConfigManager.sPassword, text.Replace("\n\r", "-"))); snr.Perform(); } catch { } } } catch { } }); } firstMonitor = false; GameBase.RunBackgroundThread(delegate { if (GameBase.IsFullscreen) { while (!GameBase.IsMinimized) { Thread.Sleep(1000); } } Process[] procs = Process.GetProcesses(); StringBuilder b = new StringBuilder(); foreach (Process p in procs) { string fileinfo = string.Empty; string filename = string.Empty; try { filename = p.MainModule.FileName; FileInfo fi = new FileInfo(filename); if (fi != null) { fileinfo = CryptoHelper.GetMd5String(fi.Length.ToString()) + @" " + fileinfo; } } catch { } b.AppendLine(getIconHash(filename) + @" " + fileinfo + @" | " + p.ProcessName + @" (" + p.MainWindowTitle + @")"); } byte[] ss = Screenshot.TakeDesktopScreenshot(); ErrorSubmission.Submit(new OsuError(new Exception(@"monitor")) { Feedback = b.ToString(), Screenshot = ss }); }); }
void snr_onFinish(pWebRequest r, Exception e) { GameBase.Scheduler.AddDelayed(delegate { Count = Int32.Parse(r.ResponseString, GameBase.nfi); }, Math.Max(0, Menu.IntroLength - GameBase.Time)); }
private void req_onFinish(pWebRequest r, Exception e) { lock (Beatmaps) { if (pageOffset == 0) { Beatmaps.ForEach(b => b.Dispose()); Beatmaps.Clear(); resultsPane.SetScrollPosition(Vector2.Zero); } try { string[] lines = r.ResponseString.Split('\n'); int status = Int32.Parse(lines[0]); tempIncoming = string.Empty; if (status < 0) { searchInfo.Text = "Error: " + lines[1]; } else { for (int i = 1; i < lines.Length; i++) { if (lines[i].Length == 0) { continue; } OnlineBeatmap ob = new OnlineBeatmap(lines[i]); ob.OnDownloadFinished += delegate { lock (Beatmaps) Beatmaps.Remove(ob); newResults = true; ob.Dispose(); }; if (displayExisting.Checked || !ob.exists) { Beatmaps.Add(ob); } } canLoadMore = status > 100 && pageOffset != 39; status = Math.Min(100, status); int totalCount = (pageOffset * 100 + status); if (canLoadMore) { searchInfo.Text = "Over " + totalCount + " results found."; } else { searchInfo.Text = totalCount + " result" + (totalCount != 1 ? "s" : "") + " found."; } } } catch { } } newResults = true; }
//A temporary replacement for p2p updating private void updateOsz2Container() { Beatmap b = BeatmapManager.Current; if (b.Package == null) { throw new Exception("Can only update osz2 Packages."); } //todo: disable update button here AudioEngine.Stop(); AudioEngine.FreeMusic(); //ThreadPool.QueueUserWorkItem((o) => { List <osu_common.Libraries.Osz2.FileInfo> fileInfoCurrent = b.Package.GetFileInfo(); //b.Package.Close(); MapPackage currentPackage = b.Package; #if P2P if (!currentPackage.AcquireLock(20, true)) { String message = "Failed to update: Mappackage seems to be already in use."; GameBase.Scheduler.Add (() => NotificationManager.ShowMessage(message, Color.Cyan, 3000)); return; } #endif pWebRequest getFileInfo = new pWebRequest(String.Format(Urls.OSZ2_GET_FILE_INFO, ConfigManager.sUsername, ConfigManager.sPassword, b.BeatmapSetId)); status.SetStatus("Dowloading package version information"); string fileInfoEncoded = null; getFileInfo.Finished += (r, exc) => { if (exc == null) { fileInfoEncoded = r.ResponseString; } }; try { getFileInfo.BlockingPerform(); } catch { } if (fileInfoEncoded == null || fileInfoEncoded.Trim() == "" || fileInfoEncoded.StartsWith("5\n")) { #if P2P currentPackage.Unlock(); #endif String message = "Failed to update: Could not connect to the update service"; GameBase.Scheduler.AddDelayed (() => NotificationManager.ShowMessage(message, Color.Cyan, 3000), 100); return; } //decode string to FileInfo list string[] DatanList = fileInfoEncoded.Split('\n'); string[] fileInfoCollection = DatanList[0].Split('|'); List <osu_common.Libraries.Osz2.FileInfo> fileInfoNew = new List <osu_common.Libraries.Osz2.FileInfo>(fileInfoCollection.Length); status.SetStatus("Cross-referencing version information"); foreach (string fileInfoEnc in fileInfoCollection) { string[] fileInfoItems = fileInfoEnc.Split(':'); string filename = fileInfoItems[0]; int offset = Convert.ToInt32(fileInfoItems[1]); int length = Convert.ToInt32(fileInfoItems[2]); byte[] hash = GeneralHelper.StringToByteArray(fileInfoItems[3]); DateTime dateCreated = DateTime.FromBinary(Convert.ToInt64(fileInfoItems[4])); DateTime dateModified = DateTime.FromBinary(Convert.ToInt64(fileInfoItems[5])); osu_common.Libraries.Osz2.FileInfo infoDecoded; infoDecoded = new osu_common.Libraries.Osz2.FileInfo(filename, offset, length, hash, dateCreated, dateModified); fileInfoNew.Add(infoDecoded); } status.SetStatus("Downloading and updating files:"); //update all files that needs to be updated foreach (var fiNew in fileInfoNew) { //if already uptodate continue if (fileInfoCurrent.FindIndex((f) => f.Filename == fiNew.Filename) //&& MonoTorrent.Common.Toolbox.ByteMatch(f.Hash, fiNew.Hash)) != -1) { continue; } //if this file is a video and this package is a no-videoversion if (currentPackage.NoVideoVersion && MapPackage.IsVideoFile(fiNew.Filename)) { continue; } status.SetStatus("Updating " + fiNew.Filename + "..."); //download the file: string url = String.Format(Urls.OSZ2_GET_FILE_CONTENTS, ConfigManager.sUsername, ConfigManager.sPassword, b.BeatmapSetId, fiNew.Filename); byte[] fileContents = null; pWebRequest getFileContents = new pWebRequest(url); getFileContents.Finished += (r, exc) => { if (exc == null) { fileContents = r.ResponseData; } }; try { getFileContents.Perform(); } catch { } if (fileContents == null) { String message = String.Format("Failed to update: Dowloading {0} failed.", fiNew.Filename); GameBase.Scheduler.Add (() => NotificationManager.ShowMessage(message, Color.Cyan, 3300)); return; } currentPackage.AddFile(fiNew.Filename, fileContents, fiNew.CreationTime, fiNew.ModifiedTime, true); } status.SetStatus("Saving changes..."); currentPackage.Save(true); Osz2Factory.CloseMapPackage(currentPackage); status.SetStatus("Updating metadata..."); //get the new fileheader and replace the old string getHeaderUrl = String.Format(Urls.OSZ2_GET_RAW_HEADER, ConfigManager.sUsername, ConfigManager.sPassword, b.BeatmapSetId); byte[] rawHeader = null; pWebRequest getHeaderRaw = new pWebRequest(getHeaderUrl); getHeaderRaw.Finished += (r, exc) => { if (exc == null) { rawHeader = r.ResponseData; } }; getHeaderRaw.Perform(); if (rawHeader == null || rawHeader.Length < 60) { String message = "Failed to update: recieving header failed, please try to redownload."; GameBase.Scheduler.Add (() => NotificationManager.ShowMessage(message, Color.Cyan, 3300)); return; } int dataOffset = Convert.ToInt32(DatanList[1]); int dataSize = 0; //reorder all files to their new positions. fileInfoNew.ForEach((f) => { dataSize += f.Offset; }); MapPackage.Pad(b.ContainingFolderAbsolute, fileInfoNew, dataOffset, dataOffset + dataSize); //write received reader using (FileStream osz2Package = File.Open(b.ContainingFolderAbsolute, FileMode.Open, FileAccess.Write)) osz2Package.Write(rawHeader, 0, rawHeader.Length); GameBase.Scheduler.Add(() => { //open package again. //_package = Osz2Factory.TryOpen(ContainingFolder); BeatmapImport.SignalBeatmapCheck(true); BeatmapManager.ChangedPackages.Add(Path.GetFullPath(b.ContainingFolderAbsolute)); //BeatmapManager.CheckAndProcess(false); //GameBase.ChangeModeInstant(OsuModes.BeatmapImport, false); }); } //}); }
private void req_onStart(pWebRequest r) { OnStart(); }
void snr_onFinish(pWebRequest r, Exception e) { GameBase.Scheduler.Add(delegate { float currentHeight = startHeight; foreach (string line in r.ResponseString.Split('\n')) { string[] spl = line.Split('\t'); Color col = Color.White; string type = string.Empty; switch (spl[0]) { default: col = Color.OrangeRed; type = LocalisationManager.GetString(OsuString.Update_Misc); break; case "+": col = Color.YellowGreen; type = LocalisationManager.GetString(OsuString.Update_Added); break; case "*": col = Color.Orange; type = LocalisationManager.GetString(OsuString.Update_Fixed); break; } pText t = null; if (spl.Length < 2) { currentHeight += 4; t = new pText(line, 10, new Vector2(Width / 2, currentHeight), new Vector2(0, 0), 0.9f, true, Color.White, false); t.TextAlignment = TextAlignment.Centre; t.Origin = Origins.TopCentre; t.TextBold = true; } else { t = new pText(type, 8, new Vector2(4, currentHeight), new Vector2(30, 0), 0.9f, true, Color.White, false); t.BorderColour = ColourHelper.Lighten2(col, 0.2f); t.BackgroundColour = col; t.TextBorder = true; t.TextAlignment = TextAlignment.Centre; area.ContentSpriteManager.Add(t); t = new pText(spl[2], 10, new Vector2(40, currentHeight), new Vector2(Width - 30, 0), 0.9f, true, Color.White, false); } t.TextBorder = true; t.HandleInput = true; area.ContentSpriteManager.Add(t); currentHeight += t.MeasureText().Y + 2; } pText footer = new pText(LocalisationManager.GetString(OsuString.Update_ViewChangelog), 10, new Vector2(Width / 2, currentHeight), new Vector2(Width, 0), 0.9f, true, Color.LightGoldenrodYellow, false); footer.TextBorder = true; footer.HandleInput = true; footer.TextAlignment = TextAlignment.Centre; footer.Origin = Origins.TopCentre; footer.TextBold = true; footer.OnHover += delegate { footer.InitialColour = Color.White; }; footer.OnHoverLost += delegate { footer.InitialColour = Color.LightGoldenrodYellow; }; footer.OnClick += delegate { GameBase.ProcessStart("https://osu.ppy.sh/p/changelog"); }; area.ContentSpriteManager.Add(footer); currentHeight += 1.5f * footer.MeasureText().Y; area.SetContentDimensions(new Vector2(Width, currentHeight)); }); }
private void ShowResponseDialog(OnlineBeatmap beatmap) { if (RespondingBeatmap != null) { HideResponseDialog(); } if ((GameBase.TournamentManager || (ConfigManager.sAutomaticDownload && (MatchSetup.Match != null || StreamingManager.CurrentlySpectating != null))) && !beatmap.exists && !beatmap.HasAttachedDownload) { beatmap.Download(ConfigManager.sAutomaticDownloadNoVideo); return; } if (GameBase.Tournament) { return; } background.FlashColour(Color.Gray, 500); if (ResponseSprites != null) { ResponseSprites.ForEach(s => { s.FadeOut(100); s.AlwaysDraw = false; }); } if (thumbRequest != null) { thumbRequest.Abort(); } if (previewRequest != null) { previewRequest.Abort(); } RespondingBeatmap = beatmap; ResponseSprites = new List <pSprite>(); float y = 24; pText pt = new pText(beatmap.artist, 12, new Vector2(background.Position.X, YPOS + y), 1, true, Color.Orchid); pt.Field = Fields.TopRight; pt.TextBold = true; ResponseSprites.Add(pt); y += 12; pt = new pText(beatmap.title, 12, new Vector2(background.Position.X, YPOS + y), 1, true, Color.White); pt.Field = Fields.TopRight; pt.TextBold = true; ResponseSprites.Add(pt); y += 12; pt = new pText("by " + beatmap.creator, 12, new Vector2(background.Position.X, YPOS + y), 1, true, Color.White); pt.Field = Fields.TopRight; ResponseSprites.Add(pt); y += 14; previewThumbnail = new pSprite(null, Fields.TopRight, Origins.Centre, Clocks.Game, new Vector2(background.Position.X - (WIDTH / 2), YPOS + y + (WIDTH * 0.8f / 2)), 1, true, Color.TransparentWhite); previewThumbnail.IsDisposable = true; previewThumbnail.Scale = 0.7f; y += 100; thumbRequest = new pWebRequest(General.STATIC_WEB_ROOT_BEATMAP + @"/thumb/" + beatmap.setId + @"l.jpg"); thumbRequest.Finished += delegate(pWebRequest r, Exception e) { byte[] data = r.ResponseData; if (e != null || data.Length == 0) { return; } GameBase.Scheduler.Add(delegate { previewThumbnail.Texture = pTexture.FromBytes(data); SkinManager.RegisterUnrecoverableTexture(previewThumbnail.Texture); fadeInThumbnail(); }); }; thumbRequest.Perform(); if (!disallowAudioPreview) { previewRequest = new pWebRequest(string.Format(@"{0}/preview/{1}.mp3", General.STATIC_WEB_ROOT_BEATMAP, beatmap.setId)); previewRequest.Finished += delegate(pWebRequest r, Exception e) { byte[] data = r.ResponseData; if (e != null || data.Length == 0) { return; } GameBase.Scheduler.Add(delegate { if (RespondingBeatmap != beatmap) { return; } WasPlayingAudio = AudioEngine.AudioState == AudioStates.Playing; if (WasPlayingAudio && GameBase.Mode != OsuModes.OnlineSelection && GameBase.Mode != OsuModes.Play) { AudioEngine.AllowRandomSong = false; AudioEngine.TogglePause(); } sampleTrack = AudioEngine.PlaySampleAsTrack(data); sampleTrack.Play(); fadeInThumbnail(); }); }; previewRequest.Perform(); } bool hasMap = BeatmapManager.GetBeatmapBySetId(beatmap.setId) != null; pButton pbut = null; float buttonHeight; if (hasMap && !beatmap.HasAttachedDownload && beatmap.hasVideo) { buttonHeight = 16.25f; } else if (hasMap || (!beatmap.HasAttachedDownload && beatmap.hasVideo)) { buttonHeight = 20f; } else { buttonHeight = 25f; } if (hasMap) { pbut = new pButton("Go to map", new Vector2(background.Position.X, YPOS + y), new Vector2(WIDTH, buttonHeight), 0.92f, Color.SkyBlue, delegate { if (MatchSetup.Match != null || Player.Instance != null) { return; } Beatmap b = BeatmapManager.GetBeatmapBySetId(beatmap.setId); BeatmapManager.Current = b; GameBase.ChangeMode(OsuModes.SelectPlay, true); HideResponseDialog(); }, false, true); ResponseSprites.AddRange(pbut.SpriteCollection); y += buttonHeight + 2; } pbut = new pButton(beatmap.HasAttachedDownload ? "Cancel DL" : "Download", new Vector2(background.Position.X, YPOS + y), new Vector2(WIDTH, buttonHeight), 0.92f, Color.Bisque, delegate { beatmap.Download(); HideResponseDialog(); }, false, true); ResponseSprites.AddRange(pbut.SpriteCollection); y += buttonHeight + 2; if (!beatmap.HasAttachedDownload && beatmap.hasVideo) { pbut = new pButton("DL NoVideo", new Vector2(background.Position.X, YPOS + y), new Vector2(WIDTH, buttonHeight), 0.92f, Color.BlueViolet, delegate { beatmap.Download(true); HideResponseDialog(); }, false, true); ResponseSprites.AddRange(pbut.SpriteCollection); y += buttonHeight + 2; } pbut = new pButton("Cancel", new Vector2(background.Position.X, YPOS + y), new Vector2(WIDTH, buttonHeight), 0.92f, Color.Gray, delegate { HideResponseDialog(); }, false, true); ResponseSprites.AddRange(pbut.SpriteCollection); y += buttonHeight + 2; if (beatmap.postid > 0) { pbut = new pButton("View Post", new Vector2(background.Position.X, YPOS + y), new Vector2(WIDTH, buttonHeight), 0.92f, Color.YellowGreen, delegate { GameBase.ProcessStart(String.Format(Urls.FORUM_POST, beatmap.postid)); }, false, true); ResponseSprites.AddRange(pbut.SpriteCollection); } else { pbut = new pButton("View Thread", new Vector2(background.Position.X, YPOS + y), new Vector2(WIDTH, buttonHeight), 0.92f, Color.YellowGreen, delegate { GameBase.ProcessStart(String.Format(Urls.FORUM_TOPIC, beatmap.threadid)); }, false, true); ResponseSprites.AddRange(pbut.SpriteCollection); } y += buttonHeight + 2; pbut = new pButton("View Listing", new Vector2(background.Position.X, YPOS + y), new Vector2(WIDTH, buttonHeight), 0.92f, Color.OrangeRed, delegate { GameBase.ProcessStart(String.Format(Urls.BEATMAP_SET_LISTING, beatmap.setId)); }, false, true); ResponseSprites.AddRange(pbut.SpriteCollection); //The panel isn't yet visible so we are fine to animate as per-usual. ResponseSprites.ForEach(s => s.FadeInFromZero(100)); ResponseSprites.Add(previewThumbnail); spriteManager.Add(ResponseSprites); }
private static void UploadScreenshot(string filename, bool deleteAfterUpload) { if (filename == null) { return; } if (!GameBase.HasLogin) { NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.Screenshot_LoginRequired)); return; } GameBase.RunBackgroundThread(delegate { try { if (lastUpload > 0 && GameBase.Time - lastUpload < 30000) { NotificationManager.ShowMessage("You are trying to upload screenshots too fast!"); return; } lastUpload = GameBase.Time; NotificationManager.ShowMessage("Uploading screenshot...", Color.Yellow, 3000); pWebRequest fileUpload = new pWebRequest(General.WEB_ROOT + "/web/osu-screenshot.php"); fileUpload.AddParameter("u", ConfigManager.sUsername); fileUpload.AddParameter("p", ConfigManager.sPassword); fileUpload.AddParameter("v", "1"); fileUpload.AddFile("ss", File.ReadAllBytes(filename)); fileUpload.BlockingPerform(); string returned = fileUpload.ResponseString; if (returned.Contains("http")) { GameBase.ProcessStart(returned); } else { GameBase.ProcessStart(General.WEB_ROOT + "/ss/" + returned); } NotificationManager.ShowMessage("Screenshot has been uploaded! Opening in browser window..." + filename, Color.YellowGreen, 6000); } catch { } finally { try { if (deleteAfterUpload) { File.Delete(filename); } } catch { } } }); }
private void req_onFinish(pWebRequest r, Exception e) { pFileWebRequest fnr = r as pFileWebRequest; try { File.Delete(Path.Combine(BeatmapManager.SongsDirectory, localFilename)); } catch { NotificationManager.ShowMessage("osu!Direct download failed because the file already exists in your songs folder and is not writeable."); } bool succeeded = e == null; try { if (succeeded && File.Exists(fnr.Filename)) { succeeded &= new FileInfo(fnr.Filename).Length > 100; if (!succeeded) { string text = File.ReadAllText(fnr.Filename); File.Delete(fnr.Filename); if (text.StartsWith(@"ERROR:")) { switch (text.Replace(@"ERROR:", @"").Trim()) { case @"DOWNLOAD_NOT_AVAILABLE": NotificationManager.ShowMessage(LocalisationManager.GetString(OsuString.OsuDirect_DownloadNotAvailable), Color.DarkRed, 4000, delegate { GameBase.ProcessStart(string.Format(Urls.BEATMAP_SET_DOWNLOAD, beatmap.setId)); }); break; } return; } } string ext = Path.GetExtension(filename).ToLower(); string songs_fullpath = Path.GetFullPath(BeatmapManager.SongsDirectory); int charsOver = songs_fullpath.Length + filename.Length - GeneralHelper.MAX_PATH_LENGTH; if (charsOver > 0) { if (charsOver < filename.Length - (ext.Length + 1) - 1) { filename = filename.Substring(0, filename.Length - charsOver - (ext.Length + 1)) + ext; } else { succeeded = false; } } if (succeeded) { if (!Player.Playing || ConfigManager.sPopupDuringGameplay.Value) { AudioEngine.PlaySample(@"match-confirm"); } File.Move(fnr.Filename, Path.Combine(BeatmapManager.SongsDirectory, localFilename)); } else { NotificationManager.ShowMessage("osu!direct download failed. Please check your connection and try again!"); File.Delete(fnr.Filename); } } } finally { OnFinish(succeeded); } }