Esempio n. 1
0
        public Stream Get(Resize request)
        {
            var imageFile = VirtualFiles.GetFile(UploadsDir.CombineWith(request.Id + ".png"));

            if (request.Id == null || imageFile == null)
            {
                throw HttpError.NotFound(request.Id + " was not found");
            }

            using (var stream = imageFile.OpenRead())
                using (var img = Image.FromStream(stream))
                {
                    var parts  = request.Size?.Split('x');
                    int width  = img.Width;
                    int height = img.Height;

                    if (parts != null && parts.Length > 0)
                    {
                        int.TryParse(parts[0], out width);
                    }

                    if (parts != null && parts.Length > 1)
                    {
                        int.TryParse(parts[1], out height);
                    }

                    return(Resize(img, width, height));
                }
        }
Esempio n. 2
0
        private void WriteImage(Stream ms)
        {
            ms.Position = 0;
            var hash = ms.ToMd5Hash();

            ms.Position = 0;
            var fileName = hash + ".png";

            using (var img = Image.FromStream(ms))
            {
                using (var msPng = MemoryStreamFactory.GetStream())
                {
                    img.Save(msPng, ImageFormat.Png);
                    msPng.Position = 0;
                    VirtualFiles.WriteFile(UploadsDir.CombineWith(fileName), msPng);
                }

                var stream = Resize(img, ThumbnailSize, ThumbnailSize);
                VirtualFiles.WriteFile(ThumbnailsDir.CombineWith(fileName), stream);

                ImageSizes.ForEach(x => VirtualFiles.WriteFile(
                                       UploadsDir.CombineWith(x).CombineWith(hash + ".png"),
                                       Get(new Resize {
                    Id = hash, Size = x
                }).ReadFully()));
            }
        }
Esempio n. 3
0
        private FolderResult GetFolderResult(string targetPath)
        {
            var result = new FolderResult();

            var dir = VirtualFiles.GetDirectory(targetPath);

            foreach (var subDir in dir.Directories)
            {
                if (Config.ExcludeDirectories.Contains(subDir.Name))
                {
                    continue;
                }

                result.Folders.Add(new Folder
                {
                    Name         = subDir.Name,
                    ModifiedDate = subDir.LastModified,
                    FileCount    = subDir.GetFiles().Count(),
                });
            }

            foreach (var fileInfo in dir.GetFiles())
            {
                result.Files.Add(new ServiceModel.Types.File
                {
                    Name          = fileInfo.Name,
                    Extension     = fileInfo.Extension,
                    FileSizeBytes = fileInfo.Length,
                    ModifiedDate  = fileInfo.LastModified,
                    IsTextFile    = Config.TextFileExtensions.Contains(fileInfo.Extension),
                });
            }

            return(result);
        }
Esempio n. 4
0
        public object Any(Reset request)
        {
            VirtualFiles.DeleteFiles(VirtualFiles.GetDirectory(UploadsDir).GetAllMatchingFiles("*.png"));
            VirtualFileSources.GetFile("preset-urls.txt").ReadAllText().ReadLines().ToList()
            .ForEach(url => WriteImage(new MemoryStream(url.Trim().GetBytesFromUrl())));

            return(HttpResult.Redirect("/"));
        }
Esempio n. 5
0
        public object Any(Reset request)
        {
            VirtualFiles.DeleteFiles(VirtualFiles.GetDirectory(UploadsDir).GetAllMatchingFiles("*.png"));
            File.ReadAllLines("~/imgur/preset-urls.txt".MapHostAbsolutePath()).ToList()
            .ForEach(url => WriteImage(new MemoryStream(url.Trim().GetBytesFromUrl())));

            return(HttpResult.Redirect("/imgur/"));
        }
Esempio n. 6
0
        public object Any(DeleteUpload request)
        {
            var file = request.Id + ".png";
            var filesToDelete = new[] { UploadsDir.CombineWith(file), ThumbnailsDir.CombineWith(file) }.ToList();

            ImageSizes.Each(x => filesToDelete.Add(UploadsDir.CombineWith(x, file)));
            VirtualFiles.DeleteFiles(filesToDelete);

            return(HttpResult.Redirect("/"));
        }
Esempio n. 7
0
    public override StaticContent?Get(string path)
    {
        var file = VirtualFiles.GetFile(DirPath.CombineWith(path));

        if (file == null)
        {
            return(null);
        }

        return(new StaticContent(file.GetBytesContentsAsMemory(), MimeTypes.GetExtension(file.Extension)));
    }
Esempio n. 8
0
        public object Post(RevertFiles request)
        {
            VirtualFiles.DeleteFolder(Config.RootDirectory);

            foreach (var file in VirtualFiles.GetDirectory("src").GetAllMatchingFiles("*.*"))
            {
                VirtualFiles.WriteFile(file, file.VirtualPath.Replace("src/", Config.RootDirectory));
            }

            return(new RevertFilesResponse());
        }
Esempio n. 9
0
        private string GetAndValidateExistingPath(Files request)
        {
            var targetPath = GetPath(request);

            if (!VirtualFiles.IsFile(targetPath) && !VirtualFiles.IsDirectory(targetPath))
            {
                throw new HttpError(HttpStatusCode.NotFound, new FileNotFoundException("Could not find: " + request.Path));
            }

            return(targetPath);
        }
Esempio n. 10
0
        public async Task <object> PostAsync(FileUpload request)
        {
            var feature = HostContext.GetPlugin <FileFeature>();

            List <ServiceModel.Types.File> newFiles = new List <ServiceModel.Types.File>();

            using (var trans = Db.OpenTransaction())
            {
                try
                {
                    foreach (IHttpFile requestFile in Request.Files)
                    {
                        var fileNameFromReq = requestFile.FileName;
                        var fileFullPath    =
                            feature.UploadedFileFullPathBuilder?.Invoke(request) ?? ServiceConfig.Instance.GetDefaultUploadFullFilePath(fileNameFromReq, request.Folder);

                        VirtualFiles.WriteFile(fileFullPath, requestFile.InputStream);

                        var fileRecord = new ServiceModel.Types.File()
                        {
                            ApplicationId   = request.ApplicationId,
                            ContentType     = requestFile.ContentType,
                            ExtraAttribute1 = request.ExtraAttribute1,
                            ExtraAttribute2 = request.ExtraAttribute2,
                            ExtraAttribute3 = request.ExtraAttribute3,
                            ExtraAttribute4 = request.ExtraAttribute4,
                            FileName        = requestFile.FileName,
                            ReferencedBy    = request.ReferencedBy,
                            FileHash        = requestFile.InputStream.ComputeFileMd5(),
                            CreatedBy       = GetSession().GetUserAuthName(),
                            CreatedDate     = DateTime.UtcNow,
                            ModifiedBy      = GetSession().GetUserAuthName(),
                            ModifiedDate    = DateTime.UtcNow
                        };
                        await Db.InsertAsync(fileRecord);

                        newFiles.Add(fileRecord);
                    }

                    trans.Commit();
                }
                catch (Exception e)
                {
                    trans.Rollback();
                    throw new HttpError(HttpStatusCode.InternalServerError, e);
                }
            }

            return(new FileUploadResponse()
            {
                Ids = newFiles.Select(f => f.Id).ToList(), Results = newFiles
            });
        }
            public object Any(MockUploadFile request)
            {
                for (int i = 0; i < Request.Files.Length; i++)
                {
                    var file = Request.Files[i];

                    string fileId   = Guid.NewGuid().ToString();
                    var    session  = this.GetSession();
                    var    fileName = session.Id.CombineWith(fileId);
                    VirtualFiles.WriteFile(fileName, file.InputStream);
                }

                return(request);
            }
