public static byte[] ToByteArray(this System.IO.Stream strm)
        {
            if(strm is System.IO.MemoryStream)
            {
                return (strm as System.IO.MemoryStream).ToArray();
            }

            long originalPosition = -1;
            if(strm.CanSeek)
            {
                originalPosition = strm.Position;
            }

            try
            {
                using (var ms = new System.IO.MemoryStream())
                {
                    ms.CopyTo(ms);
                    return ms.ToArray();
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (originalPosition >= 0) strm.Position = originalPosition;
            }
        }
Пример #2
0
        public ActionResult Forge(ViewModels.UploadViewModel model)
        {
            Response.TrySkipIisCustomErrors = true;
            if (ModelState.IsValid)
            {
                var currentUser = UserManager.FindById(User.Identity.GetUserId<int>());

                Models.GameMapVariant variant = new Models.GameMapVariant();
                variant.Title = model.Title.Replace("\0", "");
                variant.ShortDescription = model.Description;
                variant.Description = model.Content;
                variant.CreatedOn = DateTime.UtcNow;
                variant.AuthorId = User.Identity.GetUserId<int>();
                variant.File = new Models.File()
                {
                    FileSize = model.File.ContentLength,
                    FileName = Guid.NewGuid().ToString() + ".vrt",
                    UploadedOn = variant.CreatedOn,
                    MD5 = model.File.InputStream.ToMD5()
                };
                // Validate the variant to see if it's not a duplicate.

                var validateMap = GameMapService.ValidateHash(variant.File.MD5);

                if (validateMap != null)
                {
                    Response.StatusCode = 400;
                    return Content(string.Format(
                            "<b>Keep it Clean!</b> The forge variant has already been uploaded: <a target=\"_blank\" href=\"{0}\">{1}</a>.",
                            Url.Action("Details", "Forge", new { slug = validateMap.Slug }),
                            validateMap.Title));
                }

                /* Read the map type from the uploaded file.
                 * This is also a validation message to make sure
                 * that the file uploaded is an actual map.
                 */

                var detectType = VariantDetector.Detect(model.File.InputStream);
                if (detectType == VariantType.Invalid)
                {
                    // The given map doesn't exist.
                    model.File.InputStream.Close();

                    Response.StatusCode = 400;
                    return Content("<b>Keep it Clean!</b> The file uploaded is invalid. Please make sure the map is in the new format.");
                }
                else if (detectType == VariantType.GameVariant)
                {
                    // The given map doesn't exist.
                    model.File.InputStream.Close();

                    Response.StatusCode = 400;
                    return Content("<strong>PARDON OUR DUST!</strong> Can't upload game variant as forge variant.");
                }

                string path = System.IO.Path.Combine(Server.MapPath("~/Content/Files/Forge/"), variant.File.FileName);
                using (var stream = new System.IO.MemoryStream())
                {
                    model.File.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                    model.File.InputStream.CopyTo(stream);

                    ForgeVariant variantItem = new ForgeVariant(stream);

                    var map = GameMapService.GetMapByInternalId(variantItem.MapId);

                    if (map != null)
                    {
                        variant.GameMapId = map.Id;

                        variantItem.VariantName = model.Title;
                        //variantItem.VariantAuthor = currentUser.UploaderName;
                        variantItem.VariantDescription = variant.ShortDescription;
                        variantItem.Save();

                        // Save the file.
                        using (var fileStream = System.IO.File.Create(path))
                        {
                            stream.Seek(0, System.IO.SeekOrigin.Begin);
                            stream.CopyTo(fileStream);
                        }
                    }
                    else
                    {
                        Response.StatusCode = 400;
                        return Content("<strong>PARDON OUR DUST!</strong> We currently do not support the uploaded map.");
                    }
                }

                GameMapService.AddVariant(variant);
                GameMapService.Save();

                return Content(Url.Action("Details", "Forge", new { slug = variant.Slug }));
            }

            Response.StatusCode = 400;
            return View("~/Views/Shared/_ModelState.cshtml");
        }
Пример #3
0
        public static void CreateUpdatePackage(System.Security.Cryptography.RSACryptoServiceProvider key, string inputfolder, string outputfolder, string manifest = null)
        {
            // Read the existing manifest

            UpdateInfo remoteManifest;

            var manifestpath = manifest ?? System.IO.Path.Combine(inputfolder, UPDATE_MANIFEST_FILENAME);

            using(var s = System.IO.File.OpenRead(manifestpath))
            using(var sr = new System.IO.StreamReader(s))
            using(var jr = new Newtonsoft.Json.JsonTextReader(sr))
                remoteManifest = new Newtonsoft.Json.JsonSerializer().Deserialize<UpdateInfo>(jr);

            if (remoteManifest.Files == null)
                remoteManifest.Files = new FileEntry[0];

            if (remoteManifest.ReleaseTime.Ticks == 0)
                remoteManifest.ReleaseTime = DateTime.UtcNow;

            var ignoreFiles = (from n in remoteManifest.Files
                                        where n.Ignore
                                        select n).ToArray();

            var ignoreMap = ignoreFiles.ToDictionary(k => k.Path, k => "", Duplicati.Library.Utility.Utility.ClientFilenameStringComparer);

            remoteManifest.MD5 = null;
            remoteManifest.SHA256 = null;
            remoteManifest.Files = null;
            remoteManifest.UncompressedSize = 0;

            var localManifest = remoteManifest.Clone();
            localManifest.RemoteURLS = null;

            inputfolder = Duplicati.Library.Utility.Utility.AppendDirSeparator(inputfolder);
            var baselen = inputfolder.Length;
            var dirsep = System.IO.Path.DirectorySeparatorChar.ToString();

            ignoreMap.Add(UPDATE_MANIFEST_FILENAME, "");

            var md5 = System.Security.Cryptography.MD5.Create();
            var sha256 = System.Security.Cryptography.SHA256.Create();

            Func<string, string> computeMD5 = (path) =>
            {
                md5.Initialize();
                using(var fs = System.IO.File.OpenRead(path))
                    return Convert.ToBase64String(md5.ComputeHash(fs));
            };

            Func<string, string> computeSHA256 = (path) =>
            {
                sha256.Initialize();
                using(var fs = System.IO.File.OpenRead(path))
                    return Convert.ToBase64String(sha256.ComputeHash(fs));
            };

            // Build a zip
            using (var archive_temp = new Duplicati.Library.Utility.TempFile())
            {
                using (var zipfile = new Duplicati.Library.Compression.FileArchiveZip(archive_temp, new Dictionary<string, string>()))
                {
                    Func<string, string, bool> addToArchive = (path, relpath) =>
                    {
                        if (ignoreMap.ContainsKey(relpath))
                            return false;

                        if (path.EndsWith(dirsep))
                            return true;

                        using (var source = System.IO.File.OpenRead(path))
                        using (var target = zipfile.CreateFile(relpath,
                                           Duplicati.Library.Interface.CompressionHint.Compressible,
                                           System.IO.File.GetLastAccessTimeUtc(path)))
                        {
                            source.CopyTo(target);
                            remoteManifest.UncompressedSize += source.Length;
                        }

                        return true;
                    };

                    // Build the update manifest
                    localManifest.Files =
                (from fse in Duplicati.Library.Utility.Utility.EnumerateFileSystemEntries(inputfolder)
                                let relpath = fse.Substring(baselen)
                                where addToArchive(fse, relpath)
                                select new FileEntry() {
                        Path = relpath,
                        LastWriteTime = System.IO.File.GetLastAccessTimeUtc(fse),
                        MD5 = fse.EndsWith(dirsep) ? null : computeMD5(fse),
                        SHA256 = fse.EndsWith(dirsep) ? null : computeSHA256(fse)
                    })
                .Union(ignoreFiles).ToArray();

                    // Write a signed manifest with the files

                        using (var ms = new System.IO.MemoryStream())
                        using (var sw = new System.IO.StreamWriter(ms))
                        {
                            new Newtonsoft.Json.JsonSerializer().Serialize(sw, localManifest);
                            sw.Flush();

                            using (var ms2 = new System.IO.MemoryStream())
                            {
                                SignatureReadingStream.CreateSignedStream(ms, ms2, key);
                                ms2.Position = 0;
                                using (var sigfile = zipfile.CreateFile(UPDATE_MANIFEST_FILENAME,
                                    Duplicati.Library.Interface.CompressionHint.Compressible,
                                    DateTime.UtcNow))
                                    ms2.CopyTo(sigfile);

                            }
                        }
                }

                remoteManifest.CompressedSize = new System.IO.FileInfo(archive_temp).Length;
                remoteManifest.MD5 = computeMD5(archive_temp);
                remoteManifest.SHA256 = computeSHA256(archive_temp);

                System.IO.File.Move(archive_temp, System.IO.Path.Combine(outputfolder, "package.zip"));

            }

            // Write a signed manifest for upload

            using(var tf = new Duplicati.Library.Utility.TempFile())
            {
                using (var ms = new System.IO.MemoryStream())
                using (var sw = new System.IO.StreamWriter(ms))
                {
                    new Newtonsoft.Json.JsonSerializer().Serialize(sw, remoteManifest);
                    sw.Flush();

                    using (var fs = System.IO.File.Create(tf))
                        SignatureReadingStream.CreateSignedStream(ms, fs, key);
                }

                System.IO.File.Move(tf, System.IO.Path.Combine(outputfolder, UPDATE_MANIFEST_FILENAME));
            }
        }
Пример #4
0
        public HttpResponseMessage DownloadPESportsFiles()
        {
            var takeAtOnce         = 50;
            var processedFileNames = new List <string>();

            byte[]          fileBytes = null;
            ZipArchiveEntry zipItem;

            using (var memoryStream = new System.IO.MemoryStream())
            {
                using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    var feedResponseFull = GeneratePESportsFunding.GenerateFeed(null, null, null, null, null, null, null, null, null, null, null, null, null, null);

                    for (var idx = 0; idx <= (int)Math.Ceiling(feedResponseFull.Length / 10.0); idx++)
                    {
                        var feedResponse = feedResponseFull.Skip(idx * 10).Take(10).ToArray();

                        foreach (var feedEntry in feedResponse)
                        {
                            foreach (var providerFundingId in feedEntry.Content.Funding.ProviderFundings)
                            {
                                var fileName = $"{providerFundingId}.txt";

                                if (processedFileNames.Contains(fileName))
                                {
                                    continue;
                                }

                                var funding    = GeneratePESportsFunding.GenerateProviderFunding(providerFundingId);
                                var fundingStr = JsonConvert.SerializeObject(funding);

                                zipItem = zip.CreateEntry(fileName);
                                processedFileNames.Add(fileName);

                                using (var originalFileMemoryStream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(fundingStr)))
                                {
                                    using (var entryStream = zipItem.Open())
                                    {
                                        originalFileMemoryStream.CopyTo(entryStream);
                                    }
                                }
                            }
                        }

                        zipItem = zip.CreateEntry($"FeedResponse_PESports_{(idx * takeAtOnce) + 1}-{(idx * takeAtOnce) + feedResponse.Length}.txt");
                        var feedResponseStr = JsonConvert.SerializeObject(feedResponse);

                        using (var originalFileMemoryStream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(feedResponseStr)))
                        {
                            using (var entryStream = zipItem.Open())
                            {
                                originalFileMemoryStream.CopyTo(entryStream);
                            }
                        }
                    }
                }

                fileBytes = memoryStream.ToArray();
            }

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(fileBytes)
            };

            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "allPesports.zip"
            };

            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");

            return(result);
        }
