public static ResourceData ToResourceData(Resource r) { var ret = new ResourceData() { ResourceID = r.ResourceID, InternalName = r.InternalName, ResourceType = r.TypeID, Dependencies = r.ResourceDependencies.Select(x => x.NeedsInternalName).ToList(), FeaturedOrder = r.FeaturedOrder, }; return ret; }
public override string Arm(ServerBattle battle, Say e, string arguments = null) { if (string.IsNullOrEmpty(arguments)) arguments = battle.server.Game ?? "zk:stable"; game = MapPicker.FindResources(ResourceType.Mod, arguments).FirstOrDefault(); if (game == null) { battle.Respond(e, "Cannot find such game."); return null; } return $"Change game to {game.RapidTag} {game.InternalName}?"; }
public override string Arm(ServerBattle battle, Say e, string arguments = null) { map = string.IsNullOrEmpty(arguments) ? MapPicker.GetRecommendedMap(battle.GetContext()) : MapPicker.FindResources(ResourceType.Map, arguments).FirstOrDefault(); if (map == null) { battle.Respond(e, "Cannot find such map."); return null; } return $"Change map to {map.InternalName} {GlobalConst.BaseSiteUrl}/Maps/Detail/{map.ResourceID} ?"; }
public static ResourceData ToResourceData(Resource r) { var ret = new ResourceData() { ResourceID = r.ResourceID, InternalName = r.InternalName, ResourceType = r.TypeID, Dependencies = r.ResourceDependencies.Select(x => x.NeedsInternalName).ToList(), MapIs1v1 = r.MapIs1v1, MapIsTeams = r.MapIsTeams, MapIsFfa = r.MapIsFfa, MapIsSpecial = r.MapIsSpecial, MapSupportLevel = r.MapSupportLevel }; return ret; }
static void StoreMetadata(string md5, Resource resource, byte[] serializedData, byte[] torrentData, byte[] minimap, byte[] metalMap, byte[] heightMap) { var file = String.Format("{0}/{1}", Global.MapPath("~/Resources"), resource.InternalName.EscapePath()); resource.LastChange = DateTime.UtcNow; if (minimap != null) File.WriteAllBytes(String.Format("{0}.minimap.jpg", file), minimap); if (metalMap != null) File.WriteAllBytes(String.Format("{0}.metalmap.jpg", file), metalMap); if (heightMap != null) File.WriteAllBytes(String.Format("{0}.heightmap.jpg", file), heightMap); if (torrentData != null) File.WriteAllBytes(GetTorrentPath(resource.InternalName, md5), torrentData); if (serializedData != null) { File.WriteAllBytes(String.Format("{0}.metadata.xml.gz", file), serializedData); if (minimap != null) { var map = (Map)new XmlSerializer(typeof(Map)).Deserialize(new MemoryStream(serializedData.Decompress())); if (string.IsNullOrEmpty(resource.AuthorName)) { if (!string.IsNullOrEmpty(map.Author)) resource.AuthorName = map.Author; else { if (!string.IsNullOrEmpty(map.Description)) { var m = Regex.Match(map.Description, "by ([\\w]+)", RegexOptions.IgnoreCase); if (m.Success) resource.AuthorName = m.Groups[1].Value; } } } if (resource.MapIsSpecial == null) resource.MapIsSpecial = map.ExtractorRadius > 120 || map.MaxWind > 40; resource.MapSizeSquared = (map.Size.Width/512)*(map.Size.Height/512); resource.MapSizeRatio = (float)map.Size.Width/map.Size.Height; resource.MapWidth = map.Size.Width/512; resource.MapHeight = map.Size.Height/512; using (var im = Image.FromStream(new MemoryStream(minimap))) { int w, h; if (resource.MapSizeRatio > 1) { w = ThumbnailSize; h = (int)(w/resource.MapSizeRatio); } else { h = ThumbnailSize; w = (int)(h*resource.MapSizeRatio); } using (var correctMinimap = new Bitmap(w, h, PixelFormat.Format24bppRgb)) { using (var graphics = Graphics.FromImage(correctMinimap)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(im, 0, 0, w, h); } var jgpEncoder = ImageCodecInfo.GetImageEncoders().First(x => x.FormatID == ImageFormat.Jpeg.Guid); var encoderParams = new EncoderParameters(1); encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L); var target = String.Format("{0}/{1}.thumbnail.jpg", Global.MapPath("~/Resources"), resource.InternalName.EscapePath()); correctMinimap.Save(target, jgpEncoder, encoderParams); } } } } }
public static void RemoveResourceFiles(Resource resource) { var file = String.Format("{0}/{1}", Global.MapPath("~/Resources"), resource.InternalName.EscapePath()); Utils.SafeDelete(String.Format("{0}.minimap.jpg", file)); Utils.SafeDelete(String.Format("{0}.thumbnail.jpg", file)); Utils.SafeDelete(String.Format("{0}.heightmap.jpg", file)); Utils.SafeDelete(String.Format("{0}.metalmap.jpg", file)); Utils.SafeDelete(String.Format("{0}.metadata.xml.gz", file)); foreach (var content in resource.ResourceContentFiles) Utils.SafeDelete(GetTorrentPath(content)); }
public static ReturnValue RegisterResource(int apiVersion, string springVersion, string md5, int length, ResourceType resourceType, string archiveName, string internalName, byte[] serializedData, List<string> dependencies, byte[] minimap, byte[] metalMap, byte[] heightMap, byte[] torrentData) { if (md5 == null) throw new ArgumentNullException("md5"); if (archiveName == null) throw new ArgumentNullException("archiveName"); if (internalName == null) throw new ArgumentNullException("internalName"); if (serializedData == null) throw new ArgumentNullException("serializedData"); if (torrentData == null) throw new ArgumentNullException("torrentData"); if (PlasmaServerApiVersion > apiVersion) throw new Exception("Obsolete PlasmaServer Client"); if (dependencies == null) dependencies = new List<string>(); var db = new ZkDataContext(); var contentFile = db.ResourceContentFiles.FirstOrDefault(x => x.Md5 == md5); if (contentFile != null) { // content file already stored if (contentFile.Resource.InternalName != internalName) return ReturnValue.Md5AlreadyExistsWithDifferentName; // new spring version we add its hash StoreMetadata(md5, contentFile.Resource, serializedData, torrentData, minimap, metalMap, heightMap); db.SaveChanges(); return ReturnValue.Ok; } var resource = db.Resources.Where(x => x.InternalName == internalName).SingleOrDefault(); if (resource == null) { resource = new Resource { InternalName = internalName, TypeID = resourceType }; db.Resources.Add(resource); StoreMetadata(md5, resource, serializedData, torrentData, minimap, metalMap, heightMap); } if (!resource.ResourceDependencies.Select(x => x.NeedsInternalName).Except(dependencies).Any()) { // new dependencies are superset foreach (var depend in dependencies) { // add missing dependencies var s = depend; if (!resource.ResourceDependencies.Any(x => x.NeedsInternalName == s)) resource.ResourceDependencies.Add(new ResourceDependency { NeedsInternalName = depend }); } } if (resource.ResourceContentFiles.Any(x => x.Length == length && x.Md5 != md5)) { return ReturnValue.Md5AlreadyExistsWithDifferentName; // add proper message - file exists with different md5 and same size - cant register cant detect mirrors } resource.ResourceContentFiles.Add(new ResourceContentFile { FileName = archiveName, Length = length, Md5 = md5 }); File.WriteAllBytes(GetTorrentPath(internalName, md5), torrentData); // add new torrent file db.SaveChanges(); return ReturnValue.Ok; }
public void UpdateMission(ZkDataContext db, Mission mission, Mod modInfo) { var file = mission.Mutator.ToArray(); var tempName = Path.GetTempFileName() + ".zip"; File.WriteAllBytes(tempName, file); using (var zf = new ZipFile(tempName)) { zf.UpdateEntry("modinfo.lua", Encoding.UTF8.GetBytes(GetModInfo(mission.NameWithVersion, mission.Mod, mission.Name, "ZK"))); // FIXME hardcoded crap FixScript(mission, zf, "script.txt"); var script = FixScript(mission, zf, GlobalConst.MissionScriptFileName); modInfo.MissionScript = script; //modInfo.ShortName = mission.Name; modInfo.Name = mission.NameWithVersion; zf.Save(); } mission.Mutator = File.ReadAllBytes(tempName); mission.Script = Regex.Replace(mission.Script, "GameType=([^;]+);", (m) => { return string.Format("GameType={0};", mission.NameWithVersion); }); File.Delete(tempName); var resource = db.Resources.FirstOrDefault(x => x.MissionID == mission.MissionID); if (resource == null) { resource = new Resource() { DownloadCount = 0, TypeID = ZkData.ResourceType.Mod }; db.Resources.Add(resource); } resource.InternalName = mission.NameWithVersion; resource.MissionID = mission.MissionID; resource.ResourceDependencies.Clear(); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Map }); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Mod }); resource.ResourceContentFiles.Clear(); // generate torrent var tempFile = Path.Combine(Path.GetTempPath(), mission.SanitizedFileName); File.WriteAllBytes(tempFile, mission.Mutator.ToArray()); var creator = new TorrentCreator(); creator.Path = tempFile; var torrentStream = new MemoryStream(); creator.Create(torrentStream); try { File.Delete(tempFile); } catch { } var md5 = Hash.HashBytes(mission.Mutator.ToArray()).ToString(); resource.ResourceContentFiles.Add(new ResourceContentFile() { FileName = mission.SanitizedFileName, Length = mission.Mutator.Length, LinkCount = 1, Links = string.Format(MissionFileUrl, mission.MissionID), Md5 = md5 }); var basePath = GlobalConst.SiteDiskPath + @"\resources\"; File.WriteAllBytes(string.Format(@"{2}\{0}_{1}.torrent", resource.InternalName.EscapePath(), md5, basePath), torrentStream.ToArray()); File.WriteAllBytes(string.Format(@"{1}\{0}.metadata.xml.gz", resource.InternalName.EscapePath(), basePath), MetaDataCache.SerializeAndCompressMetaData(modInfo)); File.WriteAllBytes(string.Format(GlobalConst.SiteDiskPath + @"\img\missions\{0}.png", mission.MissionID, basePath), mission.Image.ToArray()); }
MapDetailData GetMapDetailData(Resource res, ZkDataContext db) { var data = new MapDetailData { Resource = res, MyRating = res.MapRatings.SingleOrDefault(x => x.AccountID == Global.AccountID) ?? new MapRating() }; // load map info from disk - or used cached copy if its in memory var cachedEntry = HttpContext.Application["mapinfo_" + res.ResourceID] as Map; if (cachedEntry != null) data.MapInfo = cachedEntry; else { var path = Server.MapPath("~/Resources/") + res.MetadataName; if (System.IO.File.Exists(path)) { try { data.MapInfo = (Map)new XmlSerializer(typeof(Map)).Deserialize(new MemoryStream(System.IO.File.ReadAllBytes(path).Decompress())); HttpContext.Application["mapinfo_" + res.ResourceID] = data.MapInfo; } catch (Exception ex) { Trace.TraceWarning("Failed to get map metedata {0}:{1}", res.MetadataName, ex); data.MapInfo = new Map(); } } } if (res.ForumThread != null) { res.ForumThread.UpdateLastRead(Global.AccountID, false); db.SubmitChanges(); } return data; }
public void UpdateMission(ZkDataContext db, Mission mission, Mod modInfo) { var file = mission.Mutator.ToArray(); var tempName = Path.GetTempFileName() + ".zip"; File.WriteAllBytes(tempName, file); using (var zf = ZipFile.Open(tempName, ZipArchiveMode.Update)) { var modinfoEntry = zf.GetEntry("modinfo.lua"); modinfoEntry.Delete(); modinfoEntry = zf.CreateEntry("modinfo.lua"); WriteZipArchiveEntry(modinfoEntry, GetModInfo(mission.NameWithVersion, mission.ModRapidTag, mission.Name, "ZK")); FixScript(mission, zf, "script.txt"); var script = FixScript(mission, zf, GlobalConst.MissionScriptFileName); modInfo.MissionScript = script; //modInfo.ShortName = mission.Name; modInfo.Name = mission.NameWithVersion; } mission.Mutator = File.ReadAllBytes(tempName); if (string.IsNullOrEmpty(mission.Script)) mission.Script = " "; // tweak for silly update validation mission.Script = Regex.Replace(mission.Script, "GameType=([^;]+);", (m) => $"GameType={mission.NameWithVersion};"); File.Delete(tempName); var resource = db.Resources.FirstOrDefault(x => x.MissionID == mission.MissionID); if (resource == null) { resource = new Resource() { DownloadCount = 0, TypeID = ZkData.ResourceType.Mod }; db.Resources.Add(resource); } resource.InternalName = mission.NameWithVersion; resource.MissionID = mission.MissionID; resource.ResourceDependencies.Clear(); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Map }); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Mod }); resource.ResourceContentFiles.Clear(); // generate torrent var tempFile = Path.Combine(Path.GetTempPath(), mission.SanitizedFileName); File.WriteAllBytes(tempFile, mission.Mutator.ToArray()); var creator = new TorrentCreator(); creator.Path = tempFile; var torrentStream = new MemoryStream(); creator.Create(torrentStream); try { File.Delete(tempFile); } catch { } var md5 = Hash.HashBytes(mission.Mutator.ToArray()).ToString(); resource.ResourceContentFiles.Add(new ResourceContentFile() { FileName = mission.SanitizedFileName, Length = mission.Mutator.Length, LinkCount = 1, Links = string.Format(MissionFileUrl, mission.MissionID), Md5 = md5 }); var basePath = GlobalConst.SiteDiskPath + @"\resources\"; if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath); File.WriteAllBytes(string.Format(@"{2}\{0}_{1}.torrent", resource.InternalName.EscapePath(), md5, basePath), torrentStream.ToArray()); File.WriteAllBytes(string.Format(@"{1}\{0}.metadata.xml.gz", resource.InternalName.EscapePath(), basePath), MetaDataCache.SerializeAndCompressMetaData(modInfo)); var imgPath = GlobalConst.SiteDiskPath + @"\img\missions\"; if (!Directory.Exists(imgPath)) Directory.CreateDirectory(imgPath); File.WriteAllBytes(string.Format(imgPath + "{0}.png", mission.MissionID, basePath), mission.Image.ToArray()); }
partial void DeleteResource(Resource instance);
partial void UpdateResource(Resource instance);
partial void InsertResource(Resource instance);