Esempio n. 12
0
        private void Notification_ClipboardUpdate(object sender, EventArgs e)
        {
            labelResult.Text = "";

            Log("New content in clipboard!");

            if (!VirtualFiles.ContainsVirtualFiles)
            {
                Log("Clipboard does not contain virtual files. Please handle this data with common Clipboard.GetXXXX methods.");
                return;
            }

            try
            {
                //some test properties
                var containsEmClientEmail = VirtualFiles.ContainsEmclientEmail;
                var containsOutlookEmail  = VirtualFiles.ContainsOutlookEmail;

                if (!checkBoxOutlook.Checked) //Default way
                {
                    Log("Option 1: Get file streams");
                    var streams = VirtualFiles.GetVirtualFilesAsStreams();

                    Log("Option 2: Get files saved to disk");
                    var files = VirtualFiles.GetVirtualFilesAsFiles();

                    foreach (var file in files)
                    {
                        Log("Saved file " + file.FullName);
                    }
                }
                else //Outlook special handling
                {
                    Log("Option 1: Get file streams");
                    var streams = VirtualFiles.GetOutlookVirtualFilesAsStreams();

                    Log("Option 2: Get files saved to disk");
                    var files = VirtualFiles.GetOutlookVirtualFilesAsFiles();

                    foreach (var file in files)
                    {
                        Log("Saved Outlook msg file " + file.FullName);
                    }
                }
            }
            catch (Exception ex)
            {
                Log("Got exception: " + ex.Message + Environment.NewLine + "Stacktrace: " + ex.StackTrace);
            }
        }
Esempio n. 13
0
        public async Task <object> Get(GetFileContent request)
        {
            ServiceModel.Types.File fileDb = await GetFileByIdOrThrowAsync(request.Id);

            var root     = ServiceConfig.Instance.DefaultUploadsPath.Replace("~", "").MapServerPath();
            var filePath = $"{root}/{fileDb.FileName}";
            var file     = VirtualFiles.GetFile(filePath);
            var content  = file.ReadAllBytes();

            return(new GetFileContentResponse()
            {
                Content = content,
                ContentType = fileDb.ContentType
            });
        }
Esempio n. 14
0
        private FileResult GetFileResult(string filePath)
        {
            var file       = VirtualFiles.GetFile(filePath);
            var isTextFile = Config.TextFileExtensions.Contains(file.Extension);

            return(new FileResult
            {
                Name = file.Name,
                Extension = file.Extension,
                FileSizeBytes = file.Length,
                IsTextFile = isTextFile,
                Contents = isTextFile ? VirtualFiles.GetFile(file.VirtualPath).ReadAllText() : null,
                ModifiedDate = file.LastModified,
            });
        }
Esempio n. 15
0
        public object Any(UpdateS3 request)
        {
            if (request.Razor)
            {
                var kurtRazor = VirtualFiles.GetFile("stars/dead/cobain/default.cshtml");
                VirtualFiles.WriteFile(kurtRazor.VirtualPath, UpdateContent("UPDATED RAZOR", kurtRazor.ReadAllText(), request.Clear));
                HostContext.GetPlugin <RazorFormat>().RefreshPage(kurtRazor.VirtualPath);
            }

            var kurtMarkdown = VirtualFiles.GetFile("stars/dead/cobain/Content.md");

            VirtualFiles.WriteFile(kurtMarkdown.VirtualPath, UpdateContent("UPDATED MARKDOWN", kurtMarkdown.ReadAllText(), request.Clear));
            HostContext.GetPlugin <MarkdownFormat>().RefreshPage(kurtMarkdown.VirtualPath);

            return(HttpResult.Redirect("/stars/dead/cobain/"));
        }
Esempio n. 16
0
        public void Put(Files request)
        {
            var targetFile = VirtualFiles.GetFile(GetAndValidateExistingPath(request));

            if (!Config.TextFileExtensions.Contains(targetFile.Extension))
            {
                throw new NotSupportedException("PUT Can only update text files, not: " + targetFile.Extension);
            }

            if (request.TextContents == null)
            {
                throw new ArgumentNullException("TextContents");
            }

            VirtualFiles.WriteFile(targetFile.VirtualPath, request.TextContents);
        }
Esempio n. 17
0
 internal PlasticFileSystem(
     WorkspaceContent content,
     string cachePath,
     PlasticAPI plasticApi,
     FileHandles handles,
     WorkspaceLocalFiles tempStorage,
     VirtualFiles virtualFiles)
 {
     mWorkspaceContent      = content;
     mChangesTreeOperations = new ChangesTreeOperations(content);
     mLocalFilesPath        = cachePath;
     mFileCache             = new FileCache(mLocalFilesPath);
     mPlasticApi            = plasticApi;
     mHandles      = handles;
     mLocalFiles   = tempStorage;
     mVirtualFiles = virtualFiles;
 }
Esempio n. 18
0
        public object Post(Files request)
        {
            var targetDir = GetPath(request);

            if (VirtualFiles.IsFile(targetDir))
            {
                throw new NotSupportedException(
                          "POST only supports uploading new files. Use PUT to replace contents of an existing file");
            }

            foreach (var uploadedFile in base.Request.Files)
            {
                var newFilePath = targetDir.CombineWith(uploadedFile.FileName);
                VirtualFiles.WriteFile(newFilePath, uploadedFile.InputStream);
            }

            return(new FilesResponse());
        }
