public HttpResult(FileInfo fileResponse, bool asAttachment) : this(fileResponse, MimeTypes.GetMimeType(fileResponse.Name), asAttachment) { }
/// <summary> /// Gets the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns>System.Object.</returns> public Task <object> Get(GetDashboardConfigurationPage request) { IPlugin plugin = null; Stream stream = null; var page = ServerEntryPoint.Instance.PluginConfigurationPages.FirstOrDefault(p => string.Equals(p.Name, request.Name, StringComparison.OrdinalIgnoreCase)); if (page != null) { plugin = page.Plugin; stream = page.GetHtmlStream(); } if (plugin == null) { var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, request.Name, StringComparison.OrdinalIgnoreCase)); if (altPage != null) { plugin = altPage.Item2; stream = _assemblyInfo.GetManifestResourceStream(plugin.GetType(), altPage.Item1.EmbeddedResourcePath); } } if (plugin != null && stream != null) { return(_resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator(DashboardUIPath).ModifyHtml("dummy.html", stream, null, _appHost.ApplicationVersion.ToString(), null))); } throw new ResourceNotFoundException(); }
public FileReference Store(string Name, Stream Stream) { string ContentType = MimeTypes.GetMimeType(Name); return(this.Store(Name, Stream, ContentType)); }
/// <summary> /// Initializes a new instance of the <see cref="GenericFileResponse"/> for the file specified /// by the <paramref name="filePath"/> parameter. /// </summary> /// <param name="filePath">The name of the file, including path relative to the root of the application, that should be returned.</param> /// <remarks>The <see cref="MimeTypes.GetMimeType"/> method will be used to determine the mimetype of the file and will be used as the content-type of the response. If no match if found the content-type will be set to application/octet-stream.</remarks> public GenericFileResponse(string filePath) : this(filePath, MimeTypes.GetMimeType(filePath)) { }
public async Task <Tuple <string, string, DateTime> > ProcessImage(ImageProcessingOptions options) { if (options == null) { throw new ArgumentNullException("options"); } var originalImage = options.Image; var item = options.Item; if (!originalImage.IsLocalFile) { if (item == null) { item = _libraryManager().GetItemById(options.ItemId); } originalImage = await _libraryManager().ConvertImageToLocal(item, originalImage, options.ImageIndex).ConfigureAwait(false); } var originalImagePath = originalImage.Path; var dateModified = originalImage.DateModified; var originalImageSize = originalImage.Width > 0 && originalImage.Height > 0 ? new ImageSize(originalImage.Width, originalImage.Height) : (ImageSize?)null; if (!_imageEncoder.SupportsImageEncoding) { return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified)); } var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false); originalImagePath = supportedImageInfo.Item1; dateModified = supportedImageInfo.Item2; var requiresTransparency = TransparentImageTypes.Contains(Path.GetExtension(originalImagePath) ?? string.Empty); if (options.Enhancers.Length > 0) { if (item == null) { item = _libraryManager().GetItemById(options.ItemId); } var tuple = await GetEnhancedImage(new ItemImageInfo { DateModified = dateModified, Type = originalImage.Type, Path = originalImagePath }, requiresTransparency, item, options.ImageIndex, options.Enhancers, CancellationToken.None).ConfigureAwait(false); originalImagePath = tuple.Item1; dateModified = tuple.Item2; requiresTransparency = tuple.Item3; // TODO: Get this info originalImageSize = null; } var photo = item as Photo; var autoOrient = false; ImageOrientation?orientation = null; if (photo != null) { if (photo.Orientation.HasValue) { if (photo.Orientation.Value != ImageOrientation.TopLeft) { autoOrient = true; orientation = photo.Orientation; } } else { // Orientation unknown, so do it autoOrient = true; orientation = photo.Orientation; } } if (options.HasDefaultOptions(originalImagePath, originalImageSize) && (!autoOrient || !options.RequiresAutoOrientation)) { // Just spit out the original file if all the options are default return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified)); } //ImageSize? originalImageSize = GetSavedImageSize(originalImagePath, dateModified); //if (originalImageSize.HasValue && options.HasDefaultOptions(originalImagePath, originalImageSize.Value) && !autoOrient) //{ // // Just spit out the original file if all the options are default // _logger.Info("Returning original image {0}", originalImagePath); // return new ValueTuple<string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified); //} var newSize = ImageHelper.GetNewImageSize(options, null); var quality = options.Quality; var outputFormat = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency); var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer); CheckDisposed(); var lockInfo = GetLock(cacheFilePath); await lockInfo.Lock.WaitAsync().ConfigureAwait(false); try { if (!_fileSystem.FileExists(cacheFilePath)) { if (options.CropWhiteSpace && !SupportsTransparency(originalImagePath)) { options.CropWhiteSpace = false; } var resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat); if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase)) { return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified)); } return(new Tuple <string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath))); } return(new Tuple <string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath))); } catch (ArgumentOutOfRangeException ex) { // Decoder failed to decode it #if DEBUG _logger.ErrorException("Error encoding image", ex); #endif // Just spit out the original file if all the options are default return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified)); } catch (Exception ex) { // If it fails for whatever reason, return the original image _logger.ErrorException("Error encoding image", ex); // Just spit out the original file if all the options are default return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified)); } finally { ReleaseLock(cacheFilePath, lockInfo); } }
/// <summary> /// Processes the request async. /// </summary> /// <param name="request">The request.</param> /// <param name="isLive">if set to <c>true</c> [is live].</param> /// <returns>Task{System.Object}.</returns> /// <exception cref="ArgumentException">A video bitrate is required /// or /// An audio bitrate is required</exception> private async Task <object> ProcessRequestAsync(StreamRequest request, bool isLive) { var cancellationTokenSource = new CancellationTokenSource(); var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false); TranscodingJob job = null; var playlist = state.OutputFilePath; if (!FileSystem.FileExists(playlist)) { await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false); try { if (!FileSystem.FileExists(playlist)) { // If the playlist doesn't already exist, startup ffmpeg try { job = await StartFfMpeg(state, playlist, cancellationTokenSource).ConfigureAwait(false); job.IsLiveOutput = isLive; } catch { state.Dispose(); throw; } var waitForSegments = state.SegmentLength >= 10 ? 2 : 3; await WaitForMinimumSegmentCount(playlist, waitForSegments, cancellationTokenSource.Token).ConfigureAwait(false); } } finally { ApiEntryPoint.Instance.TranscodingStartLock.Release(); } } if (isLive) { job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType); if (job != null) { ApiEntryPoint.Instance.OnTranscodeEndRequest(job); } return(ResultFactory.GetResult(GetLivePlaylistText(playlist, state.SegmentLength), MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary <string, string>())); } var audioBitrate = state.OutputAudioBitrate ?? 0; var videoBitrate = state.OutputVideoBitrate ?? 0; var appendBaselineStream = false; var baselineStreamBitrate = 64000; var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, appendBaselineStream, baselineStreamBitrate); job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType); if (job != null) { ApiEntryPoint.Instance.OnTranscodeEndRequest(job); } return(ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary <string, string>())); }
public async Task <ActionResult> GetVideoStream( [FromRoute, Required] Guid itemId, [FromQuery] string?container, [FromQuery] bool? @static, [FromQuery] string? @params, [FromQuery] string?tag, [FromQuery] string?deviceProfileId, [FromQuery] string?playSessionId, [FromQuery] string?segmentContainer, [FromQuery] int?segmentLength, [FromQuery] int?minSegments, [FromQuery] string?mediaSourceId, [FromQuery] string?deviceId, [FromQuery] string?audioCodec, [FromQuery] bool?enableAutoStreamCopy, [FromQuery] bool?allowVideoStreamCopy, [FromQuery] bool?allowAudioStreamCopy, [FromQuery] bool?breakOnNonKeyFrames, [FromQuery] int?audioSampleRate, [FromQuery] int?maxAudioBitDepth, [FromQuery] int?audioBitRate, [FromQuery] int?audioChannels, [FromQuery] int?maxAudioChannels, [FromQuery] string?profile, [FromQuery] string?level, [FromQuery] float?framerate, [FromQuery] float?maxFramerate, [FromQuery] bool?copyTimestamps, [FromQuery] long?startTimeTicks, [FromQuery] int?width, [FromQuery] int?height, [FromQuery] int?videoBitRate, [FromQuery] int?subtitleStreamIndex, [FromQuery] SubtitleDeliveryMethod?subtitleMethod, [FromQuery] int?maxRefFrames, [FromQuery] int?maxVideoBitDepth, [FromQuery] bool?requireAvc, [FromQuery] bool?deInterlace, [FromQuery] bool?requireNonAnamorphic, [FromQuery] int?transcodingMaxAudioChannels, [FromQuery] int?cpuCoreLimit, [FromQuery] string?liveStreamId, [FromQuery] bool?enableMpegtsM2TsMode, [FromQuery] string?videoCodec, [FromQuery] string?subtitleCodec, [FromQuery] string?transcodeReasons, [FromQuery] int?audioStreamIndex, [FromQuery] int?videoStreamIndex, [FromQuery] EncodingContext?context, [FromQuery] Dictionary <string, string> streamOptions) { var isHeadRequest = Request.Method == System.Net.WebRequestMethods.Http.Head; var cancellationTokenSource = new CancellationTokenSource(); var streamingRequest = new VideoRequestDto { Id = itemId, Container = container, Static = @static ?? false, Params = @params, Tag = tag, DeviceProfileId = deviceProfileId, PlaySessionId = playSessionId, SegmentContainer = segmentContainer, SegmentLength = segmentLength, MinSegments = minSegments, MediaSourceId = mediaSourceId, DeviceId = deviceId, AudioCodec = audioCodec, EnableAutoStreamCopy = enableAutoStreamCopy ?? true, AllowAudioStreamCopy = allowAudioStreamCopy ?? true, AllowVideoStreamCopy = allowVideoStreamCopy ?? true, BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false, AudioSampleRate = audioSampleRate, MaxAudioChannels = maxAudioChannels, AudioBitRate = audioBitRate, MaxAudioBitDepth = maxAudioBitDepth, AudioChannels = audioChannels, Profile = profile, Level = level, Framerate = framerate, MaxFramerate = maxFramerate, CopyTimestamps = copyTimestamps ?? false, StartTimeTicks = startTimeTicks, Width = width, Height = height, VideoBitRate = videoBitRate, SubtitleStreamIndex = subtitleStreamIndex, SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.Encode, MaxRefFrames = maxRefFrames, MaxVideoBitDepth = maxVideoBitDepth, RequireAvc = requireAvc ?? false, DeInterlace = deInterlace ?? false, RequireNonAnamorphic = requireNonAnamorphic ?? false, TranscodingMaxAudioChannels = transcodingMaxAudioChannels, CpuCoreLimit = cpuCoreLimit, LiveStreamId = liveStreamId, EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false, VideoCodec = videoCodec, SubtitleCodec = subtitleCodec, TranscodeReasons = transcodeReasons, AudioStreamIndex = audioStreamIndex, VideoStreamIndex = videoStreamIndex, Context = context ?? EncodingContext.Streaming, StreamOptions = streamOptions }; using var state = await StreamingHelpers.GetStreamingState( streamingRequest, Request, _authContext, _mediaSourceManager, _userManager, _libraryManager, _serverConfigurationManager, _mediaEncoder, _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, _transcodingJobType, cancellationTokenSource.Token) .ConfigureAwait(false); if (@static.HasValue && @static.Value && state.DirectStreamProvider != null) { StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager); await new ProgressiveFileCopier(state.DirectStreamProvider, null, _transcodingJobHelper, CancellationToken.None) { AllowEndOfFile = false }.WriteToAsync(Response.Body, CancellationToken.None) .ConfigureAwait(false); // TODO (moved from MediaBrowser.Api): Don't hardcode contentType return(File(Response.Body, MimeTypes.GetMimeType("file.ts") !)); } // Static remote stream if (@static.HasValue && @static.Value && state.InputProtocol == MediaProtocol.Http) { StreamingHelpers.AddDlnaHeaders(state, Response.Headers, true, startTimeTicks, Request, _dlnaManager); var httpClient = _httpClientFactory.CreateClient(NamedClient.Default); return(await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, isHeadRequest, httpClient, HttpContext).ConfigureAwait(false)); } if (@static.HasValue && @static.Value && state.InputProtocol != MediaProtocol.File) { return(BadRequest($"Input protocol {state.InputProtocol} cannot be streamed statically")); } var outputPath = state.OutputFilePath; var outputPathExists = System.IO.File.Exists(outputPath); var transcodingJob = _transcodingJobHelper.GetTranscodingJob(outputPath, TranscodingJobType.Progressive); var isTranscodeCached = outputPathExists && transcodingJob != null; StreamingHelpers.AddDlnaHeaders(state, Response.Headers, (@static.HasValue && @static.Value) || isTranscodeCached, startTimeTicks, Request, _dlnaManager); // Static stream if (@static.HasValue && @static.Value) { var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath); if (state.MediaSource.IsInfiniteStream) { await new ProgressiveFileCopier(state.MediaPath, null, _transcodingJobHelper, CancellationToken.None) { AllowEndOfFile = false }.WriteToAsync(Response.Body, CancellationToken.None) .ConfigureAwait(false); return(File(Response.Body, contentType)); } return(FileStreamResponseHelpers.GetStaticFileResult( state.MediaPath, contentType, isHeadRequest, HttpContext)); } // Need to start ffmpeg (because media can't be returned directly) var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, outputPath, "superfast"); return(await FileStreamResponseHelpers.GetTranscodedFile( state, isHeadRequest, HttpContext, _transcodingJobHelper, ffmpegCommandLineArguments, _transcodingJobType, cancellationTokenSource).ConfigureAwait(false)); }
private async Task <T> PostItemAsync <T>(string path, Dictionary <string, object> bodyParams) { T returnItem = (T)System.Activator.CreateInstance(typeof(T)); HttpContent content; if (bodyParams.ContainsKey("files") && IsLocalPath(bodyParams["files"])) { MultipartFormDataContent multiPartContent = new MultipartFormDataContent("----BotsDotNet.WebExTeams.SparkDotNetBoundary"); string[] filelist = (string[])bodyParams["files"]; bodyParams.Remove("files"); foreach (KeyValuePair <string, object> kv in bodyParams) { StringContent stringContent = new StringContent((string)kv.Value); multiPartContent.Add(stringContent, kv.Key); } foreach (string file in filelist) { FileInfo fi = new FileInfo(file); string fileName = fi.Name; byte[] fileContents = File.ReadAllBytes(fi.FullName); ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents); byteArrayContent.Headers.Add("Content-Type", MimeTypes.GetMimeType(fileName)); multiPartContent.Add(byteArrayContent, "files", fileName); } content = multiPartContent; } else if (bodyParams.ContainsKey("file_bytes")) { var fileData = (MemoryFile)bodyParams["file_bytes"]; bodyParams.Remove("file_bytes"); var multiPartContent = new MultipartFormDataContent("----BotsDotNet.WebExTeams.SparkDotNetBoundary"); foreach (var kv in bodyParams) { var sc = new StringContent((string)kv.Value); multiPartContent.Add(sc, kv.Key); } ByteArrayContent byteArrayContent = new ByteArrayContent(fileData.Content); byteArrayContent.Headers.Add("Content-Type", MimeTypes.GetMimeType(fileData.FileName)); multiPartContent.Add(byteArrayContent, "files", fileData.FileName); content = multiPartContent; } else { var jsonBody = JsonConvert.SerializeObject(bodyParams); content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); } HttpResponseMessage response = await client.PostAsync(path, content); if (response.IsSuccessStatusCode) { returnItem = DeserializeObject <T>(await response.Content.ReadAsStringAsync()); } else { throw new SparkException((int)response.StatusCode, $"{(int)response.StatusCode} ({response.ReasonPhrase})", response.Headers); } return(returnItem); }
private static void Upload(object state) { try { if (UploadList.Count == 0) { _uploading = false; return; } UploadEntry entry; try { var l = UploadList.ToList(); entry = l[0]; l.RemoveAt(0); UploadList = l.ToList(); } catch { _uploading = false; return; } var s = Service; if (s == null) { _uploading = false; return; } FileInfo fi; byte[] byteArray; try { fi = new FileInfo(entry.SourceFilename); byteArray = Helper.ReadBytesWithRetry(fi); } catch (Exception ex) { //file doesn't exist Logger.LogException(ex); _uploading = false; return; } var mt = MimeTypes.GetMimeType(fi.Extension); var body = new File { Name = fi.Name, Description = "iSpy", MimeType = mt }; string fid = GetOrCreateFolder(entry.DestinationPath); try { using (var stream = new MemoryStream(byteArray)) { body.Parents = new List <string> { fid }; var request = s.Files.Create(body, stream, mt); request.ProgressChanged += RequestProgressChanged; request.ResponseReceived += RequestResponseReceived; try { request.Upload(); } catch (Exception ex) { Logger.LogException(ex); } } } catch (Exception ex) { Logger.LogException(ex); } Upload(null); } catch (Exception ex) { Logger.LogException(ex, "Dropbox"); } }
protected string GetMimeType(FileInfo file) { return(MimeTypes.GetMimeType(file.Extension)); }
private async Task <object> DownloadFileAsync(dynamic args) { if (!ParseModType(args, out ModType modType, out Response errorResponse)) { return(await errorResponse); } string versionQuery = args.version; ModVersion version = Data.FindVersion(modType, versionQuery, includeUnreleased: false); if (version == null) { return(await Response.JsonError($"The version '{versionQuery}' could not be found.", HttpStatusCode.NotFound)); } string filePath = args.filePath; ZipArchive archive = version.OpenZipArchive(); foreach (var entry in archive.Entries) { if (entry.Name == string.Empty) { continue; } if (entry.FullName.ToLowerInvariant() == filePath.ToLowerInvariant()) { Stream fileStream = entry.Open(); var response = new ZipStreamResponse(archive, () => fileStream, MimeTypes.GetMimeType(entry.FullName)); return(await response .WithHeader("X-File-Length", entry.Length.ToString()) .AsAttachment(entry.Name)); } } archive.Dispose(); return(await Response.JsonError("The file could not be found.", HttpStatusCode.NotFound)); }
public void PostFile_does_work_with_BasicAuth() { var client = GetClientWithUserPassword(); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); var expectedContents = new StreamReader(uploadFile.OpenRead()).ReadToEnd(); var response = client.PostFile <FileUploadResponse>(ListeningOn + "/securedfileupload", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); Assert.That(response.FileName, Is.EqualTo(uploadFile.Name)); Assert.That(response.ContentLength, Is.EqualTo(uploadFile.Length)); Assert.That(response.Contents, Is.EqualTo(expectedContents)); }
public void PostFile_with_no_Credentials_throws_UnAuthorized() { try { var client = GetClient(); var uploadFile = new FileInfo("~/TestExistingDir/upload.html".MapProjectPath()); client.PostFile <FileUploadResponse>(ListeningOn + "/securedfileupload", uploadFile, MimeTypes.GetMimeType(uploadFile.Name)); Assert.Fail("Shouldn't be allowed"); } catch (WebServiceException webEx) { Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized)); Console.WriteLine(webEx.ResponseDto.Dump()); } }
public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName) { response.EndHttpRequest(skipClose: true, afterBody: r => { var fileName = request.GetPhysicalPath(); var fi = new FileInfo(fileName); if (!fi.Exists) { if ((fi.Attributes & FileAttributes.Directory) != 0) { foreach (var defaultDoc in EndpointHost.Config.DefaultDocuments) { var defaultFileName = Path.Combine(fi.FullName, defaultDoc); if (!File.Exists(defaultFileName)) { continue; } r.Redirect(request.GetPathUrl() + '/' + defaultDoc); return; } } if (!fi.Exists) { throw new HttpException(404, "File '" + request.PathInfo + "' not found."); } } TimeSpan maxAge; if (r.ContentType != null && EndpointHost.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge)) { r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds); } if (request.HasNotModifiedSince(fi.LastWriteTime)) { r.ContentType = MimeTypes.GetMimeType(fileName); r.StatusCode = 304; return; } try { r.AddHeaderLastModified(fi.LastWriteTime); r.ContentType = MimeTypes.GetMimeType(fileName); if (fileName.EqualsIgnoreCase(this.DefaultFilePath)) { if (fi.LastWriteTime > this.DefaultFileModified) { SetDefaultFile(this.DefaultFilePath); //reload } r.OutputStream.Write(this.DefaultFileContents, 0, this.DefaultFileContents.Length); r.Close(); return; } if (!Env.IsMono) { r.TransmitFile(fileName); } else { r.WriteFile(fileName); } } catch (Exception) { throw new HttpException(403, "Forbidden."); } }); }
public BufferedFileStreamActionResult(string fileName, string streamId) : base(MimeTypes.GetMimeType(fileName)) { FileName = TitleEnumerationService.GetUncPath(fileName); StreamId = streamId; }
public WebResponse UploadFile(string pathInfo, FileInfo fileInfo) { //long length = 0; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); var httpWebRequest = (HttpWebRequest)WebRequest.Create(base.ServiceClientBaseUri + pathInfo); httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest.Accept = ContentType.Json; httpWebRequest.Method = "POST"; httpWebRequest.AllowAutoRedirect = false; httpWebRequest.KeepAlive = false; Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary); string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, "upload", fileInfo.Name, MimeTypes.GetMimeType(fileInfo.Name)); byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); //Image img = null; //img = Image.FromFile("C:/Documents and Settings/Dorin Cucicov/My Documents/My Pictures/Sunset.jpg", true); //img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg); using (var fs = fileInfo.OpenRead()) { fs.WriteTo(memStream); } memStream.Write(boundarybytes, 0, boundarybytes.Length); //string formdataTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; //string formitem = string.Format(formdataTemplate, "headline", "Sunset"); //byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); //memStream.Write(formitembytes, 0, formitembytes.Length); //memStream.Write(boundarybytes, 0, boundarybytes.Length); httpWebRequest.ContentLength = memStream.Length; var requestStream = httpWebRequest.GetRequestStream(); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); return(httpWebRequest.GetResponse()); }
/// <summary> /// Get audio stream. /// </summary> /// <param name="transcodingJobType">Transcoding job type.</param> /// <param name="streamingRequest">Streaming controller.Request dto.</param> /// <returns>A <see cref="Task"/> containing the resulting <see cref="ActionResult"/>.</returns> public async Task <ActionResult> GetAudioStream( TranscodingJobType transcodingJobType, StreamingRequestDto streamingRequest) { if (_httpContextAccessor.HttpContext == null) { throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext)); } bool isHeadRequest = _httpContextAccessor.HttpContext.Request.Method == System.Net.WebRequestMethods.Http.Head; // CTS lifecycle is managed internally. var cancellationTokenSource = new CancellationTokenSource(); using var state = await StreamingHelpers.GetStreamingState( streamingRequest, _httpContextAccessor.HttpContext.Request, _authContext, _mediaSourceManager, _userManager, _libraryManager, _serverConfigurationManager, _mediaEncoder, _encodingHelper, _dlnaManager, _deviceManager, _transcodingJobHelper, transcodingJobType, cancellationTokenSource.Token) .ConfigureAwait(false); if (streamingRequest.Static && state.DirectStreamProvider != null) { StreamingHelpers.AddDlnaHeaders(state, _httpContextAccessor.HttpContext.Response.Headers, true, streamingRequest.StartTimeTicks, _httpContextAccessor.HttpContext.Request, _dlnaManager); var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfo(streamingRequest.LiveStreamId); if (liveStreamInfo == null) { throw new FileNotFoundException(); } var liveStream = new ProgressiveFileStream(liveStreamInfo.GetStream()); // TODO (moved from MediaBrowser.Api): Don't hardcode contentType return(new FileStreamResult(liveStream, MimeTypes.GetMimeType("file.ts"))); } // Static remote stream if (streamingRequest.Static && state.InputProtocol == MediaProtocol.Http) { StreamingHelpers.AddDlnaHeaders(state, _httpContextAccessor.HttpContext.Response.Headers, true, streamingRequest.StartTimeTicks, _httpContextAccessor.HttpContext.Request, _dlnaManager); var httpClient = _httpClientFactory.CreateClient(NamedClient.Default); return(await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, isHeadRequest, httpClient, _httpContextAccessor.HttpContext).ConfigureAwait(false)); } if (streamingRequest.Static && state.InputProtocol != MediaProtocol.File) { return(new BadRequestObjectResult($"Input protocol {state.InputProtocol} cannot be streamed statically")); } var outputPath = state.OutputFilePath; var outputPathExists = File.Exists(outputPath); var transcodingJob = _transcodingJobHelper.GetTranscodingJob(outputPath, TranscodingJobType.Progressive); var isTranscodeCached = outputPathExists && transcodingJob != null; StreamingHelpers.AddDlnaHeaders(state, _httpContextAccessor.HttpContext.Response.Headers, streamingRequest.Static || isTranscodeCached, streamingRequest.StartTimeTicks, _httpContextAccessor.HttpContext.Request, _dlnaManager); // Static stream if (streamingRequest.Static) { var contentType = state.GetMimeType("." + state.OutputContainer, false) ?? state.GetMimeType(state.MediaPath); if (state.MediaSource.IsInfiniteStream) { var stream = new ProgressiveFileStream(state.MediaPath, null, _transcodingJobHelper); return(new FileStreamResult(stream, contentType)); } return(FileStreamResponseHelpers.GetStaticFileResult( state.MediaPath, contentType, isHeadRequest, _httpContextAccessor.HttpContext)); } // Need to start ffmpeg (because media can't be returned directly) var encodingOptions = _serverConfigurationManager.GetEncodingOptions(); var ffmpegCommandLineArguments = _encodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, outputPath); return(await FileStreamResponseHelpers.GetTranscodedFile( state, isHeadRequest, _httpContextAccessor.HttpContext, _transcodingJobHelper, ffmpegCommandLineArguments, transcodingJobType, cancellationTokenSource).ConfigureAwait(false)); }
public void ProcessRequest(IHttpRequest request, IHttpResponse response, string operationName) { response.EndHttpHandlerRequest(skipClose: true, afterBody: r => { var fileName = request.GetPhysicalPath(); var fi = new FileInfo(fileName); if (!fi.Exists) { if ((fi.Attributes & FileAttributes.Directory) != 0) { foreach (var defaultDoc in EndpointHost.Config.DefaultDocuments) { var defaultFileName = Path.Combine(fi.FullName, defaultDoc); if (!File.Exists(defaultFileName)) { continue; } r.Redirect(request.GetPathUrl() + '/' + defaultDoc); return; } } if (!fi.Exists) { var originalFileName = fileName; if (Env.IsMono) { //Create a case-insensitive file index of all host files if (allFiles == null) { allFiles = CreateFileIndex(request.ApplicationFilePath); } if (allDirs == null) { allDirs = CreateDirIndex(request.ApplicationFilePath); } if (allFiles.TryGetValue(fileName.ToLower(), out fileName)) { fi = new FileInfo(fileName); } } if (!fi.Exists) { var msg = "Static File '" + request.PathInfo + "' not found."; log.WarnFormat("{0} in path: {1}", msg, originalFileName); throw new HttpException(404, msg); } } } TimeSpan maxAge; if (r.ContentType != null && EndpointHost.Config.AddMaxAgeForStaticMimeTypes.TryGetValue(r.ContentType, out maxAge)) { r.AddHeader(HttpHeaders.CacheControl, "max-age=" + maxAge.TotalSeconds); } if (request.HasNotModifiedSince(fi.LastWriteTime)) { r.ContentType = MimeTypes.GetMimeType(fileName); r.StatusCode = 304; return; } try { r.AddHeaderLastModified(fi.LastWriteTime); r.ContentType = MimeTypes.GetMimeType(fileName); if (fileName.EqualsIgnoreCase(this.DefaultFilePath)) { if (fi.LastWriteTime > this.DefaultFileModified) { SetDefaultFile(this.DefaultFilePath); //reload } r.OutputStream.Write(this.DefaultFileContents, 0, this.DefaultFileContents.Length); r.Close(); return; } if (EndpointHost.Config.AllowPartialResponses) { r.AddHeader(HttpHeaders.AcceptRanges, "bytes"); } long contentLength = fi.Length; long rangeStart, rangeEnd; var rangeHeader = request.Headers[HttpHeaders.Range]; if (EndpointHost.Config.AllowPartialResponses && rangeHeader != null) { rangeHeader.ExtractHttpRanges(contentLength, out rangeStart, out rangeEnd); if (rangeEnd > contentLength - 1) { rangeEnd = contentLength - 1; } r.AddHttpRangeResponseHeaders(rangeStart: rangeStart, rangeEnd: rangeEnd, contentLength: contentLength); } else { rangeStart = 0; rangeEnd = contentLength - 1; r.SetContentLength(contentLength); //throws with ASP.NET webdev server non-IIS pipelined mode } var outputStream = r.OutputStream; using (var fs = fi.OpenRead()) { if (rangeStart != 0 || rangeEnd != fi.Length - 1) { fs.WritePartialTo(outputStream, rangeStart, rangeEnd); } else { fs.WriteTo(outputStream); outputStream.Flush(); } } } catch (System.Net.HttpListenerException ex) { if (ex.ErrorCode == 1229) { return; } //Error: 1229 is "An operation was attempted on a nonexistent network connection" //This exception occures when http stream is terminated by web browser because user //seek video forward and new http request will be sent by browser //with attribute in header "Range: bytes=newSeekPosition-" throw; } catch (Exception ex) { log.ErrorFormat("Static file {0} forbidden: {1}", request.PathInfo, ex.Message); throw new HttpException(403, "Forbidden."); } }); }
/// <summary> /// Internal implementation of upload attachment /// </summary> /// <param name="entityId"></param> /// <param name="entityName"></param> /// <param name="file"></param> /// <param name="documentType"></param> /// <param name="checkUser"></param> /// <returns></returns> private async Task <IActionResult> UploadAttachmentInternal(string entityId, string entityName, IFormFile file, string documentType, bool checkUser) { FileSystemItem result = null; if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(documentType)) { return(BadRequest()); } var hasAccess = true; if (checkUser) { ValidateSession(); hasAccess = await CanAccessEntity(entityName, entityId, null).ConfigureAwait(true); } if (!hasAccess) { return(new NotFoundResult()); } var ms = new MemoryStream(); file.OpenReadStream().CopyTo(ms); var data = ms.ToArray(); // Check for a bad file type. var mimeTypes = new MimeTypes(); var mimeType = mimeTypes.GetMimeType(data); // Add additional allowed mime types here if (mimeType == null || !(mimeType.Name.Equals("image/png") || mimeType.Name.Equals("image/jpeg") || mimeType.Name.Equals("application/pdf"))) { _logger.LogError($"ERROR in uploading file due to invalid mime type {mimeType?.Name}"); return(new NotFoundResult()); } else { // Sanitize file name var illegalInFileName = new Regex(@"[#%*<>?{}~¿""]"); var fileName = illegalInFileName.Replace(file.FileName, ""); illegalInFileName = new Regex(@"[&:/\\|]"); fileName = illegalInFileName.Replace(fileName, "-"); fileName = FileSystemItemExtensions.CombineNameDocumentType(fileName, documentType); var folderName = await _dynamicsClient.GetFolderName(entityName, entityId).ConfigureAwait(true); _dynamicsClient.CreateEntitySharePointDocumentLocation(entityName, entityId, folderName, folderName); // call the web service var uploadRequest = new UploadFileRequest { ContentType = file.ContentType, Data = ByteString.CopyFrom(data), EntityName = entityName, FileName = fileName, FolderName = folderName }; var uploadResult = _fileManagerClient.UploadFile(uploadRequest); var logFolderName = WordSanitizer.Sanitize(folderName); var logFileName = WordSanitizer.Sanitize(fileName); if (uploadResult.ResultStatus == ResultStatus.Success) { // Update modifiedon to current time UpdateEntityModifiedOnDate(entityName, entityId, true); _logger.LogInformation($"SUCCESS in uploading file {logFileName} to folder {logFolderName}"); } else { _logger.LogError($"ERROR in uploading file {logFileName} to folder {logFolderName}"); throw new Exception($"ERROR in uploading file {logFileName} to folder {logFolderName}"); } } return(new JsonResult(result)); }
public BCRModule() : base(Database.Instance.GlobalSettings.url_base + "/API") { // The user must be authenticated in order to use the BCR API. this.RequiresAuthentication(); Get["/"] = x => { return(Response.AsText("Authentication OK")); }; /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve a list of all (smart)lists. Get["/Lists"] = x => { try { //var user = (BCRUser)this.Context.CurrentUser; //Gui guid = user.GetHomeList(); //ComicListItem item = Program.Database.ComicLists.GetItems<ComicListItem>(false).FirstOrDefault((ComicListItem cli) => cli.Id == s); int depth = Request.Query.depth.HasValue ? int.Parse(Request.Query.depth) : -1; return(Response.AsOData(Program.Database.ComicLists.Select(c => c.ToComicList(depth)))); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve the contents of the specified list. Get["/Lists/{id}"] = x => { try { int depth = Request.Query.depth.HasValue ? int.Parse(Request.Query.depth) : -1; IEnumerable <ComicList> list = Program.Database.ComicLists.Where(c => c.Id == new Guid(x.id)).Select(c => c.ToComicList(depth)); if (list.Count() == 0) { return(Response.AsError(HttpStatusCode.NotFound, "List not found", Request)); } return(Response.AsOData(list)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // For OData compatibility, count should be $count, but I don't know how to parse the $ with Nancy.... Get["/Lists/{id}/Comics/count"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; int totalCount = 0; return(Response.AsText(Context.ApplyODataUriFilter(BCR.GetComicsForList(user, new Guid(x.id)), ref totalCount).Count().ToString())); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Return the comics of the specified list using OData to filter the comic properties and the list paging. Get["/Lists/{id}/Comics"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; var rawcomics = BCR.GetComicsForList(user, new Guid(x.id)); int totalCount = 0; var comics = Context.ApplyODataUriFilter(rawcomics, ref totalCount); var result = new { totalCount = totalCount, items = comics }; return(Response.AsJson(result, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Returns a list of all the comics as comic excerpts Get["/Comics"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; int totalCount = 0; var comics = Context.ApplyODataUriFilter(BCR.GetComics().Select(c => c.ToComic(user)), ref totalCount); var result = new { totalCount = totalCount, items = comics }; return(Response.AsJson(result, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Return the comicbook info as an OData filtered bag of properties. Get["/Comics/{id}"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; Comic comic = BCR.GetComic(user, new Guid(x.id)); if (comic == null) { return(Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request)); } return(Response.AsOData(new List <Comic> { comic })); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve the specified page as a jpg file with the specified dimensions. Get["/Comics/{id}/Pages/{page}"] = x => { try { int width = Request.Query.width.HasValue ? int.Parse(Request.Query.width) : -1; int height = Request.Query.height.HasValue ? int.Parse(Request.Query.height) : -1; int maxWidth = Request.Query.maxWidth.HasValue ? int.Parse(Request.Query.maxWidth) : -1; int maxHeight = Request.Query.maxHeight.HasValue ? int.Parse(Request.Query.maxHeight) : -1; return(BCR.GetPageImage(new Guid(x.id), int.Parse(x.page), width, height, Response)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve the original size (in pixels) of the requested page. Get["/Comics/{id}/Pages/{page}/size"] = x => { try { int width = 0; int height = 0; BCR.GetPageImageSize(new Guid(x.id), int.Parse(x.page), ref width, ref height); return(Response.AsJson(new { width = width, height = height }, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Get one property. Get["/Comics/{id}/{property}"] = x => { try { Guid comicId = new Guid(x.id); ComicBook book = BCR.GetComics().FirstOrDefault(comic => comic.Id == comicId); if (book == null) { return(Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request)); } PropertyInfo property = book.GetType().GetProperty(x.property); object value = property.GetValue(book, null); return(Response.AsJson(value)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Update properties of the specified comicbook. /* * Put["/Comics/{id}"] = x => { * try * { * // Get the ComicBook entry from the library, so we can change it. * ComicBook book = BCR.GetComicBook(new Guid(x.id)); * if (book == null) * { * return Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request); * } * * // Convert form values to temporary ComicBook object. * ComicBook info = this.Bind<ComicBook>(); * * IEnumerable<string> keys = Request.Form.GetDynamicMemberNames(); * * // This also triggers the update of the ComicRack application. * book.CopyDataFrom(info, keys); * * return HttpStatusCode.OK; * } * catch(Exception e) * { * return Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request); * } * }; */ /////////////////////////////////////////////////////////////////////////////////////////////// // Update properties of the specified comicbook for the current user Post["/Comics/{id}/Progress"] = x => { try { // Check if the comic exists. Guid comicId = new Guid(x.id); ComicBook book = BCR.GetComics().FirstOrDefault(comic => comic.Id == comicId); if (book == null) { return(Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request)); } BCRUser user = (BCRUser)this.Context.CurrentUser; user.UpdateComicProgress(book, int.Parse(this.Request.Form.CurrentPage)); //if using multiple users do we update the master file with a users progress? //book.SetValue("CurrentPage", int.Parse(this.Request.Form.CurrentPage)); return(HttpStatusCode.OK); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Used to mark comic UserLastPagRead to 0 Post["/Comics/{id}/Mark_Unread"] = x => { try { // Check if the comic exists. Guid comicId = new Guid(x.id); ComicBook book = BCR.GetComics().FirstOrDefault(comic => comic.Id == comicId); if (book == null) { return(Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request)); } BCRUser user = (BCRUser)this.Context.CurrentUser; user.UpDateLastReadPage(book, int.Parse(this.Request.Form.CurrentPage)); //if using multiple users do we update the master file with a users progress? //book.SetValue("CurrentPage", int.Parse(this.Request.Form.CurrentPage)); return(HttpStatusCode.OK); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Update one property /* * Put["/Comics/{id}/{property}"] = x => { * try * { * // Convert form values to temporary Comic object. * string info = this.Bind<string>(); * * * // Now get the ComicBook entry from the library, so we can change it. * ComicBook book = BCR.GetComicBook(x.id); * if (book == null) * { * return Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request); * } * * // Setting one of these values also triggers the update of the ComicRack application. * book.SetValue(x.property, info); * * * return HttpStatusCode.OK; * } * catch(Exception e) * { * return Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request); * } * }; */ /////////////////////////////////////////////////////////////////////////////////////////////// // Get the BCR settings. Get["/Settings"] = x => { try { var user = (BCRUser)this.Context.CurrentUser; return(Response.AsJson(user.GetSettings(), HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Update the BCR settings. Put["/Settings"] = x => { try { var user = (BCRUser)this.Context.CurrentUser; user.UpdateSettings(this.Bind <UserSettings>()); return(HttpStatusCode.OK); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Get a list of series Get["/Series"] = x => { try { var user = (BCRUser)this.Context.CurrentUser; int totalCount = 0; var series = Context.ApplyODataUriFilter(BCR.GetSeries(), ref totalCount); var result = new { totalCount = totalCount, items = series }; return(Response.AsJson(result, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; // Get a list of series added in the last 2 days Get["/Series/Recent/{days}"] = x => { try { var user = (BCRUser)this.Context.CurrentUser; int totalCount = 0; int days = x.days; var series = BCR.GetMostRecentlyAdded(user, days); var result = new { totalCount = totalCount, items = series }; return(Response.AsJson(result, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve a list of all comics in the specified list Get["/Series/{id}"] = x => { try { var user = (BCRUser)this.Context.CurrentUser; int totalCount = 0; var series = Context.ApplyODataUriFilter(BCR.GetComicsFromSeries(user, new Guid(x.id)), ref totalCount); var result = new { totalCount = totalCount, items = series }; return(Response.AsJson(result, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve the number of comics in the specified list Get["/Series/{id}/count"] = x => { try { var user = (BCRUser)this.Context.CurrentUser; int totalCount = 0; return(Response.AsText(Context.ApplyODataUriFilter(BCR.GetComicsFromSeries(user, new Guid(x.id)), ref totalCount).Count().ToString())); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Get["/Series/{id}/Volumes"] = x => { try { return(Response.AsOData(BCR.GetVolumesFromSeries(new Guid(x.id)), HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Get["/Series/{id}/Volumes/{volume}"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; int volume = int.Parse(x.volume); var comics = BCR.GetComicsFromSeriesVolume(user, new Guid(x.id), volume); return(Response.AsOData(comics, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Get a list of publishers Get["/Publishers"] = x => { try { return(Response.AsOData(BCR.GetPublishers(), HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; Get["/Publishers/{publisher}/Imprint/{imprint}/"] = x => { try { var user = (BCRUser)this.Context.CurrentUser; //s int totalCount = 0; var pub = x.publisher; var imprint = x.imprint; if (string.IsNullOrEmpty(imprint)) { imprint = ""; } var series = BCR.GetSeries(pub, imprint); var result = new { totalCount = 0, items = series }; return(Response.AsJson(result, HttpStatusCode.OK)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; /////////////////////////////////////////////////////////////////////////////////////////////// /* * Get["/Log"] = x => * { * try * { * string severity = Request.Query.sev.HasValue ? Request.Query.sev : ""; * string message = Request.Query.msg.HasValue ? Request.Query.msg : ""; * * // TODO: write log entry to a file. * * return Response.AsRedirect("/tablet/resources/images/empty_1x1.png", RedirectResponse.RedirectType.Permanent); * } * catch (Exception e) * { * return Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request); * } * }; * * /////////////////////////////////////////////////////////////////////////////////////////////// * // Get the list of watched folders. * Get["/WatchFolder"] = x => * { * try * { * //return Response.AsOData(BCR.GetPublishers(), HttpStatusCode.OK); * * var folders = Program.Database.WatchFolders as cYo.Projects.ComicRack.Engine.Database.WatchFolderCollection; * * List<string> books = BCRExtensions.GetFolderBookList2(folders.Folders.First(), true); * return Response.AsJson(books, HttpStatusCode.OK); * * //return Response.AsRedirect("/tablet/resources/images/empty_1x1.png", RedirectResponse.RedirectType.Permanent); * } * catch (Exception e) * { * return Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request); * } * }; * * /////////////////////////////////////////////////////////////////////////////////////////////// * // Get list of all files in the folder * Get["/WatchFolder/{folder}"] = x => * { * try * { * return Response.AsRedirect("/tablet/resources/images/empty_1x1.png", RedirectResponse.RedirectType.Permanent); * * } * catch (Exception e) * { * return Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request); * } * }; * */ /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve a Comic File for download Get["/Comics/{id}/Sync/File"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; Comic comic = BCR.GetComic(user, new Guid(x.id)); if (comic == null) { return(Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request)); } var zipPath = comic.FilePath; var file = new FileStream(zipPath, FileMode.Open); string fileName = Path.GetFileName(zipPath); var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName)); return(response.AsAttachment(fileName)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; Get["/Comics/{id}/Sync/Webp2"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; Comic comic = BCR.GetComic(user, new Guid(x.id)); if (comic == null) { return(Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request)); } return(BCR.GetSyncWebp(comic, new Guid(x.id), Response)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; Get["/Comics/{id}/Sync/Webp"] = x => { try { BCRUser user = (BCRUser)this.Context.CurrentUser; Comic comic = BCR.GetComic(user, new Guid(x.id)); if (comic == null) { return(Response.AsError(HttpStatusCode.NotFound, "Comic not found", Request)); } return(BCR.GetSyncWebpStream(comic, new Guid(x.id), Response)); } catch (Exception e) { return(Response.AsError(HttpStatusCode.InternalServerError, e.ToString(), Request)); } }; }
public void TestGetMimeTypeNullFileName() { Assert.Throws <ArgumentNullException> (() => MimeTypes.GetMimeType(null)); }
/// <summary> /// Gets the specified request. /// </summary> /// <param name="request">The request.</param> /// <returns>System.Object.</returns> public Task <object> Get(GetDashboardConfigurationPage request) { var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase)); return(ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml("dummy.html", page.GetHtmlStream(), null, _appHost.ApplicationVersion.ToString(), null, false))); }
public void TestGetMimeTypeNoFileExtension() { Assert.AreEqual("application/octet-stream", MimeTypes.GetMimeType("filename")); }
public object Get(GetRemoteSubtitles request) { var result = _subtitleManager.GetRemoteSubtitles(request.Id, CancellationToken.None).Result; return(ResultFactory.GetResult(result.Stream, MimeTypes.GetMimeType("file." + result.Format))); }
public void TestGetMimeTypeFileNameDot() { Assert.AreEqual("application/octet-stream", MimeTypes.GetMimeType("filename.")); }
/// <summary> /// Initializes a new instance of the <see cref="GenericFileResponse"/> for the file specified /// by the <paramref name="filePath"/> parameter. /// </summary> /// <param name="filePath">The name of the file, including path relative to the root of the application, that should be returned.</param> /// <remarks>The <see cref="MimeTypes.GetMimeType"/> method will be used to determine the mimetype of the file and will be used as the content-type of the response. If no match if found the content-type will be set to application/octet-stream.</remarks> /// <param name="context">Current context</param> public GenericFileResponse(string filePath, NancyContext context) : this(filePath, MimeTypes.GetMimeType(filePath), context) { }
public void TestGetMimeTypeFileExtensionTxt() { Assert.AreEqual("text/plain", MimeTypes.GetMimeType("filename.txt")); }
/// <summary> /// Handle a <see cref="StreamReadModel" /> and generates job for the queue /// if needed. /// </summary> /// <param name="streamElement"></param> /// <param name="tenantId"></param> /// <param name="forceReSchedule"></param> public void Handle( StreamReadModel streamElement, TenantId tenantId, Boolean forceReSchedule = false) { if (_info.ShouldCreateJob(streamElement)) { if (!forceReSchedule) { //look for already existing job with the same blobid, there is no need to re-queue again //because if a job with the same blobid was already fired for this queue there is no need //to re-issue var existing = _collection.Find( Builders <QueuedJob> .Filter.And( Builders <QueuedJob> .Filter.Eq(j => j.BlobId, streamElement.FormatInfo.BlobId), Builders <QueuedJob> .Filter.Eq(j => j.TenantId, tenantId) ) ).Count() > 0; if (existing) { return; } } if (Logger.IsInfoEnabled) { Logger.Info($"Queue {_info.Name} CREATE JOB to process {streamElement.Describe()}"); } QueuedJob job = new QueuedJob(); job.Id = new QueuedJobId(Guid.NewGuid().ToString()); job.SchedulingTimestamp = DateTime.Now; job.StreamId = streamElement.Id; job.TenantId = tenantId; job.DocumentDescriptorId = streamElement.DocumentDescriptorId; job.BlobId = streamElement.FormatInfo.BlobId; job.Handle = new DocumentHandle(streamElement.Handle); job.Parameters = new Dictionary <string, string>(); job.Parameters.Add(JobKeys.FileExtension, streamElement.Filename.Extension); job.Parameters.Add(JobKeys.Format, streamElement.FormatInfo.DocumentFormat); job.Parameters.Add(JobKeys.FileName, streamElement.Filename); job.Parameters.Add(JobKeys.TenantId, tenantId); job.Parameters.Add(JobKeys.MimeType, MimeTypes.GetMimeType(streamElement.Filename)); job.Parameters.Add(JobKeys.PipelineId, streamElement.FormatInfo?.PipelineId?.ToString()); if (forceReSchedule) { job.Parameters.Add(JobKeys.Force, "true"); } job.HandleCustomData = streamElement.DocumentCustomData; if (_info.Parameters != null) { foreach (var parameter in _info.Parameters) { job.Parameters.Add(parameter.Key, parameter.Value); } } _collection.InsertOne(job); } else { if (Logger.IsDebugEnabled) { Logger.Debug($"Queue {_info.Name} do not need to process {streamElement.Describe()}"); } } }
public void TestGetMimeTypeFileExtensionCsv() { Assert.AreEqual("text/csv", MimeTypes.GetMimeType("filename.csv")); }
private string GetMimeType(string filename) { var mt = new MimeTypes(Server.MapPath("~/mime-types.xml")); MimeType mime = mt.GetMimeType(filename.ToLowerInvariant()); if (mime != null) return mime.Name; return "application/octet-stream"; }
public async Task <ActionResult> GetSubtitlePlaylist( [FromRoute, Required] Guid itemId, [FromRoute, Required] int index, [FromRoute, Required] string mediaSourceId, [FromQuery, Required] int segmentLength) { var item = (Video)_libraryManager.GetItemById(itemId); var mediaSource = await _mediaSourceManager.GetMediaSource(item, mediaSourceId, null, false, CancellationToken.None).ConfigureAwait(false); var runtime = mediaSource.RunTimeTicks ?? -1; if (runtime <= 0) { throw new ArgumentException("HLS Subtitles are not supported for this media."); } var segmentLengthTicks = TimeSpan.FromSeconds(segmentLength).Ticks; if (segmentLengthTicks <= 0) { throw new ArgumentException("segmentLength was not given, or it was given incorrectly. (It should be bigger than 0)"); } var builder = new StringBuilder(); builder.AppendLine("#EXTM3U") .Append("#EXT-X-TARGETDURATION:") .Append(segmentLength) .AppendLine() .AppendLine("#EXT-X-VERSION:3") .AppendLine("#EXT-X-MEDIA-SEQUENCE:0") .AppendLine("#EXT-X-PLAYLIST-TYPE:VOD"); long positionTicks = 0; var accessToken = _authContext.GetAuthorizationInfo(Request).Token; while (positionTicks < runtime) { var remaining = runtime - positionTicks; var lengthTicks = Math.Min(remaining, segmentLengthTicks); builder.Append("#EXTINF:") .Append(TimeSpan.FromTicks(lengthTicks).TotalSeconds) .Append(',') .AppendLine(); var endPositionTicks = Math.Min(runtime, positionTicks + segmentLengthTicks); var url = string.Format( CultureInfo.CurrentCulture, "stream.vtt?CopyTimestamps=true&AddVttTimeMap=true&StartPositionTicks={0}&EndPositionTicks={1}&api_key={2}", positionTicks.ToString(CultureInfo.InvariantCulture), endPositionTicks.ToString(CultureInfo.InvariantCulture), accessToken); builder.AppendLine(url); positionTicks += segmentLengthTicks; } builder.AppendLine("#EXT-X-ENDLIST"); return(File(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"))); }