Пример #5
0
        internal static byte[] Deflate(byte[] source_byte, System.IO.Compression.CompressionMode type_deflate)
        {
            byte[] dest_byte = null;

            using (System.IO.MemoryStream dest_mem = new System.IO.MemoryStream())
            {
                using (System.IO.MemoryStream source_mem = new System.IO.MemoryStream(source_byte))
                {
                    if (source_mem.CanSeek)
                    {
                        source_mem.Seek(0, System.IO.SeekOrigin.Begin);
                    }

                    if (type_deflate == System.IO.Compression.CompressionMode.Compress)
                    {
                        using (System.IO.Compression.DeflateStream deflate = new System.IO.Compression.DeflateStream(dest_mem, type_deflate))
                        {
                            source_mem.CopyTo(deflate);
                            deflate.Flush();
                        }
                    }
                    else
                    {
                        using (System.IO.Compression.DeflateStream deflate = new System.IO.Compression.DeflateStream(source_mem, type_deflate))
                        {
                            deflate.CopyTo(dest_mem);
                            deflate.Flush();
                        }
                    }

                    source_mem.Flush();
                }
                if (dest_mem.CanSeek)
                {
                    dest_mem.Seek(0, System.IO.SeekOrigin.Begin);
                }
                dest_byte = dest_mem.ToArray();
                dest_mem.Flush();
            }

            return dest_byte;
        }