Esempio n. 19
0
        public object Any(GetNZB request)
        {
            var nzb = Db.Single <NZB>(q => q.Guid == request.Id);

            using (var db = ConnectionFactory.OpenDbConnection())
            {
                db.Insert <Download>(new Download()
                {
                    NZBId     = nzb.Id,
                    IPAddress = Request.Headers["X-Forwarded-For"],
                });
            }

            var nzbpath = String.Format("nzb/{0}/{1}/{2}/{3}/",
                                        request.Id[0],
                                        request.Id[1],
                                        request.Id[2],
                                        request.Id[3]);
            var filename = String.Format("{0}.nzb.gz", request.Id);
            var path     = _settings.Get <string>("FSPath");

            Stream stream = null;

            if (!Directory.Exists(path + nzbpath) || !File.Exists(path + filename))
            {
                var file = VirtualFiles.GetFile(nzbpath + filename);
                Directory.CreateDirectory(path + nzbpath);
                File.WriteAllBytes(path + nzbpath + filename, file.ReadAllBytes());
            }
            stream = File.OpenRead(path + nzbpath + filename);

            Response.AddHeader("Content-Disposition", "attachment; filename=" + nzb.Name + ".nzb");
            MemoryStream output = new MemoryStream();

            using (Stream originalFileStream = stream)
            {
                using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                {
                    decompressionStream.CopyTo(output);
                }
            }

            return(new HttpResult(output, "application/x-nzb"));
        }
Esempio n. 20
0
        static int Delete(
            Node root,
            string path,
            VirtualFiles virtualFiles,
            ChangesTreeOperations changesTreeOperations)
        {
            Node parent = WalkTree.Find(root, Path.GetDirectoryName(path));

            if (parent == null)
            {
                return(-DokanNet.ERROR_PATH_NOT_FOUND);
            }

            Node node = WalkTree.GetChildByName(parent.GetChildren(), Path.GetFileName(path));

            if (node == null)
            {
                return(-DokanNet.ERROR_FILE_NOT_FOUND);
            }

            IVirtualFile virtualFile = virtualFiles.Get(node.GetNodeId());

            if (virtualFile != null)
            {
                mLog.ErrorFormat("We don't allow deleting virtual files. [{0}]",
                                 node.GetName());

                return(-DokanNet.ERROR_ACCESS_DENIED);
            }

            if (node.IsControlled())
            {
                changesTreeOperations.Delete(CmPath.FromWindows(path));
            }

            if (parent.DeleteChild(node))
            {
                return(0);
            }

            return(-DokanNet.ERROR_FILE_NOT_FOUND);
        }
Esempio n. 21
0
        public object Get(Files request)
        {
            var targetPath = GetAndValidateExistingPath(request);

            var isDirectory = VirtualFiles.IsDirectory(targetPath);

            if (!isDirectory && request.ForDownload)
            {
                return(new HttpResult(VirtualFiles.GetFile(targetPath), asAttachment: true));
            }

            var response = isDirectory
                ? new FilesResponse {
                Directory = GetFolderResult(targetPath)
            }
                : new FilesResponse {
                File = GetFileResult(targetPath)
            };

            return(response);
        }
Esempio n. 22
0
    // Configure your AppHost with the necessary configuration and dependencies your App needs
    public override void Configure(Container container)
    {
        // JsConfig.Init(new ServiceStack.Text.Config {
        //     IncludeNullValues = true,
        //     TextCase = TextCase.PascalCase
        // });
        SetConfig(new HostConfig
        {
            //DebugMode = false,
            DebugMode       = true,
            AdminAuthSecret = "secret",
        });

        var memFs = GetVirtualFileSource <MemoryVirtualFiles>();
        var files = VirtualFiles.GetDirectory("custom").GetAllFiles();

        files.Each(file => memFs.WriteFile($"locode/{file.Name}", file));
        GlobalRequestFilters.Add((req, res, dto) => {
            files.Each(file => memFs.WriteFile($"locode/{file.Name}", file));
        });

        ConfigurePlugin <UiFeature>(feature => {
            Console.WriteLine(@"ConfigurePlugin<UiFeature>...");
            feature.HtmlModules.Add(new("/modules/forms", "/forms"));

            feature.Module.Configure((appHost, module) =>
            {
                module.VirtualFiles = appHost.VirtualFiles;
                module.DirPath      = module.DirPath.Replace("/modules", "");
            });
            feature.Handlers.Cast <SharedFolder>().Each(x =>
                                                        x.SharedDir = x.SharedDir.Replace("/modules", ""));
        });

        // Not needed in `dotnet watch` and in /wwwroot/modules/ui which can use _framework/aspnetcore-browser-refresh.js"
        Plugins.AddIfDebug(new HotReloadFeature
        {
            VirtualFiles   = VirtualFiles,
            DefaultPattern = "*.html;*.js;*.css"
        });
        //Plugins.Add(new PostmanFeature());

        var uploadVfs  = new FileSystemVirtualFiles(TalentBlazorWwwRootDir);
        var appDataVfs = new FileSystemVirtualFiles(TalentBlazorAppDataDir);

        Plugins.Add(new FilesUploadFeature(
                        new UploadLocation("profiles", uploadVfs, allowExtensions: FileExt.WebImages,
                                           resolvePath: ctx => $"/profiles/{ctx.FileName}"),

                        new UploadLocation("game_items", appDataVfs, allowExtensions: FileExt.WebImages),

                        new UploadLocation("files", GetVirtualFileSource <FileSystemVirtualFiles>(),
                                           resolvePath: ctx => $"/files/{ctx.FileName}"),

                        new UploadLocation("users", uploadVfs, allowExtensions: FileExt.WebImages,
                                           resolvePath: ctx => $"/profiles/users/{ctx.UserAuthId}.{ctx.FileExtension}"),

                        new UploadLocation("applications", appDataVfs, maxFileCount: 3, maxFileBytes: 10_000_000,
                                           resolvePath: ctx => ctx.GetLocationPath((ctx.Dto is CreateJobApplication create
                    ? $"job/{create.JobId}"
                    : $"app/{ctx.Dto.GetId()}") + $"/{ctx.DateSegment}/{ctx.FileName}"),
                                           readAccessRole: RoleNames.AllowAnon, writeAccessRole: RoleNames.AllowAnon)
                        ));

        Metadata.ForceInclude = new() {
            typeof(GetAccessToken)
        };
        Plugins.Add(new ServiceStack.Api.OpenApi.OpenApiFeature());
    }
