internal void PackageOsz2() { if (hitObjectManager.Beatmap.InOszContainer) { return; } SaveFile(); GameBase.MenuActive = true; SaveFileDialog s = new SaveFileDialog(); s.RestoreDirectory = true; s.AddExtension = true; s.Filter = @"Packaged Beatmaps|*.osz2"; s.DefaultExt = @".osz2"; s.FileName = GeneralHelper.WindowsFilenameStrip(hitObjectManager.Beatmap.SortTitle); DialogResult r = s.ShowDialog(GameBase.Form); if (r == DialogResult.OK) { MapPackage pkg = hitObjectManager.Beatmap.ConvertToOsz2(s.FileName, false); pkg.Close(); } GameBase.MenuActive = false; }
// returns null if already openened or writelocked public static MapPackage TryOpen(string path, bool createIfNotFound, bool metadataOnly) { lock (locker) { string absolute = Path.GetFullPath(path).ToLower(); MapPackage package = openPackages.Find(s => s.Filename.Equals(absolute)); if (package == null) { try { package = new MapPackage(absolute, null, createIfNotFound, metadataOnly); } #if DEBUG catch (ExecutionEngineException) #else catch (Exception) #endif { return(null); } openPackages.Add(package); } //we now use the locker built into the mappackage //lockInternal(package); return(package); } }
/// <summary> /// Get map package by coordinates. /// </summary> /// <returns>MapPackage instance</returns> public MapPackage getMapPkg(double latitude, double longitude, int zoom) { MapPackage pkg = this.mapSourceMem.findMapPkg(latitude, longitude, zoom); if (pkg == null) { pkg = this.mapSourceHdd.findMapPkg(latitude, longitude, zoom); if (pkg == null) { pkg = this.mapSourceWeb.findMapPkg(latitude, longitude, zoom); } if (pkg != null) { this.mapSourceMem.putMapPkg(pkg); } else { string msg = "Map package can't be found for location: (" + latitude + "; " + longitude + "), zoom: " + zoom; Debug.WriteLine("MapSourceManager: getMapPkg: " + msg); throw new MapNotFoundException(msg); } } return(pkg); }
public void Dispose() { if (package != null) { package.Dispose(); package = null; } }
/// <summary> /// Put map package to the source. /// </summary> public void putMapPkg(MapPackage mapPkg) { if (this.recentlyUsedMapPkgs.Count >= CACHE_SIZE) { this.recentlyUsedMapPkgs[0].freeParts(); this.recentlyUsedMapPkgs.RemoveAt(0); } this.recentlyUsedMapPkgs.Add(mapPkg); }
public Stream GetFileStream(string filename) { MapPackage p = Package; if (p == null) { return(null); } return(p.GetFile(filename)); }
public int PatchMappackageWithKey(string Package, byte[] Key = null) { string Osz2PatchFilename = s3getToTemp("working/" + Package.Replace(".osz2", ".patch"), true); if (Osz2PatchFilename == null) { return((int)UpdateResponseCode.FileDoesNotExist); } string Osz2Filename = s3getToTemp("osz2/" + Package); if (Osz2Filename == null) { return((int)UpdateResponseCode.FileDoesNotExist); } string Osz2FilenameTemp = Osz2Filename + ".temp"; if (!MapPackage.UpdateFromPatch(Osz2Filename, Osz2PatchFilename, Osz2FilenameTemp)) { File.Delete(Osz2PatchFilename); File.Delete(Osz2FilenameTemp); return((int)UpdateResponseCode.UnknownError); } File.Delete(Osz2Filename); File.Move(Osz2FilenameTemp, Osz2Filename); //check if updated mappackage is valid UpdateResponseCode code = DoMapPackageActionSafe((M) => { return(UpdateResponseCode.UpdateSuccessful); }, Osz2Filename, Key, false, false); if (code != UpdateResponseCode.UpdateSuccessful) { return((int)code); } //copy patched file back to the original try { //when replacing failed it will automaticaly be restored to the previous version s3putFile("osz2/" + Package, Osz2Filename); } catch (Exception e) { log(e); //todo add logger here code = UpdateResponseCode.CopyingFailed; } finally { File.Delete(Osz2PatchFilename); } return((int)code); }
public int ChangeKey(string SourcePackage, string TargetPackage, byte[] OldKey, byte[] NewKey) { log("Changing key for {0} / {1}", SourcePackage, TargetPackage); string osz2FilenameOld = s3getToTemp("osz2/" + SourcePackage); string osz2FilenameNew = osz2FilenameOld + ".new"; try { //ensure an existing new file doesn't existing exist. File.Delete(osz2FilenameNew); if (!File.Exists(osz2FilenameOld)) { log("couldn't find local file {0}", osz2FilenameOld); return((int)UpdateResponseCode.FileDoesNotExist); } using (MapPackage oldPackage = new MapPackage(osz2FilenameOld, OldKey, false, false)) using (MapPackage newPackage = new MapPackage(osz2FilenameNew, NewKey, true, false)) { Dictionary <MapMetaType, string> metaData = oldPackage.GetAllMetadata(); foreach (KeyValuePair <MapMetaType, string> mapMeta in metaData) { newPackage.AddMetadata(mapMeta.Key, mapMeta.Value); } List <FileInfo> fileInfo = oldPackage.GetFileInfo(); foreach (FileInfo fo in fileInfo) { using (var br = new BinaryReader(oldPackage.GetFile(fo.Filename))) { newPackage.AddFile(fo.Filename, br.ReadBytes((int)br.BaseStream.Length), fo.CreationTime, fo.ModifiedTime); } } newPackage.Save(); } s3putFile("osz2/" + TargetPackage, osz2FilenameNew); File.Delete(osz2FilenameNew); } catch (Exception e) { File.Delete(osz2FilenameOld); File.Delete(osz2FilenameNew); log(e); } return((int)UpdateResponseCode.UpdateSuccessful); }
/// <summary> /// Calls a MapPackageAction in a safe environment by catching all the exceptions /// and translating them to appropiate responsecodes. /// </summary> /// <param name="Action">A MapPackageAction which updates the osz2 file in the save environment</param> /// <param name="MappackageFile">Path to the osz2 fileparam> /// <param name="Key">The key used to decrypt or encrypt the mappackage</param> /// <param name="SaveData">Whether to save the data after using the custom defined action on the beatmap</param> /// <returns>the UpdateResponseCode of the custom defined action when no exception has occured /// while loading the beatmap(osz2) file, or a failed UpdateResponseCode when there has.</returns> private UpdateResponseCode DoMapPackageActionSafe(MapPackageAction Action, string MappackageFile, byte[] Key, bool SaveData, bool MetadataOnly) { string originalPath = MappackageFile; if (!File.Exists(MappackageFile)) { MappackageFile = s3getToTemp("osz2/" + MappackageFile); } else { originalPath = Path.GetFileName(originalPath); } UpdateResponseCode CustomResponseCode; if (!File.Exists(MappackageFile)) { return(UpdateResponseCode.FileDoesNotExist); } try { using (MapPackage Osz2Beatmap = new MapPackage(MappackageFile, Key, false, MetadataOnly)) { CustomResponseCode = Action(Osz2Beatmap); if (CustomResponseCode == UpdateResponseCode.UpdateSuccessful && SaveData) { Osz2Beatmap.Save(); } Osz2Beatmap.Close(); } if (CustomResponseCode == UpdateResponseCode.UpdateSuccessful && SaveData) { s3putFile("osz2/" + originalPath, MappackageFile); } } catch (IOException e) { log(e); return(UpdateResponseCode.Osz2Corrupted); } catch (Exception e) { log(e); return(UpdateResponseCode.UnknownError); } finally { } return(CustomResponseCode); }
private MapPackage parseMapXml(string pkgName, string pathToMapXml) { // load xml document XmlDocument docMapXml = new XmlDocument(); docMapXml.Load(pathToMapXml); // get description XmlNode descrNode = docMapXml.SelectSingleNode("/map/description"); string descr = ""; // description isn't required if (descrNode != null) { descr = descrNode.InnerText; } // get top left corner latitude XmlNode topLeftLatitudeNode = docMapXml.SelectSingleNode( "/map/coordinates/topLeft/latitude"); double topLeftLatitude = parseCoordinate(topLeftLatitudeNode.InnerText); // get top left corner longitude XmlNode topLeftLongitudeNode = docMapXml.SelectSingleNode( "/map/coordinates/topLeft/longitude"); double topLeftLongitude = parseCoordinate(topLeftLongitudeNode.InnerText); // get bottom right corner latitude XmlNode bottomRightLatitudeNode = docMapXml.SelectSingleNode( "/map/coordinates/bottomRight/latitude"); double bottomRightLatitude = parseCoordinate(bottomRightLatitudeNode.InnerText); // get bottom right corner longitude XmlNode bottomRightLongitudeNode = docMapXml.SelectSingleNode( "/map/coordinates/bottomRight/longitude"); double bottomRightLongitude = parseCoordinate(bottomRightLongitudeNode.InnerText); // get parts image format XmlNode partsFormatNode = docMapXml.SelectSingleNode("/map/parts/format"); string partsFormat = ""; // parts format aren't required if (partsFormatNode != null) { partsFormat = partsFormatNode.InnerText; } MapPackage mapPkg = new MapPackage(pkgName, topLeftLatitude, topLeftLongitude, bottomRightLatitude, bottomRightLongitude); if (partsFormat != "") { mapPkg.setPartsFormat(partsFormat); } return(mapPkg); }
public void loadImages(MapPackage pkg) { Hashtable parts = new Hashtable(); try { string pathToParts = this.mapsDir + "\\zoom_" + pkg.getZoom() + "\\" + pkg.getName() + "\\parts"; DirectoryInfo partsDirInfo = new DirectoryInfo(pathToParts); string searchPattern = "*"; if (pkg.getPartsFormat() != "") { searchPattern += "." + pkg.getPartsFormat(); } foreach (FileInfo partFileInfo in partsDirInfo.GetFiles(searchPattern)) { String partFileName = partFileInfo.Name; // remove extension char[] s = ".".ToCharArray(); String name = partFileName.Split(s)[0]; // get part coordinates (not geografical) s = "_".ToCharArray(); String[] pointStr = name.Split(s); // NOTE: part images are named inversely, row number is first then col number Point p = new Point(Convert.ToInt32(pointStr[1]), Convert.ToInt32(pointStr[0])); Bitmap img = new Bitmap(pathToParts + "\\" + partFileInfo.ToString()); parts[p] = img; } } catch (Exception e) { Debug.WriteLine("MapPkgRepository: loadImages: error during images load!"); throw new MapPkgRepositoryException("error during images load", e); } try { // after successfully loading parts set them in map pkg foreach (DictionaryEntry part in parts) { pkg.setPart((Point)part.Key, (Bitmap)part.Value); } } catch (Exception e) { pkg.freeParts(); Debug.WriteLine("MapPkgRepository: loadImages: error during images put to map pkg!"); throw new MapPkgRepositoryException("error during images put to map pkg", e); } }
public static void CloseMapPackage(MapPackage package) { lock (locker) { int index = openPackages.IndexOf(package); package.Close(); openPackages.Remove(package); if (index == -1) { return; } } }
/* * Create available map packages list * by reading maps directory. */ public void readMapsDir() { string msg = "Reading map pkg: "; this.availableMapPkgs = new List <MapPackage>(); string zoomMapsDir = this.mapsDir + "\\zoom_" + this.zoom; DirectoryInfo[] dirs; try { DirectoryInfo dirInfo = new DirectoryInfo(zoomMapsDir); dirs = dirInfo.GetDirectories(); } catch (Exception e) { Debug.WriteLine("MapSourceHdd: readMapsDir: can't read zoom maps dir: " + zoomMapsDir); throw new MapSourceException("error reading zoom maps dir", e); } int i = 0; foreach (DirectoryInfo dir in dirs) { if (loadingMapPkgEvent != null) { loadingMapPkgEvent(msg + i + "/" + dirs.Length); } FileInfo[] mapFileInfo = dir.GetFiles("map.xml"); if (mapFileInfo.Length > 0) { Debug.WriteLine("MapSourceHdd: readMapsDir(): found map package, dir: " + dir.Name); string mapPkgName = dir.Name; try { MapPackage mapPkg = this.mapPkgMapperHdd.getWithoutImages(mapPkgName, this.zoom); this.availableMapPkgs.Add(mapPkg); //Debug.WriteLine("MapSourceHdd: readMapsDir: added map packege '" + mapPkgName + "'"); } catch (MapPkgRepositoryException e) { Debug.WriteLine("MapSourceHdd: readMapsDir: couldn't add map packege '" + mapPkgName + "' due to error: " + e.Message); throw new MapSourceException("error adding map package", e); } } i++; } }
/// <summary> /// Find map package by coordinates in the source. /// </summary> /// <returns>MapPackage instance.</returns> public MapPackage findMapPkg(double latitude, double longitude, int zoom) { //foreach (MapPackage mapPkg in this.recentlyUsedMapPkgs) // iterate in reverse to start from the newest for (int i = this.recentlyUsedMapPkgs.Count - 1; i >= 0; i--) { MapPackage mapPkg = this.recentlyUsedMapPkgs[i]; if (mapPkg.getZoom() == zoom && mapPkg.coordinatesMatches(latitude, longitude)) { //Debug.WriteLine("MapSourceMem: findMapPkg: found map pkg: " + mapPkg); return(mapPkg); } } Debug.WriteLine("MapSourceMem: findMapPkg: not found pkg for: (" + latitude + "; " + longitude + "), zoom: " + zoom); return(null); }
private void SetDifficulty(Difficulty newDifficulty, bool force = false) { bool isNewDifficulty = Player.Difficulty != newDifficulty || force; velocity = 0; if (Player.Beatmap == null) { return; } MapPackage package = Player.Beatmap.Package; if (package == null) { return; } if (isNewDifficulty) { if (!force) { AudioEngine.PlaySample(OsuSamples.ButtonTap); } string versions = package.GetMetadata(MapMetaType.Version); if (versions != null && !versions.Contains(newDifficulty.ToString())) { /*if (Player.Difficulty == Difficulty.Easy) * //came from easy -> expert; drop back on normal! * Player.Difficulty = Difficulty.Normal; * else*/ { isNewDifficulty = false; pendingModeChange = false; } } else { Player.Difficulty = newDifficulty; } } updateModeSelectionArrows(isNewDifficulty); }
internal void PackageOsz() { Beatmap b = hitObjectManager.Beatmap; if (b.InOszContainer) { return; } SaveFile(); DeleteUnnecessaryFiles(); GameBase.PackageFile(b.SortTitle + @".osz", b.ContainingFolderAbsolute); #if DEBUG MapPackage p = b.ConvertToOsz2(Path.Combine(GameBase.EXPORT_FOLDER, GeneralHelper.WindowsFilenameStrip(b.SortTitle) + @".osz2"), false); Osz2Factory.CloseMapPackage(p); #endif }
// Get map package which is neighbour for given in specified direction. public MapPackage getNeighbourMapPkg(MapPackage pkg, Point direction, int zoom) { if (direction.X != -1 && direction.X != 0 && direction.X != 1 || direction.Y != -1 && direction.Y != 0 && direction.Y != 1) { throw new MapNotFoundException("Bad direction!"); } double topLeftLongitude = pkg.getTopLeftLongitude(); double topLeftLatitude = pkg.getTopLeftLatitude(); double bottomRightLongitude = pkg.getBottomRightLongitude(); double bottomRightLatitude = pkg.getBottomRightLatitude(); double longitude = (topLeftLongitude + bottomRightLongitude) / 2; double latitude = (topLeftLatitude + bottomRightLatitude) / 2; switch (direction.X) { case 1: longitude = bottomRightLongitude + 0.000001; break; case -1: longitude = topLeftLongitude - 0.000001; break; } // NOTE: y has inverted direction in map context switch (direction.Y) { case 1: latitude = bottomRightLatitude - 0.000001; break; case -1: latitude = topLeftLatitude + 0.000001; break; } return(getMapPkg(latitude, longitude, zoom)); }
public string GetVideoInfo(string Package, byte[] Key) { string videoInfo = null; UpdateResponseCode code = DoMapPackageActionSafe( (M) => { int offset, length; string name = String.Empty; M.getVideoOffset(out offset, out length); if (offset == -1) { return(UpdateResponseCode.UpdateSuccessful); } name = M.GetFileInfo().Find((F) => MapPackage.IsVideoFile(F.Filename)).Filename; videoInfo = String.Format("{0},{1},{2}", name, length, offset); return(UpdateResponseCode.UpdateSuccessful); }, Package, Key, false, false); return(videoInfo); }
private void retrieveCurrentMapPkg() { double latitude = this.currentGpsLocation.getLatitude(); double longitude = this.currentGpsLocation.getLongitude(); // when current map pkg doesn't match, get pkg from repository if (!(this.currentMapPkg != null && this.currentMapPkg.coordinatesMatches(latitude, longitude) && this.currentMapPkg.getZoom() == this.currentZoom)) { try { // get map package from repository this.currentMapPkg = this.mapPkgRepository.getMapPkg(latitude, longitude, this.currentZoom); } catch (MapNotFoundException e) { this.currentMapPkg = null; // map pkg for current location doesn't exist in repository this.mapDisplayer.displayMessage("No map for location.", 2000, Color.Red); return; } } }
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; }
private static void writePackage(string oscFilename, string osz2Filename, string audioFilename, List <BeatmapDifficulty> difficulties, List <string> ordered) { bool isPreview = osz2Filename.Contains("_preview"); int hitObjectCutoff = 0; using (StreamWriter output = new StreamWriter(oscFilename)) { //write headers first (use first difficulty as arbitrary source) foreach (string l in headerContent) { if (isPreview) { if (l.StartsWith("Bookmarks:") && osz2Filename.Contains("_preview")) { //may need to double up on bookmarks if they don't occur often often List <int> switchPoints = Player.Beatmap.StreamSwitchPoints; if (switchPoints.Count < 10 || switchPoints[9] > 60000) { string switchString = "Bookmarks:"; foreach (int s in switchPoints) { switchString += s.ToString(nfi) + ","; switchString += s.ToString(nfi) + ","; //double bookmark hack for previews } output.WriteLine(switchString.Trim(',')); hitObjectCutoff = switchPoints.Count < 10 ? switchPoints[4] : switchPoints[9]; continue; } } } output.WriteLine(l); } //keep track of how many hitObject lines are remaining for each difficulty int[] linesRemaining = new int[difficulties.Count]; for (int i = 0; i < difficulties.Count; i++) { linesRemaining[i] = difficulties[i] == null ? 0 : difficulties[i].HitObjectLines.Count; } int currentTime = 0; while (!linesRemaining.All(i => i == 0)) { int bestMatchDifficulty = -1; HitObjectLine bestMatchLine = null; for (int i = 0; i < difficulties.Count; i++) { if (linesRemaining[i] == 0) { continue; } int holOffset = difficulties[i].HitObjectLines.Count - linesRemaining[i]; HitObjectLine line = difficulties[i].HitObjectLines[holOffset]; if (isPreview && hitObjectCutoff > 0 && line.Time > hitObjectCutoff) { linesRemaining[i]--; continue; } if (line.Time >= currentTime && (bestMatchLine == null || line.Time < bestMatchLine.Time)) { bestMatchDifficulty = i; bestMatchLine = line; } } if (bestMatchLine != null) { output.WriteLine(bestMatchDifficulty + "," + bestMatchLine.StringRepresentation); linesRemaining[bestMatchDifficulty]--; } } } using (MapPackage package = new MapPackage(osz2Filename, true)) { package.AddMetadata(MapMetaType.BeatmapSetID, "0"); string versionsAvailable = ""; if (ordered[0] != null) { versionsAvailable += "|Easy"; } if (ordered[1] != null) { versionsAvailable += "|Normal"; } if (ordered[2] != null) { versionsAvailable += "|Hard"; } if (ordered[3] != null) { versionsAvailable += "|Expert"; } package.AddMetadata(MapMetaType.Version, versionsAvailable.Trim('|')); if (string.IsNullOrEmpty(audioFilename)) { throw new Exception("FATAL ERROR: audio file not found"); } package.AddFile(Path.GetFileName(oscFilename), oscFilename, DateTime.MinValue, DateTime.MinValue); if (isPreview) { if (!File.Exists(audioFilename.Replace(".m4a", "_lq.m4a"))) { Console.WriteLine("WARNING: missing preview audio file (_lq.m4a)"); return; } package.AddFile("audio.m4a", audioFilename.Replace(".m4a", "_lq.m4a"), DateTime.MinValue, DateTime.MinValue); } else { package.AddFile(audioFilename.EndsWith(".m4a") ? "audio.m4a" : "audio.mp3", audioFilename, DateTime.MinValue, DateTime.MinValue); } string dir = Path.GetDirectoryName(audioFilename); string metadata = dir + "\\metadata.txt"; if (File.Exists(metadata)) { foreach (string line in File.ReadAllLines(metadata)) { if (line.Length == 0) { continue; } string[] var = line.Split(':'); string key = string.Empty; string val = string.Empty; if (var.Length > 1) { key = line.Substring(0, line.IndexOf(':')); val = line.Substring(line.IndexOf(':') + 1).Trim(); MapMetaType t = (MapMetaType)Enum.Parse(typeof(MapMetaType), key, true); package.AddMetadata(t, val); } } } if (isPreview) { package.AddMetadata(MapMetaType.Revision, "preview"); } string thumb = dir + "\\thumb-128.jpg"; if (File.Exists(thumb)) { package.AddFile("thumb-128.jpg", thumb, DateTime.MinValue, DateTime.MinValue); } thumb = Path.GetDirectoryName(audioFilename) + "\\thumb-256.jpg"; if (File.Exists(thumb)) { package.AddFile("thumb-256.jpg", thumb, DateTime.MinValue, DateTime.MinValue); } thumb = Path.GetDirectoryName(audioFilename) + "\\thumb-512.jpg"; if (File.Exists(thumb)) { package.AddFile("thumb-512.jpg", thumb, DateTime.MinValue, DateTime.MinValue); } package.Save(); } }
private static void lockInternal(MapPackage package) { openPackages.Add(package); Waithandles.Add(new AutoResetEvent(false)); }
/// <summary> /// Put map package to the source. /// </summary> public void putMapPkg(MapPackage mapPkg) { // will be useful when map downloaded from web throw new Exception("The method or operation is not implemented."); }
/// <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; }
public void save(MapPackage pkg) { throw new System.NotImplementedException(); }
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); }); }
//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); }); } //}); }
// TODO: this method is too big public void createNew() { Debug.WriteLine("----- createCurrentView -----", ToString()); // container to keep map parts which create current map view Hashtable viewParts = new Hashtable(); // get current gps coordinates double latitude = this.currentGpsLocation.getLatitude(); double longitude = this.currentGpsLocation.getLongitude(); //Debug.WriteLine("latitude: " + latitude + ", longitude: " + longitude, this.ToString()); // get point which indicates part image for the location Point partPoint = this.currentMapPkg.getPartPoint(latitude, longitude); Debug.WriteLine("partPoint: " + PointUtil.pointStr(partPoint), ToString()); // get location (pixel coordinates) inside part image Point insidePartPosition = this.currentMapPkg.getInsidePartPosition(latitude, longitude); //Debug.WriteLine("insidePartPosition: (" + insidePartPosition.X + "; " + insidePartPosition.Y + ")", this.ToString()); // add center MapView point Point centerViewPoint = new Point(1, 1); viewParts[centerViewPoint] = this.currentMapPkg.getPart(partPoint); // map view has only sense when there is center map part if (viewParts[centerViewPoint] == null) { Debug.WriteLine("Can't get center part! viewParts[centerViewPoint] is null - skipping.", this.ToString()); // return when center part is null this.currentMapVeiw = null; return; } // add neighbours of center point foreach (DictionaryEntry entry in this.pointSurroundings) { Point directionPoint = (Point)entry.Value; Debug.WriteLine("directionPoint: " + PointUtil.pointStr(directionPoint), ToString()); Point viewNeighbour = PointMath.addPoints(centerViewPoint, directionPoint); Point mapNeighbour = PointMath.addPoints(partPoint, directionPoint); try { viewParts[viewNeighbour] = this.currentMapPkg.getPart(mapNeighbour); if (viewParts[viewNeighbour] == null) { Debug.WriteLine("looking for view neighbour:", this.ToString()); MapPackage neighbourPkg = null; int neighbourDirectionX = 0; if (mapNeighbour.X > this.currentMapPkg.getMaxX()) { neighbourDirectionX = 1; } if (mapNeighbour.X < 0) { neighbourDirectionX = -1; } int neighbourDirectionY = 0; if (mapNeighbour.Y > this.currentMapPkg.getMaxY()) { neighbourDirectionY = 1; } if (mapNeighbour.Y < 0) { neighbourDirectionY = -1; } Point neighbourDirection = new Point(neighbourDirectionX, neighbourDirectionY); try { Debug.WriteLine(" trying to get neighbour pkg for neighbour point: " + PointUtil.pointStr(neighbourDirection), ToString()); // get neighbour map package neighbourPkg = this.mapPkgRepository.getNeighbourMapPkg(this.currentMapPkg, neighbourDirection, this.currentZoom); } catch (MapNotFoundException e) { Debug.WriteLine(" Can't get neighbour pkg for: " + this.currentMapPkg + ", dircetion: (" + directionPoint.X + "; " + directionPoint.Y + "), ERROR: " + e.Message, this.ToString()); } if (neighbourPkg != null) { if (mapNeighbour.X > this.currentMapPkg.getMaxX()) { mapNeighbour.X = 0; } if (mapNeighbour.X < 0) { mapNeighbour.X = neighbourPkg.getMaxX(); } if (mapNeighbour.Y > this.currentMapPkg.getMaxY()) { mapNeighbour.Y = 0; } if (mapNeighbour.Y < 0) { mapNeighbour.Y = neighbourPkg.getMaxY(); } Debug.WriteLine(" getting map part from neighbour pkg for point: " + PointUtil.pointStr(mapNeighbour), this.ToString()); viewParts[viewNeighbour] = neighbourPkg.getPart(mapNeighbour); } } else { Debug.WriteLine("view neighbour ok", this.ToString()); } } catch (Exception e) { Debug.WriteLine("Can't get neighbour(" + entry.Key + ")! ERROR: " + e.Message, this.ToString()); } } // create map view MapView mapView = new MapView(this.currentGpsLocation, insidePartPosition, viewParts, this.orderingPoints); mapView.setLatitudePerPixel(this.currentMapPkg.getLatitudePerPixel()); mapView.setLongitudePerPixel(this.currentMapPkg.getLongitudePerPixel()); Area mapViewArea = createMapViewArea(mapView); Area centerImgArea = createMapViewAreaForCenterImg(mapView); mapView.setArea(mapViewArea); mapView.setCenterImgArea(centerImgArea); Debug.WriteLine("-----------------------------\n", ToString()); this.currentMapVeiw = mapView; }
/// <summary> /// Put map package to the source. /// </summary> public void putMapPkg(MapPackage mapPkg) { throw new Exception("The method or operation is not implemented."); }
public void update(GpsLocation currentGpsLocation, MapPackage currentMapPkg, int currentZoom) { this.currentGpsLocation = currentGpsLocation; this.currentMapPkg = currentMapPkg; this.currentZoom = currentZoom; }