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\";

            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());
        }
Пример #2
0
        void PerformUnitSyncOperation(WorkItem workItem)
        {
            Trace.TraceInformation("PerformUnitSyncOperation");
            VerifyUnitSync();

            if (unitSync == null)
            {
                Trace.TraceError("Skipping file after unitsync loading errors: {0}", workItem.CacheItem.ShortPath);
                CacheMarkFailedUnitSync(workItem.CacheItem.ShortPath);
                return;
            }

            var info = GetUnitSyncData(workItem.CacheItem.FileName);

            UnInitUnitsync();

            if (info != null)
            {
                workItem.CacheItem.InternalName = info.Name;
                workItem.CacheItem.ResourceType = info is Map ? ResourceType.Map : ResourceType.Mod;

                CacheItemAdd(workItem.CacheItem);

                var args = new CancelEventArgs <IResourceInfo>(info);
                UploadUnitsyncData.Invoke(this, args);
                if (args.Cancel)
                {
                    return;
                }

                var serializedData = MetaDataCache.SerializeAndCompressMetaData(info);

                var    map       = info as Map;
                object userState = null;
                try
                {
                    var creator = new TorrentCreator();
                    creator.Path = GetFullPath(workItem);
                    var ms = new MemoryStream();
                    creator.Create(ms);

                    byte[] minimap   = null;
                    byte[] metalMap  = null;
                    byte[] heightMap = null;
                    if (map != null)
                    {
                        minimap   = map.Minimap.ToBytes(ImageSize);
                        metalMap  = map.Metalmap.ToBytes(ImageSize);
                        heightMap = map.Heightmap.ToBytes(ImageSize);
                        userState = new MapRegisteredEventArgs(info.Name, map, minimap, metalMap, heightMap, serializedData);
                    }
                    var mod = info as Mod;
                    if (mod != null)
                    {
                        userState = new KeyValuePair <Mod, byte[]>(mod, serializedData);
                    }

                    Trace.TraceInformation("uploading {0} to server", info.Name);
                    Task.Factory.StartNew(() => {
                        ReturnValue e;
                        try {
                            e = service.RegisterResource(PlasmaServiceVersion, springPaths.SpringVersion, workItem.CacheItem.Md5.ToString(),
                                                         workItem.CacheItem.Length, info is Map ? ResourceType.Map : ResourceType.Mod, workItem.CacheItem.FileName, info.Name,
                                                         serializedData, mod != null ? mod.Dependencies.ToList() : null, minimap, metalMap, heightMap,
                                                         ms.ToArray());
                        } catch (Exception ex) {
                            Trace.TraceError("Error uploading data to server: {0}", ex);
                            return;
                        } finally {
                            Interlocked.Decrement(ref itemsSending);
                        }

                        if (e != ReturnValue.Ok)
                        {
                            Trace.TraceWarning("Resource registering failed: {0}", e);
                            return;
                        }
                        var mapArgs = userState as MapRegisteredEventArgs;
                        if (mapArgs != null)
                        {
                            var mapName = mapArgs.MapName;
                            MetaData.SaveMinimap(mapName, mapArgs.Minimap);
                            MetaData.SaveMetalmap(mapName, mapArgs.MetalMap);
                            MetaData.SaveHeightmap(mapName, mapArgs.HeightMap);
                            MetaData.SaveMetadata(mapName, mapArgs.SerializedData);
                            MapRegistered(this, mapArgs);
                        }
                        else
                        {
                            var kvp               = (KeyValuePair <Mod, byte[]>)userState;
                            var modInfo           = kvp.Key;
                            var serializedDataRet = kvp.Value;
                            MetaData.SaveMetadata(modInfo.Name, serializedDataRet);
                            ModRegistered(this, new EventArgs <Mod>(mod));
                        }
                    });

                    Interlocked.Increment(ref itemsSending);
                }
                catch (Exception e)
                {
                    Trace.TraceError("Error registering new resource {0}: {1}", workItem.CacheItem.ShortPath, e);
                }
            }
            else
            {
                Trace.TraceError("Could not unitsync file {0}", workItem.CacheItem.ShortPath);
                CacheMarkFailedUnitSync(workItem.CacheItem.ShortPath);
            }
            return;
        }