Esempio n. 23
0
        public object Post(ImportNZB nzb)
        {
            if (nzb.Key != _settings.GetString("ApiKey"))
            {
                throw new HttpError(401, "Unauthorized");
            }

            if (Db.Exists <NZB>(new { ReleaseId = nzb.ReleaseId }))
            {
                throw new HttpError(500, "NZB already imported");
            }

            if (Request.Files.Length == 0 && !String.IsNullOrEmpty(nzb.Data))
            {
                throw new HttpError(500, "No file present");
            }

            if (Request.Files.Length == 0 && !String.IsNullOrEmpty(nzb.Data))
            {
                byte[] data = Convert.FromBase64String(nzb.Data);

                using (var stream = new MemoryStream(data))
                {
                    var file = String.Format("nzb/{0}/{1}/{2}/{3}/{4}.nzb.gz",
                                             nzb.Guid[0],
                                             nzb.Guid[1],
                                             nzb.Guid[2],
                                             nzb.Guid[3],
                                             nzb.Guid);

                    VirtualFiles.WriteFile(file, stream);
                }
            }

            Title title;

            var catCount = Db.Single <Count>(q => q.CategoryId == nzb.CategoryId);

            bool titleExists =
                (nzb.TVEpisodeId != 0 && Db.Exists <Title>(q => q.TVEpisodeId == nzb.TVEpisodeId)) ||
                (nzb.ImdbId != 0 && Db.Exists <Title>(q => q.ImdbId == nzb.ImdbId));

            using (var db = ConnectionFactory.OpenDbConnection()) {
                if (nzb.TVEpisodeId != 0 && !titleExists)
                {
                    db.Save <Title>(new Title()
                    {
                        TVEpisodeId = nzb.TVEpisodeId,
                        VideoId     = nzb.VideoId,
                        Name        = nzb.Name1 + " " + nzb.Name2,
                        Name1       = nzb.Name1,
                        Name2       = nzb.Name2,
                    });
                }
                else if (nzb.ImdbId != 0 && !titleExists)
                {
                    db.Save <Title>(new Title()
                    {
                        ImdbId = nzb.ImdbId,
                        Name   = nzb.Name1,
                        Name1  = nzb.Name1,
                    });
                }

                if (nzb.ImdbId != 0)
                {
                    title = db.Single <Title>(q => q.ImdbId == nzb.ImdbId);
                }
                else
                {
                    title = db.Single <Title>(q => q.TVEpisodeId == nzb.TVEpisodeId);
                }

                bool saveVideo   = nzb.Video != null && !db.Exists <Video>(q => q.Id == nzb.VideoId);
                bool saveEpisode = nzb.TVEpisode != null && !db.Exists <TVEpisode>(q => q.Id == nzb.TVEpisodeId);

                //if (saveEpisode)
                //nzb.TVEpisode.Summary = "";//System.Net.WebUtility.UrlDecode(nzb.TVEpisode.Summary);

                using (var trans = db.OpenTransaction(IsolationLevel.ReadCommitted)) {
                    try {
                        var n = new NZB()
                        {
                            TitleId = title.Id,
                            ImdbId  = nzb.ImdbId,
                            VideoId = nzb.VideoId,
                            Name    = nzb.Name,
                            Parts   = nzb.Parts,
                            Size    = nzb.Size,
                            GroupId = nzb.GroupId,
                            Guid    = nzb.Guid,
                            //NzbGuid = nzb.NzbGuid,
                            ReleaseId   = nzb.ReleaseId,
                            TVEpisodeId = nzb.TVEpisodeId,
                            PostDate    = nzb.PostDate,
                            ImportDate  = DateTime.Now,
                            CategoryId  = nzb.CategoryId,
                            Added       = nzb.AddDate
                        };

                        if (saveVideo)
                        {
                            nzb.Video.Id = nzb.VideoId;
                            db.Save <Video>(nzb.Video);
                        }

                        if (saveEpisode)
                        {
                            nzb.TVEpisode.Id = nzb.TVEpisodeId;
                            db.Save <TVEpisode>(nzb.TVEpisode);
                        }

                        db.Save <NZB>(n);

                        catCount.Total++;
                        db.Save <Count>(catCount);

                        trans.Commit();
                    } catch (Exception e) {
                        trans.Rollback();
                        throw new HttpError(500, "Database error: " + e.Message);
                    } // catch
                }     // trans
            }         // db

            foreach (var file in Request.Files)
            {
                var filename = String.Format("nzb/{0}/{1}/{2}/{3}/{4}",
                                             file.FileName[0],
                                             file.FileName[1],
                                             file.FileName[2],
                                             file.FileName[3],
                                             file.FileName);

                file.SaveTo(VirtualFiles, filename);
            }

            return(true);
        }
Esempio n. 24
0
 public object Get(Images request)
 {
     return(VirtualFiles.GetDirectory(UploadsDir).Files.Map(x => x.Name));
 }
Esempio n. 25
0
        public void Delete(Files request)
        {
            var targetFile = GetAndValidateExistingPath(request);

            VirtualFiles.DeleteFile(targetFile);
        }