Пример #6
0
        /// <summary>
        /// Produces an ELF compatible binary output stream with the compiled methods
        /// </summary>
        /// <param name="outstream">The output stream</param>
        /// <param name="assemblyOutput">The assembly text output, can be null</param>
        /// <param name="methods">The compiled methods</param>
        public Dictionary<int, Mono.Cecil.MethodReference> EmitELFStream(System.IO.Stream outstream, System.IO.TextWriter assemblyOutput, IEnumerable<ICompiledMethod> methods)
        {
            Dictionary<int, Mono.Cecil.MethodReference> callpoints;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                uint bootloader_offset;
                callpoints = EmitInstructionStream(ms, assemblyOutput, methods, out bootloader_offset);

                SPEEmulator.ELFReader.EmitELFHeader((uint)ms.Length, bootloader_offset, outstream);

                ms.Position = 0;
                ms.CopyTo(outstream);
            }

            return callpoints;
        }
Пример #7
0
        public static void CreateUpdatePackage(System.Security.Cryptography.RSACryptoServiceProvider key, string inputfolder, string outputfolder, string manifest = null)
        {
            // Read the existing manifest

            UpdateInfo remoteManifest;

            var manifestpath = manifest ?? System.IO.Path.Combine(inputfolder, UPDATE_MANIFEST_FILENAME);

            using (var s = System.IO.File.OpenRead(manifestpath))
                using (var sr = new System.IO.StreamReader(s))
                    using (var jr = new Newtonsoft.Json.JsonTextReader(sr))
                        remoteManifest = new Newtonsoft.Json.JsonSerializer().Deserialize <UpdateInfo>(jr);

            if (remoteManifest.Files == null)
            {
                remoteManifest.Files = new FileEntry[0];
            }

            if (remoteManifest.ReleaseTime.Ticks == 0)
            {
                remoteManifest.ReleaseTime = DateTime.UtcNow;
            }

            var ignoreFiles = (from n in remoteManifest.Files
                               where n.Ignore
                               select n).ToArray();

            var ignoreMap = ignoreFiles.ToDictionary(k => k.Path, k => "", Duplicati.Library.Utility.Utility.ClientFilenameStringComparer);

            remoteManifest.MD5              = null;
            remoteManifest.SHA256           = null;
            remoteManifest.Files            = null;
            remoteManifest.UncompressedSize = 0;

            var localManifest = remoteManifest.Clone();

            localManifest.RemoteURLS = null;

            inputfolder = Duplicati.Library.Utility.Utility.AppendDirSeparator(inputfolder);
            var baselen = inputfolder.Length;
            var dirsep  = System.IO.Path.DirectorySeparatorChar.ToString();

            ignoreMap.Add(UPDATE_MANIFEST_FILENAME, "");

            var md5    = System.Security.Cryptography.MD5.Create();
            var sha256 = System.Security.Cryptography.SHA256.Create();

            Func <string, string> computeMD5 = (path) =>
            {
                md5.Initialize();
                using (var fs = System.IO.File.OpenRead(path))
                    return(Convert.ToBase64String(md5.ComputeHash(fs)));
            };

            Func <string, string> computeSHA256 = (path) =>
            {
                sha256.Initialize();
                using (var fs = System.IO.File.OpenRead(path))
                    return(Convert.ToBase64String(sha256.ComputeHash(fs)));
            };

            // Build a zip
            using (var archive_temp = new Duplicati.Library.Utility.TempFile())
            {
                using (var zipfile = new Duplicati.Library.Compression.FileArchiveZip(archive_temp, new Dictionary <string, string>()))
                {
                    Func <string, string, bool> addToArchive = (path, relpath) =>
                    {
                        if (ignoreMap.ContainsKey(relpath))
                        {
                            return(false);
                        }

                        if (path.EndsWith(dirsep))
                        {
                            return(true);
                        }

                        using (var source = System.IO.File.OpenRead(path))
                            using (var target = zipfile.CreateFile(relpath,
                                                                   Duplicati.Library.Interface.CompressionHint.Compressible,
                                                                   System.IO.File.GetLastAccessTimeUtc(path)))
                            {
                                source.CopyTo(target);
                                remoteManifest.UncompressedSize += source.Length;
                            }

                        return(true);
                    };

                    // Build the update manifest
                    localManifest.Files =
                        (from fse in Duplicati.Library.Utility.Utility.EnumerateFileSystemEntries(inputfolder)
                         let relpath = fse.Substring(baselen)
                                       where addToArchive(fse, relpath)
                                       select new FileEntry()
                    {
                        Path = relpath,
                        LastWriteTime = System.IO.File.GetLastAccessTimeUtc(fse),
                        MD5 = fse.EndsWith(dirsep) ? null : computeMD5(fse),
                        SHA256 = fse.EndsWith(dirsep) ? null : computeSHA256(fse)
                    })
                        .Union(ignoreFiles).ToArray();

                    // Write a signed manifest with the files

                    using (var ms = new System.IO.MemoryStream())
                        using (var sw = new System.IO.StreamWriter(ms))
                        {
                            new Newtonsoft.Json.JsonSerializer().Serialize(sw, localManifest);
                            sw.Flush();

                            using (var ms2 = new System.IO.MemoryStream())
                            {
                                SignatureReadingStream.CreateSignedStream(ms, ms2, key);
                                ms2.Position = 0;
                                using (var sigfile = zipfile.CreateFile(UPDATE_MANIFEST_FILENAME,
                                                                        Duplicati.Library.Interface.CompressionHint.Compressible,
                                                                        DateTime.UtcNow))
                                    ms2.CopyTo(sigfile);
                            }
                        }
                }

                remoteManifest.CompressedSize = new System.IO.FileInfo(archive_temp).Length;
                remoteManifest.MD5            = computeMD5(archive_temp);
                remoteManifest.SHA256         = computeSHA256(archive_temp);

                System.IO.File.Move(archive_temp, System.IO.Path.Combine(outputfolder, "package.zip"));
            }

            // Write a signed manifest for upload

            using (var tf = new Duplicati.Library.Utility.TempFile())
            {
                using (var ms = new System.IO.MemoryStream())
                    using (var sw = new System.IO.StreamWriter(ms))
                    {
                        new Newtonsoft.Json.JsonSerializer().Serialize(sw, remoteManifest);
                        sw.Flush();

                        using (var fs = System.IO.File.Create(tf))
                            SignatureReadingStream.CreateSignedStream(ms, fs, key);
                    }

                System.IO.File.Move(tf, System.IO.Path.Combine(outputfolder, UPDATE_MANIFEST_FILENAME));
            }
        }