Esempio n. 26
0
        public object Any(FastNZB.ServiceModel.APIRequest req)
        {
            if (req.o == "json")
            {
                throw new HttpError(500, "JSON Not supported");
            }

            if (req.t != "g" && req.t != "get")
            {
                base.Request.ResponseContentType = MimeTypes.Xml;
            }

            var function = "";
            IEnumerable <NZBResult> results = new List <NZBResult>();
            int total = 0;

            switch (req.t)
            {
            case "caps":
                function = "c";
                break;

            case "g":
            case "get":
                function = "g";
                break;

            case "s":
            case "search":
                function = "s";
                break;

            case "tv":
            case "tvsearch":
                function = "tv";
                break;

            case "m":
            case "movie":
                function = "m";
                break;

            default:
                throw new HttpError(202, "No such function");
            }

            if (function != "c" && !Db.Exists <APIKey>(q => q.Key == req.apikey))
            {
                return(new HttpError(101, "API Key not present or invalid"));
            }

            // api rate limit to 60/minute
            APIKey key = null;

            if (function != "c")
            {
                key = Db.Single <APIKey>(q => q.Key == req.apikey);
                var cacheKey = String.Format("apikey-rate-{0}", key.Id);
                var requests = Cache.Get <int>(cacheKey);
                if (requests == 0 || DateTime.Now > Cache.Get <DateTime>(cacheKey + "-expires"))
                {
                    requests = 1;
                    Cache.Set <int>(cacheKey, requests);
                    Cache.Set <DateTime>(cacheKey + "-expires", DateTime.Now.AddMinutes(1));
                }
                else
                {
                    Cache.Set <int>(cacheKey, requests + 1);
                }

                if (requests > 60)
                {
                    return(new HttpError(500, "Request limit reached, please try again in one minute"));
                }
            }

            // deter scrapers
            if (req.offset > 1000)
            {
                req.offset = 0;
            }

            // TODO, store these caps values somewhere else
            if (function == "c")
            {
                var caps = new Caps()
                {
                    Server = new Server()
                    {
                        Title      = "fastNZB",
                        Email      = "*****@*****.**",
                        Image      = "https://fastnzb.com/assets/img/nzb.png",
                        Appversion = "1.0.0",
                        Version    = "0.1",
                        Strapline  = "A great usenet indexer",
                        Meta       = "usenet,nzbs,cms,community",
                    },
                    Limits = new Limits()
                    {
                        Max     = "100",
                        Default = "100"
                    },
                    Registration = new Registration()
                    {
                        Open      = "yes",
                        Available = "yes"
                    },
                    Searching = new Searching()
                    {
                        Search = new Search()
                        {
                            Available = "yes", SupportedParams = "q"
                        },
                        Tvsearch = new Tvsearch()
                        {
                            Available       = "yes",
                            SupportedParams = "q,vid,tvdbid,traktid,rid,tvmazeid,imdbid,tmdbid,season,ep",
                        },
                        Moviesearch = new Moviesearch()
                        {
                            Available = "yes", SupportedParams = "q,imdbid"
                        },
                        Audiosearch = new Audiosearch()
                        {
                            Available = "no", SupportedParams = ""
                        },
                    },
                    Categories = new Categories()
                    {
                        Category = new List <FastNZB.ServiceModel.Category>()
                        {
                            new FastNZB.ServiceModel.Category()
                            {
                                Id     = "2000",
                                Name   = "Movies",
                                Subcat = new List <Subcat>()
                                {
                                    new Subcat()
                                    {
                                        Id = "2050", Name = "3D"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2060", Name = "BluRay"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2070", Name = "DVD"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2010", Name = "Foreign"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2040", Name = "HD"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2999", Name = "Other"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2030", Name = "SD"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2045", Name = "UHD"
                                    },
                                    new Subcat()
                                    {
                                        Id = "2080", Name = "WEBDL"
                                    },
                                }
                            },
                            new FastNZB.ServiceModel.Category()
                            {
                                Id     = "5000",
                                Name   = "TV",
                                Subcat = new List <Subcat>()
                                {
                                    new Subcat()
                                    {
                                        Id = "5080", Name = "Documentary"
                                    },
                                    new Subcat()
                                    {
                                        Id = "5040", Name = "HD"
                                    },
                                    new Subcat()
                                    {
                                        Id = "5030", Name = "SD"
                                    },
                                    new Subcat()
                                    {
                                        Id = "5010", Name = "WEB-DL"
                                    },
                                }
                            }
                        },
                    }
                };

                var ser = new XmlSerializer(typeof(Caps));
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");

                using (StringWriter textWriter = new Utf8StringWriter()) {
                    ser.Serialize(textWriter, caps, ns);

                    return(new HttpResult(textWriter.ToString(), "text/xml;charset=UTF-8"));
                }
            }
            else if (function == "s") /* ------------------------------------------------------- */
            {
                var catsrch = GetCatSearch(Db, req.cat);

                var whereSql = String.Format(String.Concat(
                                                 "WHERE 1=1 ",
                                                 "{0} {1} {2} {3} "),
                                             !String.IsNullOrEmpty(req.q) ? GetSphinxSearch(req.q) : "",
                                             catsrch,
                                             req.maxage > 0 ? String.Format("AND r.PostDate > NOW() - INTERVAL {0} DAY", req.maxage) : "",
                                             req.minsize > 0 ? String.Format("AND r.Size >= {0}'", req.minsize) : ""
                                             );

                var baseSql = String.Format(String.Concat(
                                                "SELECT r.*, ",
                                                "concat(cp.title, ' > ', c.title) AS category_name, ",
                                                "g.name AS group_name ",
                                                "FROM NZB r ",
                                                String.IsNullOrEmpty(req.q) ? "" :  "INNER JOIN NZBSearch rse ON rse.id = r.Id ",
                                                "LEFT JOIN `Group` g ON g.id = r.GroupId ",
                                                "LEFT JOIN Category c ON c.id = r.CategoryId ",
                                                "LEFT JOIN Category cp ON cp.id = c.parentid "
                                                ));


                if (!String.IsNullOrEmpty(req.q) && (req.q.Contains("blade") || req.q.Contains("sniper")))
                {
                    whereSql += "AND 0=1 ";
                }

                var sql = String.Format(String.Concat(
                                            "{0} ",
                                            "{1} ORDER BY r.PostDate DESC LIMIT {2} OFFSET {3} "
                                            ), baseSql, whereSql, req.limit > 0 ? (req.limit > 100 ? 100 : req.limit) : 100, req.offset);

                if (String.IsNullOrEmpty(req.q))
                {
                    total = Db.Scalar <int>(String.Format(String.Concat(
                                                              "SELECT SUM(Count) ",
                                                              "FROM Count r WHERE 1=1 ",
                                                              "{0} "), catsrch));
                }
                else
                {
                    total = Db.Scalar <int>(String.Format(String.Concat(
                                                              "SELECT count(*) ",
                                                              "FROM NZB r INNER JOIN NZBSearch rse ON rse.id = r.Id ",
                                                              "{0} "), whereSql));
                }

                results = Db.Select <NZBResult>(sql);
            }
            else if (function == "m") /* ------------------------------------------------------- */
            {
                int imdbId = -1;

                // don't return anything if it's an invalid id
                if (!string.IsNullOrEmpty(req.imdbid) && !int.TryParse(req.imdbid, out imdbId))
                {
                    return(getResults(results, total, req.offset, key, req));
                }

                string catsrch = GetCatSearch(Db, req.cat);

                var whereSql = String.Format(String.Concat(
                                                 "WHERE 1=1 ",
                                                 "{0} {1} {2} {3} {4} "),
                                             !String.IsNullOrEmpty(req.q) ? GetSphinxSearch(req.q) : "",
                                             (imdbId != -1 ? String.Format(" AND imdbid = {0} ", imdbId.ToString().PadLeft(7, '0')) : ""),
                                             catsrch,
                                             req.maxage > 0 ? String.Format("AND r.PostDate > NOW() - INTERVAL {0} DAY", req.maxage) : "",
                                             req.minsize > 0 ? String.Format("AND r.Size >= {0}'", req.minsize) : ""
                                             );

                var baseSql = String.Format(String.Concat(
                                                "SELECT r.*, ",
                                                "concat(cp.title, ' > ', c.title) AS category_name, ",
                                                "g.name AS group_name ",
                                                "FROM NZB r ",
                                                String.IsNullOrEmpty(req.q) ? "" : "INNER JOIN NZBSearch rse ON rse.id = r.Id ",
                                                "LEFT JOIN `Group` g ON g.id = r.GroupId ",
                                                "LEFT JOIN Category c ON c.id = r.CategoryId ",
                                                "LEFT JOIN Category cp ON cp.id = c.parentid "
                                                ));

                var sql = String.Format(String.Concat(
                                            "{0} ",
                                            "{1} ORDER BY r.PostDate DESC LIMIT {2} OFFSET {3} "
                                            ), baseSql, whereSql, req.limit > 0 ? (req.limit > 100 ? 100 : req.limit) : 100, req.offset);

                if (String.IsNullOrEmpty(req.q) && imdbId == -1)
                {
                    total = Db.Scalar <int>(String.Format(String.Concat(
                                                              "SELECT SUM(Count) ",
                                                              "FROM Count r WHERE 1=1 ",
                                                              "{0} "), catsrch));
                }
                else
                {
                    total = Db.Scalar <int>(String.Format(String.Concat(
                                                              "SELECT count(z.id) FROM (SELECT r.id FROM NZB r INNER JOIN NZBSearch rse ON rse.id = r.Id {0} LIMIT 125000) z "), whereSql));
                }

                results = Db.Select <NZBResult>(sql);
            }
            else if (function == "tv") /* ------------------------------------------------------- */
            {
                var airdate = "";
                var series  = "";
                var episode = "";
                // Process season only queries or Season and Episode/Airdate queries
                if (!String.IsNullOrEmpty(req.season) && !String.IsNullOrEmpty(req.ep))
                {
                    if (Regex.IsMatch(req.season, @"(19|20)\d{2}") && req.ep.Contains(@"/"))
                    {
                        var regex = new Regex(@"(19|20)\d{2}").Match(req.season);
                        airdate = (regex.Groups[0] + "-" + req.ep).Replace('/', '-');//str_replace('/', '-', $year[0] . '-' . $_GET['ep']);
                    }
                    else
                    {
                        series  = req.season;
                        episode = req.ep;
                    }
                }
                else if (!String.IsNullOrEmpty(req.season))
                {
                    series  = req.season;
                    episode = (!String.IsNullOrEmpty(req.ep) ? req.ep : "");
                }


                var  query        = "";
                var  siteSQL      = new List <string>();
                var  showSql      = "";
                bool validShowIds = true;

                var siteIdArr = new Dictionary <string, string>()
                {
                    { "id", !String.IsNullOrEmpty(req.vid) ? req.vid : "0" },
                    { "tvdb", !String.IsNullOrEmpty(req.tvdbid) ? req.tvdbid : "0" },
                    { "trakt", !String.IsNullOrEmpty(req.traktid) ? req.traktid : "0" },
                    { "tvrage", !String.IsNullOrEmpty(req.rid) ? req.rid : "0" },
                    { "tvmaze", !String.IsNullOrEmpty(req.tvmazeid) ? req.tvmazeid : "0" },
                    { "imdb", !String.IsNullOrEmpty(req.imdbid) ? req.imdbid : "0" },
                    { "tmdb", !String.IsNullOrEmpty(req.tmdbid) ? req.tmdbid : "0" }
                };

                foreach (var val in siteIdArr)
                {
                    int id = 0;

                    if (!int.TryParse(val.Value, out id))
                    {
                        validShowIds = false;
                    }

                    if (id > 0)
                    {
                        siteSQL.Add(String.Format("{0} = {1} ", val.Key, id));
                    }
                    //siteSQL += String.Format("OR {0} = {1} ", val.Key, id);
                }

                if (siteSQL.Count > 0)
                {
                    int episodeInt = 0;
                    int seriesInt  = 0;
                    int.TryParse(new Regex(@"^s0*", RegexOptions.IgnoreCase).Replace(series, ""), out seriesInt);
                    int.TryParse(new Regex(@"^e0*", RegexOptions.IgnoreCase).Replace(episode, ""), out episodeInt);

                    var showQuery = String.Format(String.Concat(
                                                      "SELECT ",
                                                      "v.id AS video, ",
                                                      "CAST(GROUP_CONCAT(tve.id SEPARATOR ',') AS CHAR) AS episodes ",
                                                      "FROM Video v ",
                                                      "LEFT JOIN TVEpisode tve ON v.id = tve.videos_id ",
                                                      "WHERE ({0}) {1} {2} {3} ",
                                                      "GROUP BY v.id "),
                                                  siteSQL.Join(" OR "),
                                                  !String.IsNullOrEmpty(series) ? String.Format("AND tve.series = {0}", seriesInt) : "",
                                                  !String.IsNullOrEmpty(episode) ? String.Format("AND tve.episode = {0}", episodeInt) : "",
                                                  !String.IsNullOrEmpty(airdate) ? String.Format("AND DATE(tve.firstaired) = '{0}'", esc(airdate)) : ""
                                                  );
                    //return new HttpResult(showQuery);
                    var show = Db.Single <ShowNZB>(showQuery);
                    if (show != null)
                    {
                        if ((!String.IsNullOrEmpty(series) || !String.IsNullOrEmpty(episode) || !String.IsNullOrEmpty(airdate)) && show.episodes.Length > 0)
                        {
                            showSql = String.Format(" AND r.TVEpisodeId IN ({0}) ", show.episodes);
                        }
                        else if (show.video > 0)
                        {
                            showSql = " AND r.VideoId = " + show.video + " ";
                            // If $series is set but episode is not, return Season Packs only
                            if (!String.IsNullOrEmpty(series) && String.IsNullOrEmpty(episode))
                            {
                                showSql += " AND r.tv_episodes_id = 0 ";
                            }
                        }
                        else
                        {
                            // If we were passed Episode Info and no match was found, do not run the query
                            return(getResults(results, total, req.offset, key, req));
                        }
                    }
                    else
                    {
                        // If we were passed Site ID Info and no match was found, do not run the query
                        return(getResults(results, total, req.offset, key, req));
                    }
                }
                // no valid ids found, return nil
                else if (siteSQL.Count == 0 && !validShowIds)
                {
                    return(getResults(results, total, req.offset, key, req));
                }

                // If $name is set it is a fallback search, add available SxxExx/airdate info to the query
                if (!String.IsNullOrEmpty(req.q) && showSql == "")
                {
                    int seriesInt = 0;
                    int.TryParse(series, out seriesInt);
                    if (!String.IsNullOrEmpty(series) && seriesInt < 1900)
                    {
                        req.q += String.Format(" S{0}", series.PadLeft(2, '0'));
                        if (!String.IsNullOrEmpty(episode) && !episode.Contains(@"/"))
                        {
                            req.q += String.Format("E{0}", episode.PadLeft(2, '0'));
                        }
                    }
                    else if (!String.IsNullOrEmpty(airdate))
                    {
                        req.q += String.Format(" {0}",
                                               airdate.Replace(@"/", " ")
                                               .Replace("-", " ")
                                               .Replace(".", " ")
                                               .Replace("_", " "));
                    }
                }


                string catsrch = GetCatSearch(Db, req.cat);

                string whereSql = String.Format(String.Concat(
                                                    "WHERE 1=1 ",
                                                    "{0} ",
                                                    "{1} {2} {3} {4} "),
                                                !String.IsNullOrEmpty(req.q) ? GetSphinxSearch(req.q) : "",
                                                catsrch,
                                                showSql,
                                                req.maxage > 0 ? String.Format("AND r.PostDate > NOW() - INTERVAL {0} DAY", req.maxage) : "",
                                                req.minsize > 0 ? String.Format("AND r.Size >= {0}'", req.minsize) : ""
                                                );

                query = String.Format(String.Concat(
                                          "SELECT r.*,",
                                          "v.title, v.countries_id, v.started, v.tvdb, v.trakt,",
                                          "    v.imdb, v.tmdb, v.tvmaze, v.tvrage, v.source,",
                                          "tve.series, tve.episode, tve.se_complete, tve.title, tve.firstaired, tve.summary, ",
                                          "CONCAT(cp.title, ' > ', c.title) AS category_name, ",
                                          "Group.name AS group_name ",
                                          "FROM NZB r ",
                                          String.IsNullOrEmpty(req.q) ? "" : "INNER JOIN NZBSearch rse ON rse.id = r.Id ",
                                          "LEFT OUTER JOIN Video v ON r.VideoId = v.id AND v.type = 0 ",
                                          "LEFT OUTER JOIN TVEpisode tve ON r.TVEpisodeId = tve.id ",
                                          "LEFT JOIN Category c ON c.id = r.CategoryId ",
                                          "LEFT JOIN Category cp ON cp.id = c.parentid ",
                                          "LEFT JOIN `Group` ON `Group`.id = r.GroupId ",
                                          "{0} ORDER BY PostDate DESC LIMIT {1} OFFSET {2} "),
                                      whereSql, req.limit > 0 ? (req.limit > 100 ? 100 : req.limit) : 100, req.offset);

                results = Db.Select <NZBResult>(query);

                if (String.IsNullOrEmpty(req.q) && String.IsNullOrEmpty(showSql))
                {
                    total = Db.Scalar <int>(String.Format(String.Concat(
                                                              "SELECT SUM(Count) ",
                                                              "FROM Count r WHERE 1=1 ",
                                                              "{0} "), catsrch));
                }
                else
                {
                    total = Db.Scalar <int>(String.Format(String.Concat(
                                                              "SELECT count(z.id) FROM (SELECT r.id FROM NZB r ",
                                                              "INNER JOIN NZBSearch rse ON rse.id = r.Id ",
                                                              "LEFT OUTER JOIN Video v ON r.VideoId = v.id AND v.type = 0 ",
                                                              "LEFT OUTER JOIN TVEpisode tve ON r.TVEpisodeId = tve.id {0} LIMIT 125000) z "
                                                              ), whereSql));
                }
            }
            else if (function == "g") /* ------------------------------------------------------- */
            {
                var nzb = Db.Single <NZB>(q => q.Guid == req.id);

                using (var db = ConnectionFactory.OpenDbConnection())
                {
                    db.Insert <Download>(new Download()
                    {
                        NZBId     = nzb.Id,
                        APIKeyId  = key.Id,
                        IPAddress = Request.Headers["X-Forwarded-For"],
                    });
                }

                var nzbpath = String.Format("nzb/{0}/{1}/{2}/{3}/",
                                            req.id[0],
                                            req.id[1],
                                            req.id[2],
                                            req.id[3]);
                var filename = String.Format("{0}.nzb.gz", req.id);
                var path     = _settings.Get <string>("FSPath");

                Stream stream = null;

                // check if nzb is stored in cache, else get from virt files (S3)
                if (!Directory.Exists(path + nzbpath) || !File.Exists(path + filename))
                {
                    var file = VirtualFiles.GetFile(nzbpath + filename);
                    Directory.CreateDirectory(path + nzbpath);
                    File.WriteAllBytes(path + nzbpath + filename, file.ReadAllBytes());
                }
                stream = File.OpenRead(path + nzbpath + filename);

                Response.AddHeader("Content-Disposition", "attachment; filename=" + nzb.Name + ".nzb");

                // decompress gzip
                MemoryStream output = new MemoryStream();

                using (Stream originalFileStream = stream)
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(output);
                    }
                }

                return(new HttpResult(output, "application/x-nzb"));
            }

            return(getResults(results, total, req.offset, key, req));
        }