Пример #8
0
        public AdminModule() : base("/admin")
        {
            _tinyfxPageRender = new Cores.TinyfxPageRender(TinyfxCore.Configuration);

            this.RequiresAuthentication();

            // 全局文本替换
            Get("/global-replace", _ => {
                bool enable = false;

                if (enable)
                {
                    // 原始
                    string srcText = "/images/";
                    // 替换为
                    string dstTest = "/files/";

                    int bb    = 0;
                    var ps    = new PressService();
                    var data  = ps.AllPosts;
                    var newpp = new List <Models.Post>();
                    foreach (var item in data)
                    {
                        var pc     = item;
                        string ori = new Faes().Decrypt(item.Content);
                        int poc    = ori.IndexOf(srcText);
                        if (poc >= 0)
                        {
                            string mr  = ori.Replace(srcText, dstTest);
                            pc.Content = new Faes().Encrypt(mr);
                            bb++;
                        }

                        newpp.Add(pc);
                    }
                    string xml = new XmlSerializor().SerializorToString(newpp);
                    return(xml);
                }
                else
                {
                    return(new NotFoundResponse());
                }
            });


            Get("/", _ =>
            {
                return(Response.AsText(_tinyfxPageRender.RenderAdminDashboard(), "text/html"));
            });

            Get("/dashboard", _ =>
            {
                return(Response.AsText(_tinyfxPageRender.RenderAdminDashboard(), "text/html"));
            });

            Get("/edit-post", _ =>
            {
                long pid      = 0;
                string pidstr = Request.Query.Pid;
                pid           = pidstr.AsLong();
                return(Response.AsText(_tinyfxPageRender.RenderCreatePost("GET", pid, null, null, false), "text/html"));
            });

            Post("/edit-post", _ =>
            {
                long pid      = 0;
                string pidstr = Request.Query.Pid;
                pid           = pidstr.AsLong();

                string title   = Request.Form.title;
                string content = Request.Form.content;
                bool isPublic  = false;
                if (Request.Form.isPublic != null && Request.Form.isPublic == "on")
                {
                    isPublic = true;
                }

                string html = _tinyfxPageRender.RenderCreatePost("POST", pid, title, content, isPublic);

                if (html != null)
                {
                    return(Response.AsText(html, "text/html"));
                }
                else
                {
                    return(Response.AsRedirect(this.ModulePath + "/post-list"));
                }
            });

            Get("/post-list", _ =>
            {
                string pageStr = Request.Query.page;
                string pidStr  = Request.Query.pid;
                string action  = Request.Query.action + "";

                int page = pageStr.AsInt();
                long pid = pidStr.AsLong();

                return(Response.AsText(_tinyfxPageRender.RenderPostList(page, action, pid), "text/html"));
            });

            Post("/upload", _ =>
            {
                var faes   = new Faes();
                var config = TinyfxCore.Configuration;
                var file   = this.Request.Files.FirstOrDefault();
                if (file != null)
                {
                    try
                    {
                        DateTime now = DateTime.Now;

                        string ext = System.IO.Path.GetExtension(file.Name).ToLower();
                        if (!TinyfxCore.Mime.ContainsKey(ext))
                        {
                            return(Response.AsJson(new { error = 3, url = "" }));
                        }
                        string filename = now.Ticks.ToString() + ext;
                        string year     = now.Year.ToString();
                        string month    = now.Month.ToString();
                        string dir      = System.IO.Path.Combine(config.DataDirectory, TinyfxCore.IMAGE_UPLOAD_DIR, year, month);
                        if (!string.IsNullOrEmpty(TinyfxCore.Configuration.DataDirectory))
                        {
                            dir = System.IO.Path.Combine(TinyfxCore.Configuration.DataDirectory, TinyfxCore.IMAGE_UPLOAD_DIR, year, month);
                        }
                        string fullname = System.IO.Path.Combine(dir, filename);
                        if (!System.IO.Directory.Exists(dir))
                        {
                            System.IO.Directory.CreateDirectory(dir);
                        }

                        if (TinyfxCore.Configuration.Encryption)
                        {
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            faes.Encrypt(file.Value, ms);
                            ms.Seek(0, System.IO.SeekOrigin.Begin);
                            using (var fs = System.IO.File.Open(fullname, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                            {
                                ms.CopyTo(fs);
                            }
                        }
                        else
                        {
                            using (var fs = System.IO.File.Open(fullname, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
                            {
                                file.Value.CopyTo(fs);
                            }
                        }

                        string url = "/files/" + year + "_" + month + "_" + filename;
                        return(Response.AsJson(new { error = 0, url = url }));
                    }
                    catch (Exception)
                    {
                        return(Response.AsJson(new { error = 1, url = "" }));
                    }
                }
                else
                {
                    return(Response.AsJson(new { error = 2, url = "" }));
                }
            });

            Get("/change-password", _ =>
            {
                LogHelper.WriteLog(LogHelper.LogType.INFO, "HTTP GET /change-password", null);
                return(Response.AsText(_tinyfxPageRender.RenderChangePassword(Request.Method, null, null, null), "text/html"));
            });

            Post("/change-password", _ =>
            {
                LogHelper.WriteLog(LogHelper.LogType.INFO, "HTTP POST /change-password", null);

                string username   = Request.Form.username + "";
                string password   = Request.Form.password + "";
                string repassword = Request.Form.repassword + "";

                return(Response.AsText(_tinyfxPageRender.RenderChangePassword(Request.Method, username, password, repassword), "text/html"));
            });
        }
Пример #9
0
        public ActionResult GameType(ViewModels.UploadViewModel model)
        {
            Response.TrySkipIisCustomErrors = true;
            if (ModelState.IsValid)
            {
                var currentUser = UserManager.FindById(User.Identity.GetUserId <int>());

                Models.GameTypeVariant variant = new Models.GameTypeVariant();
                variant.Title            = model.Title.Replace("\0", "");
                variant.ShortDescription = model.Description;
                variant.Description      = model.Content;
                variant.CreatedOn        = DateTime.UtcNow;
                variant.AuthorId         = User.Identity.GetUserId <int>();
                variant.File             = new Models.File()
                {
                    FileSize   = model.File.ContentLength,
                    FileName   = Guid.NewGuid().ToString() + ".gtv",
                    UploadedOn = variant.CreatedOn,
                    MD5        = model.File.InputStream.ToMD5()
                };

                var validateGame = GameTypeService.ValidateHash(variant.File.MD5);

                if (validateGame != null)
                {
                    Response.StatusCode = 400;
                    return(Content(string.Format(
                                       "<b>Keep it Clean!</b> The game variant has already been uploaded: <a target=\"_blank\" href=\"{0}\">{1}</a>.",
                                       Url.Action("Details", "GameType", new { slug = validateGame.Slug }),
                                       validateGame.Title)));
                }

                /* Read the map type from the uploaded file.
                 * This is also a validation message to make sure
                 * that the file uploaded is an actual map.
                 */

                var detectType = VariantDetector.Detect(model.File.InputStream);
                if (detectType == VariantType.Invalid)
                {
                    // The given map doesn't exist.
                    model.File.InputStream.Close();

                    Response.StatusCode = 400;
                    return(Content("<b>Keep it Clean!</b> The file uploaded is invalid. Please make sure it's a valid game variant."));
                }
                else if (detectType == VariantType.ForgeVariant)
                {
                    // The given map doesn't exist.
                    model.File.InputStream.Close();

                    Response.StatusCode = 400;
                    return(Content("<strong>PARDON OUR DUST!</strong> Can't upload forge variant as game variant."));
                }

                string path = System.IO.Path.Combine(Server.MapPath("~/Content/Files/GameType/"), variant.File.FileName);
                using (var stream = new System.IO.MemoryStream())
                {
                    model.File.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                    model.File.InputStream.CopyTo(stream);

                    GameVariant variantItem = new GameVariant(stream);

                    var type = GameTypeService.GetByInternalId(variantItem.TypeId);

                    if (type != null)
                    {
                        variant.GameTypeId = type.Id;

                        variantItem.VariantName = model.Title;
                        //variantItem.VariantAuthor = currentUser.UploaderName;
                        variantItem.VariantDescription = variant.ShortDescription;
                        variantItem.Save();


                        // Save the file.
                        using (var fileStream = System.IO.File.Create(path))
                        {
                            stream.Seek(0, System.IO.SeekOrigin.Begin);
                            stream.CopyTo(fileStream);
                        }
                    }
                    else
                    {
                        Response.StatusCode = 400;
                        return(Content("<strong>PARDON OUR DUST!</strong> We currently do not support the uploaded gametype."));
                    }
                }

                GameTypeService.AddVariant(variant);
                GameTypeService.Save();

                return(Content(Url.Action("Details", "GameType", new { slug = variant.Slug })));
            }

            Response.StatusCode = 400;
            return(View("~/Views/Shared/_ModelState.cshtml"));
        }
Пример #10
0
        public static void SaveData()
        {
            if (!Manager.isReady || Manager.Data == null)
            {
                return;
            }

            var text = "";

            try
            {
                text = FileFormat.XML.Utils.ClassToXML <Data.Data>(Manager.Data, false);
#if UNITY_EDITOR
                System.IO.File.WriteAllText(dataFile.FullName, text);
#else
                using (var msi = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(text)))
                    using (var mso = new System.IO.MemoryStream())
                    {
                        using (var gs = new GZipStream(mso, CompressionMode.Compress)) msi.CopyTo(gs);
                        System.IO.File.WriteAllBytes(dataFile.FullName, mso.ToArray());
                    }
#endif

                Logging.Log("Data saved");
            }
            catch (System.Exception e) { Debug.LogError($"Error while saving: {e.Message}\n{e.StackTrace}"); }
        }