Esempio n. 27
0
 /// <summary>
 /// Doesn't actually add a file, but instead reserves space.  This is used with "bUseAdaptiveUnityBuild", to prevent
 /// other compiled unity blobs in the module's numbered set from having to be recompiled after we eject source files
 /// one of that module's unity blobs.  Basically, it can prevent dozens of files from being recompiled after the first
 /// time building after your working set of source files changes
 /// </summary>
 /// <param name="File">The virtual file to add to the collection</param>
 public void AddVirtualFile(FileItem File)
 {
     VirtualFiles.Add(File);
     VirtualLength += File.Length;
 }
Esempio n. 28
0
 ? fileContents(VirtualFiles, path)
 : file is IVirtualFile ifile
Esempio n. 29
0
 public override void Save(string path, StaticContent content)
 {
     VirtualFiles.WriteFile(DirPath.CombineWith(path), content.Data);
 }
Esempio n. 30
0
        public async Task <object> Get(GistRef request)
        {
            if (string.IsNullOrEmpty(request.Slug))
            {
                throw new ArgumentNullException(nameof(request.Slug));
            }
            if (string.IsNullOrEmpty(request.Lang))
            {
                throw new ArgumentNullException(nameof(request.Lang));
            }
            var lang = LangInfoUtils.AssertLangInfo(request.Lang);

            var includeTypes = string.IsNullOrEmpty(request.IncludeTypes)
                ? null
                : request.IncludeTypes;

            var requestDto = includeTypes;
            Dictionary <string, string> args = null;

            if (includeTypes != null && includeTypes.IndexOf('(') >= 0)
            {
                var kvps = includeTypes.RightPart('(');
                kvps         = '{' + kvps.Substring(0, kvps.Length - 1) + '}';
                args         = kvps.FromJsv <Dictionary <string, string> >();
                includeTypes = includeTypes.LeftPart('(');
                requestDto   = includeTypes.LastRightPart(',');

                //If any includeTypes were given (e.g. tag) use that instead of just Request DTO:
                if (includeTypes.IndexOf(',') >= 0)
                {
                    includeTypes = includeTypes.LastLeftPart(',');
                    //Replace URL-friendly brackets with braces
                    includeTypes = includeTypes.Replace('[', '{').Replace(']', '}');
                    //Treat '*' as All DTOs, i.e. don't limit included DTO Types
                    if (includeTypes == "*")
                    {
                        includeTypes = null;
                    }
                }
                else if (!includeTypes.EndsWith(".*"))
                {
                    includeTypes += ".*";
                }
            }

            var baseUrl = request.Slug;

            if (baseUrl.IndexOf("://", StringComparison.Ordinal) == -1)
            {
                if (baseUrl.StartsWith("http.") || baseUrl.StartsWith("https."))
                {
                    baseUrl = baseUrl.LeftPart('.') + "://" + baseUrl.RightPart('.');
                }
                else
                {
                    baseUrl = "https://" + baseUrl;
                }
            }

            var key = $"{nameof(GistRef)}:{baseUrl}:{lang.Code}:{request.IncludeTypes??"*"}.gist";

            if (request.NoCache == true)
            {
                await CacheAsync.RemoveAsync(key);
            }
            var gist = await CacheAsync.GetOrCreateAsync(key, TimeSpan.FromMinutes(10), async() => {
                var site         = await Sites.GetSiteAsync(request.Slug);
                var langInfo     = await site.Languages.GetLanguageInfoAsync(request.Lang);
                var baseUrlTitle = baseUrl.RightPart("://").LeftPart("/");
                if (includeTypes != null)
                {
                    baseUrlTitle += $" {requestDto}";
                    langInfo      = await langInfo.ForRequestAsync(includeTypes);
                }
                var langTypesContent = langInfo.Content;

                var files        = new Dictionary <string, GistFile>();
                var description  = $"{baseUrlTitle} {lang.Name} API";
                var meta         = site.Metadata.Api;
                var requestOp    = meta.Operations.FirstOrDefault(x => x.Request.Name == requestDto);
                var authTemplate = requestOp?.RequiresAuth == true
                    ? lang.RequiresAuthTemplate
                    : "";

                var types = new List <string> {
                    requestDto ?? "MyRequest"
                };
                if (requestOp != null && args != null)
                {
                    var props = requestOp.Request.GetFlattenedProperties(meta);
                    foreach (var entry in args)
                    {
                        var prop = props.FirstOrDefault(x =>
                                                        string.Equals(x.Name, entry.Key, StringComparison.OrdinalIgnoreCase));
                        var propType = prop?.Type != null ? meta.FindType(prop.Type, prop.Namespace) : null;
                        if (propType != null)
                        {
                            types.Add(propType.Name);
                        }
                    }
                }

                lang.Files.Each((string k, string v) => {
                    var content = v
                                  .Replace("{BASE_URL}", baseUrl)
                                  .Replace("{REQUEST}", requestDto ?? "MyRequest")
                                  .Replace("{RESPONSE}", lang.GetResponse(requestOp))
                                  .Replace("{TYPES}", string.Join(", ", types))
                                  .Replace("{API_COMMENT}", request.IncludeTypes != null ? "" : lang.LineComment)
                                  .Replace("{REQUIRES_AUTH}", authTemplate)
                                  .Replace("{DESCRIPTION}", description)
                                  .Replace("{INSPECT_VARS}", requestDto != null ? lang.InspectVarsResponse : null);

                    var textCase = site.Metadata.App.JsTextCase != null
                        ? (TextCase)Enum.Parse(typeof(TextCase), site.Metadata.App.JsTextCase, ignoreCase: true)
                        : TextCase.CamelCase;
                    using var jsScope = JsConfig.With(new Config { TextCase = textCase });
                    {
                        content = args != null
                            ? content.Replace("{REQUEST_BODY}", lang.RequestBody(requestDto, args, meta))
                            : content.Replace("{REQUEST_BODY}", "");
                    }

                    var file = new GistFile {
                        Filename = k,
                        Content  = content,
                        Type     = MimeTypes.PlainText,
                        Raw_Url  = new GistRefFile {
                            Slug = request.Slug, Lang = lang.Code, File = k
                        }.ToAbsoluteUri(Request),
                    };
                    file.Size = file.Content.Length;
                    files[k]  = file;
                });

                var langFiles = VirtualFiles.GetDirectory($"files/{lang.Code}");
                if (langFiles != null)
                {
                    foreach (var file in langFiles.GetAllFiles())
                    {
                        var content           = file.ReadAllText();
                        lang.Files[file.Name] = content;
                    }
                }

                var dtoFileName    = $"{lang.DtosPathPrefix}dtos.{lang.Ext}";
                files[dtoFileName] = new GistFile {
                    Filename = dtoFileName,
                    Content  = langTypesContent,
                    Size     = langTypesContent.Length,
                    Type     = MimeTypes.PlainText,
                    Raw_Url  = langInfo.Url,
                };

                var resolvedUrl = Request.IsSecureConnection
                    ? "https://" + Request.AbsoluteUri.RightPart("://")
                    : Request.AbsoluteUri;
                var to = new GithubGist {
                    Description = description,
                    Created_At  = DateTime.UtcNow,
                    Files       = files,
                    Public      = true,
                    Url         = resolvedUrl,
                    Owner       = new GithubUser {
                        Id         = 76883648,
                        Login      = "******",
                        Avatar_Url = "https://avatars2.githubusercontent.com/u/76883648?v=4",
                        Url        = "https://api.github.com/users/gistcafe",
                        Html_Url   = "https://github.com/gistcafe",
                        Type       = "User"
                    }
                };
                var hashCode = new HashCode();
                hashCode.Add(to.Description);
                files.Each(entry => {
                    hashCode.Add(entry.Key);
                    hashCode.Add(entry.Value);
                });
                to.Id = resolvedUrl;
                return(to);
            });