private async Task <object> DownloadArchiveAsync(dynamic args, bool includeUnreleased) { if (includeUnreleased) { this.RequiresAuthentication(); } if (!ParseModType(args, out ModType modType, out Response errorResponse)) { return(await errorResponse); } string versionQuery = args.version; ModVersion version = Data.FindVersion(modType, versionQuery, includeUnreleased); if (version == null) { return(await Response.Error($"The version '{versionQuery}' could not be found.", HttpStatusCode.NotFound)); } var fileStream = new FileStream(Path.Combine(version.DirectoryPath, "archive.zip"), FileMode.Open, FileAccess.Read); var response = new StreamResponse(() => fileStream, MimeTypes.GetMimeType("archive.zip")); return(await response.AsAttachment($"goimp-{modType.ToString().ToLowerInvariant()}-{version.Version}.zip")); }
public Response ProcessRequest(NancyContext context, string path) { path = string.Concat("~", path.Substring(PathPrefix.Length)); using (bundles.GetReadLock()) { Bundle bundle; IAsset asset; if (!bundles.TryGetAssetByPath(path, out asset, out bundle)) { logger.Info("ProcessRequest : Asset '{0}' not found", path); return(new HtmlResponse(HttpStatusCode.NotFound)); } var actualETag = "\"" + asset.Hash.ToHexString() + "\""; var givenETag = context.Request.Headers["If-None-Match"]; if (givenETag.Equals(actualETag)) { logger.Info("ProcessRequest : Asset '{0}' not modified", path); var notModified = new HtmlResponse(HttpStatusCode.NotModified); notModified.ContentType = bundle.ContentType; return(notModified); } logger.Info("ProcessRequest : Asset '{0}' returned", path); var response = new StreamResponse(asset.OpenStream, bundle.ContentType); response.WithHeader("ETag", actualETag); return(response); } }
private Response HandleDownloadRequest(dynamic parameters) { string vsixName = HttpUtility.UrlDecode(parameters.vsix); string vsixId = parameters.id; string vsixFilePath = Path.Combine(Environment.CurrentDirectory, _configuration.VsixStorageDirectory, vsixName); // Count the download bool refreshFile = FileCounter.SetDownloadCount(vsixId, _configuration); // Serve the requested VSIX file back to the caller Response fileResponse = null; var vsixFile = new FileStream(vsixFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); using (var response = new StreamResponse(() => vsixFile, "application/octet-stream")) { fileResponse = response.AsAttachment(vsixName); } // Re-process the file if (refreshFile && File.Exists(vsixFilePath)) { // Schedule the ATOM feed to be re-created by touching the VSIX file in question File.SetLastWriteTime(vsixFilePath, DateTime.Now); } return(fileResponse); }
public override async Task Do( IAsyncStreamReader <StreamRequest> requestStream, IServerStreamWriter <StreamResponse> responseStream, ServerCallContext context) { if (!await requestStream.MoveNext()) { return; } _subscribers.TryAdd(requestStream.Current.ClientId, responseStream); do { if (requestStream.Current == null) { continue; } _logger.LogInformation($"X: {requestStream.Current.X}, Y: {requestStream.Current.Y}, ClientId: {requestStream.Current.ClientId}"); var response = new StreamResponse { X = requestStream.Current.X, Y = requestStream.Current.Y }; foreach (var subscriber in _subscribers) { await subscriber.Value.WriteAsync(response); } } while (await requestStream.MoveNext()); }
public void Should_return_content_of_stream_from_current_location_of_stream() { // Given var streamContent = new byte[] { 1, 2, 3, 4, 5 }; var inputStream = new MemoryStream(streamContent) { Position = 2 }; var response = new StreamResponse(() => inputStream, "test"); var outputStream = new MemoryStream(); var expectedContent = new byte[] { 3, 4, 5 }; // When response.Contents.Invoke(outputStream); // Then outputStream.ToArray().ShouldEqualSequence(expectedContent); }
public override Response ProcessRequest(NancyContext context) { if (!context.Request.Url.Path.StartsWith(HandlerRoot, StringComparison.InvariantCultureIgnoreCase)) { return(null); } var path = context.Request.Url.Path.Remove(0, HandlerRoot.Length + 1); var match = Regex.Match(path, @"^(?<filename>.*)_[a-z0-9]+_(?<extension>[a-z]+)$", RegexOptions.IgnoreCase); if (match.Success == false) { //if (Logger != null) Logger.Error("RawFileRouteHandler.ProcessRequest : Invalid file path in URL '{0}'", path); return(null); } var extension = match.Groups["extension"].Value; var filePath = Path.Combine(applicationRoot, string.Concat(match.Groups["filename"].Value, ".", extension).Replace('/', '\\')); if (!File.Exists(filePath)) { //if (Logger != null) Logger.Error("RawFileRouteHandler.ProcessRequest : Raw file does not exist '{0}'", filePath); return(null); } var response = new StreamResponse(() => File.OpenRead(filePath), MimeTypes.GetMimeType(filePath)); //if (Logger != null) Logger.Trace("RawFileRouteHandler.ProcessRequest : Returned response for '{0}'", context.Request.Url.Path); return(response); }
public void SetUp() { // Create a response object and get the binary representation of it var streamMessage = new StreamMessage (); var response1 = new Response (); response1.Time = 42; response1.Error = "Foo"; var streamResponse1 = new StreamResponse (); streamResponse1.Id = 1263; var response2 = new Response (); response2.Time = 123; response2.Error = "Bar"; var streamResponse2 = new StreamResponse (); streamResponse2.Id = 3443; streamResponse2.Response = response2; streamMessage.Responses.Add (streamResponse1); streamMessage.Responses.Add (streamResponse2); expectedMessage = streamMessage; using (var stream = new MemoryStream ()) { expectedMessage.WriteDelimitedTo (stream); messageBytes = stream.ToArray (); } }
public Response ProcessRequest(NancyContext context, string path) { var pattern = new Regex(@"~?/?[a-z]{5,}/[a-f0-9]{10,}/", RegexOptions.IgnoreCase); path = pattern.Replace(path, "/"); using (bundles.GetReadLock()) { var bundle = bundles.FindBundlesContainingPath(path).OfType <TBundle>().FirstOrDefault(); if (bundle == null) { logger.Info("ProcessRequest : Bundle '{0}' not found", path); return(new HtmlResponse(HttpStatusCode.NotFound)); } var actualETag = "\"" + bundle.Hash.ToHexString() + "\""; var givenETag = context.Request.Headers["If-None-Match"]; if (givenETag.Equals(actualETag)) { logger.Info("ProcessRequest : Bundle '{0}' not modified", path); var notModified = new HtmlResponse(HttpStatusCode.NotModified); notModified.ContentType = bundle.ContentType; return(notModified); } logger.Info("ProcessRequest : Bundle '{0}' returned", path); var response = new StreamResponse(bundle.OpenStream, bundle.ContentType); response.WithHeader("ETag", actualETag); return(response); } }
public async Task TestStream() { // Check that the user has an Xbox Music Pass subscription UserProfileResponse userProfileResponse = await AuthenticatedClient.GetUserProfileAsync(Namespace.music).Log(); // Beware: HasSubscription is bool?. You want != true instead of == false if (userProfileResponse.HasSubscription != true) { Assert.Inconclusive("The user doesn't have an Xbox Music Pass subscription. Cannot stream from catalog."); } // Get popular tracks in the user's country ContentResponse browseResults = await AuthenticatedClient.BrowseAsync(Namespace.music, ContentSource.Catalog, ItemType.Tracks).Log(); Assert.IsNotNull(browseResults, "The browse response should not be null"); AssertPaginatedListIsValid(browseResults.Tracks, 25, 100); // Stream the first streamable track Track track = browseResults.Tracks.Items.First(t => t.Rights.Contains("Stream")); StreamResponse streamResponse = await AuthenticatedClient.StreamAsync(track.Id, ClientInstanceId).Log(); Assert.IsNotNull(streamResponse, "The stream URL response should not be null"); Assert.IsNotNull(streamResponse.Url, "The stream URL should not be null"); Assert.IsNotNull(streamResponse.ContentType, "The stream content type should not be null"); Assert.IsNotNull(streamResponse.ExpiresOn, "The stream expiry date should not be null"); }
public void SetUp() { // Create a response object and get the binary representation of it var streamMessage = new StreamMessage(); var response1 = new Response(); response1.Time = 42; response1.Error = "Foo"; var streamResponse1 = new StreamResponse(); streamResponse1.Id = 1263; var response2 = new Response(); response2.Time = 123; response2.Error = "Bar"; var streamResponse2 = new StreamResponse(); streamResponse2.Id = 3443; streamResponse2.Response = response2; streamMessage.Responses.Add(streamResponse1); streamMessage.Responses.Add(streamResponse2); expectedMessage = streamMessage; using (var stream = new MemoryStream()) { expectedMessage.WriteDelimitedTo(stream); messageBytes = stream.ToArray(); } }
/// <summary> /// Definition of routing urls /// </summary> public MainModule() { Get("/", x => { return(View["index.html", Program.ViewModel.Items]); }); //View detail Get("/views/{uri*}", x => { String id = x.uri.ToString().Replace(".html", ""); FolderComicsInfo info = Program.ViewModel.GetFolderComicInfoById(id); return(View["detail.html", info]); }); Get("/Search/{term*}", x => { String searchby = x.term.ToString().Replace(".html", ""); var result = Program.ViewModel.Items.Where(f => f.FolderName.Contains(searchby)).ToList(); return(View["index.html", result]); }); //Download File Get("/comics/{uri*}", p => { dynamic cbrPath = p.uri.ToString(); bool e = System.IO.File.Exists(cbrPath); var file = new FileStream(cbrPath, FileMode.Open); String fileName = System.IO.Path.GetFileName(cbrPath); StreamResponse response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName)); return(response.AsAttachment(fileName)); }); }
public override Response ProcessRequest(NancyContext context) { if (!context.Request.Url.Path.StartsWith(HandlerRoot, StringComparison.InvariantCultureIgnoreCase)) { return(null); } var path = Regex.Match(string.Concat("~", context.Request.Url.Path.Remove(0, HandlerRoot.Length)), @"^[^\?]*").Value; var bundles = BundleContainer.FindBundlesContainingPath(path).ToList(); if (bundles == null) { //if (Logger != null) // Logger.Error("AssetRouteHandler.ProcessRequest : Bundle not found for path '{0}'", context.Request.Url.Path); return(null); } IAsset asset; Bundle bundle; if (!bundles.TryGetAssetByPath(path, out asset, out bundle)) { //if (Logger != null) // Logger.Error("AssetRouteHandler.ProcessRequest : Asset not found for path '{0}'", context.Request.Url.Path); return(null); } var response = new StreamResponse(asset.OpenStream, bundle.ContentType); //if (Logger != null) // Logger.Trace("AssetRouteHandler.ProcessRequest : Returned response for '{0}'", context.Request.Url.Path); return(response); }
/// <summary> /// /// </summary> /// <param name="path"></param> /// <param name="queryParams"></param> /// <param name="methodName"></param> /// <returns></returns> protected StreamResponse CallGetApi(string path, Dictionary <string, string> queryParams, string methodName = "<unknown>") { HttpResponseMessage resp = ApiClient.CallGet(path, queryParams); GenerateApiException(resp, methodName); var fileName = ""; if (resp.Content.Headers.ContentDisposition != null && resp.Content.Headers.ContentDisposition.FileName != null) { fileName = resp.Content.Headers.ContentDisposition.FileName; } Stream outStream = new MemoryStream(); Task task = resp.Content.ReadAsStreamAsync() .ContinueWith((tsk) => { var contentStream = tsk.Result; contentStream.CopyTo(outStream); outStream.Flush(); outStream.Position = 0; }); task.Wait(); StreamResponse response = new StreamResponse() { Status = resp.StatusCode.ToString(), Code = (int)resp.StatusCode, ReasonPhrase = resp.ReasonPhrase }; response.ContentStream = outStream; response.FileName = fileName; return(response); }
private async Task <StreamResponse> UrlPostToStream <T>(string request, T data = null, string referer = null, ERequestOptions requestOptions = ERequestOptions.None, byte maxTries = MaxTries) where T : class { if (string.IsNullOrEmpty(request) || (maxTries == 0)) { return(null); } StreamResponse result = null; for (byte i = 0; i < maxTries; i++) { HttpResponseMessage response = await InternalPost(request, data, referer, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); if (response?.StatusCode.IsClientErrorCode() == true) { if (requestOptions.HasFlag(ERequestOptions.ReturnClientErrors)) { result = new StreamResponse(response); } break; } if (response?.Content == null) { continue; } return(new StreamResponse(response, await response.Content.ReadAsStreamAsync().ConfigureAwait(false))); } return(result); }
public async Task <StreamResponse> HandleAsync(MessageWriter messageWriter, CancellationToken cancellationToken) { if (messageWriter == null) { throw new ArgumentNullException("messageWriter"); } if (cancellationToken == null) { throw new ArgumentNullException("cancellationToken"); } this.messageWriter = messageWriter; log.Trace("HandleAsync: '{0}' JobId: '{1}''", request.Handle, request.JobId); StreamResponse streamResponse = null; Job job = GetJobById(request.JobId, ref streamResponse); // if job is null, streamResponse is set to error if (job != null) { if (job.HasStatus) { var awaitables = new List <Task>(); foreach (IJobStatus status in job.RetrieveStatus()) { awaitables.Add(ListenStatusAsync(status)); } await Task.WhenAll(awaitables); } try { if (job.IsCompleted) { if (job.Result == null) { streamResponse = ToStreamResponse(GetResponseData(true, "Error! Job with ID '{0}' is completed but no result is available!\n", request.JobId)); } else { streamResponse = ToStreamResponse(job.Result); } } else { job.AttachListener(this); IJobResult result = await job.ListenAsync(); streamResponse = StreamResponse.Create(result.ExitCode); } } finally { jobManager.RemoveJob(request.JobId); } } return(streamResponse); }
protected override void ConfigureConventions(NancyConventions nancyConventions) { string[] splitters = new string[] { "static/" }; base.ConfigureConventions(nancyConventions); Console.WriteLine("Initializing Bootstrapper:" + Application.STATIC_DIR); Conventions.StaticContentsConventions.Add( (context, rootPath) => { var Request = context.Request; string[] splitted = Request.Path.Split(splitters, System.StringSplitOptions.RemoveEmptyEntries); if (splitted.Length != 2) { return(null); } string[] restPath = splitted[1].Split('/'); string filePath = Path.Combine(restPath); filePath = Path.Combine(Application.STATIC_DIR, filePath); Console.WriteLine("READ:" + filePath); var file = new FileStream(filePath, FileMode.Open); string fileName = restPath[restPath.Length - 1]; //set a filename var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName)); return(response); }); }
public FlagModule() { Get("/", args => "Hello from Nancy running on CoreCLR"); Get("/flags/{id}", args => { // return "flag_" + args["id"]; var id = this.Request.Query["id"]; byte[] dataPNG = flagPNG(id); //var response = new GenericFileResponse(); MemoryStream ms = new MemoryStream(dataPNG); var response = new StreamResponse(() => ms, "image/png"); // using (MemoryStream ms = new MemoryStream(dataPNG)) // { // var response = new StreamResponse(() => ms, "image/png"); // } return(response.AsAttachment("flag.png")); }); Get("/flag/get", args => { var id = this.Request.Query["id"]; return(flagPNG(id)); }); }
public TServe(IManifest manifest) { Get["/"] = parameters => JsonConvert.SerializeObject(manifest.GetEntries()); /* * * https://stackoverflow.com/questions/20121730/file-downloads-in-a-self-host-nancy-application * */ Get["/{id}/{chunkNum}"] = parameters => { var manifestEntry = manifest.GetEntries().Single(e => e.Id == parameters.id); var folderPath = Manifest.MakeChunkFolderPath(manifestEntry); //TODO: This tightly couples this class to the Manifest class instead of the interface var filePath = $"{folderPath}\\{parameters.chunkNum}.chnk"; if (File.Exists(filePath)) { var file = new FileStream(filePath, FileMode.Open); string fileName = manifestEntry.Id + "-" + parameters.chunkNum; var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName)); return(response.AsAttachment(fileName)); } else { return(HttpStatusCode.NoContent); } }; }
public static Schema.KRPC.StreamResponse ToProtobufMessage(this StreamResponse streamResponse) { var result = new Schema.KRPC.StreamResponse(); result.Id = streamResponse.Id; result.Response = streamResponse.Response.ToProtobufMessage(); return(result); }
internal XmlDocumentResponse(StreamResponse streamResponse, XmlDocument content) : this(streamResponse) { if (streamResponse == null) { throw new ArgumentNullException(nameof(streamResponse)); } Content = content; }
private HtmlDocumentResponse(StreamResponse streamResponse, IDocument document) : this(streamResponse) { if ((streamResponse == null) || (document == null)) { throw new ArgumentNullException(nameof(streamResponse) + " || " + nameof(document)); } Content = document; }
public static Task <IHttpResponse> DownloadAsync( StreamResponse onFound, NotFoundResponse onNotFound) { return(SpaHandler.LoadSpaFile( (blobStream) => onFound(blobStream), () => onNotFound())); }
public StreamRequest(Request request) { Identifier = nextIdentifier; nextIdentifier++; Procedure = KRPC.Service.Services.Instance.GetProcedureSignature(request); Arguments = KRPC.Service.Services.Instance.DecodeArguments(Procedure, request); Response = new StreamResponse(); Response.Id = Identifier; }
private Response SendAttachmentResponse(string fileName) { string filePath = Path.Combine(Directory.GetCurrentDirectory(), $@"content\download\{fileName}"); var file = new FileStream(filePath, FileMode.Open); var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName)); return(response.AsAttachment(fileName)); }
/// <summary> /// Dummy implementation that does nothing. /// </summary> /// <returns>Response message.</returns> public override StreamResponse ConstructResponse() { var mr = new StreamResponse(); Log.InfoFormat("HSM delay {0} set and ignored", _delay); mr.Append(ErrorCodes.ER_00_NO_ERROR); return(mr); }
public StreamRequest(Request request) { Identifier = NextIdentifier; var services = Services.Instance; Procedure = services.GetProcedureSignature(request.Service, request.Procedure); Arguments = services.GetArguments(Procedure, request.Arguments); Response = new StreamResponse(Identifier); }
private static Response ResponseFromBundle(AssetBundle assetBundle, string contentType) { var stream = new MemoryStream(assetBundle.Bytes); var response = new StreamResponse(() => stream, contentType); response.Headers["ETag"] = assetBundle.ETag; response.Headers["Cache-Control"] = "no-cache"; return(response); }
public StreamRequest(Request request) { Identifier = nextIdentifier; nextIdentifier++; Procedure = KRPC.Service.Services.Instance.GetProcedureSignature (request); Arguments = KRPC.Service.Services.Instance.DecodeArguments (Procedure, request); Response = new StreamResponse (); Response.Id = Identifier; }
public TestingEndpoints() : base("/") { Get("/WABBAJACK_TEST_FILE.txt", _ => "Cheese for Everyone!"); Get("/WABBAJACK_TEST_FILE.zip", _ => { var response = new StreamResponse(() => new MemoryStream(Encoding.UTF8.GetBytes("Cheese for Everyone!")), "application/zip"); return(response.AsAttachment("WABBAJACK_TEST_FILE.zip")); }); }
/// <summary> /// Process request. /// </summary> /// <returns>Response message.</returns> public override StreamResponse ConstructResponse() { var mr = new StreamResponse(); KeyTypeCode ktc = null; if (!ValidateKeyTypeCode(_keyTypeCode, mr, ref ktc)) { return(mr); } var lmkKs = KeyScheme.Unspecified; if (!ValidateKeySchemeCode(_lmkScheme, mr, ref lmkKs)) { return(mr); } var clearComps = new HexKeyThales[_iNbrComponents]; var clearKey = string.Empty; for (var i = 1; i <= _iNbrComponents; i++) { clearComps[i - 1] = new HexKeyThales(ktc, false, _comps[i - 1]); if (!clearComps[i - 1].ClearKey.IsParityOk(Parity.Odd)) { mr.Append(ErrorCodes.ER_10_SOURCE_KEY_PARITY_ERROR); return(mr); } clearKey = !string.IsNullOrEmpty(clearKey) ? clearKey.XorHex(clearComps[i - 1].ClearKey) : clearComps[i - 1].ClearKey; } clearKey = clearKey.MakeParity(Parity.Odd); var cryptKey = new HexKeyThales(ktc, true, clearKey); for (var i = 1; i <= _iNbrComponents; i++) { Log.InfoFormat("Component {0} (clear): {1}", i, clearComps[i - 1].ClearKey); } Log.InfoFormat("Key (clear): {0}", clearKey); Log.InfoFormat("Check value: {0}", cryptKey.CheckValue); mr.Append(ErrorCodes.ER_00_NO_ERROR); if (lmkKs == KeyScheme.DoubleLengthKeyVariant || lmkKs == KeyScheme.TripleLengthKeyVariant) { mr.Append(cryptKey.KeyVariant); } else { mr.Append(cryptKey.KeyAnsi); } mr.Append(cryptKey.CheckValue.Substring(0, 6)); return(mr); }
public static Response getPhoto() { var file = new FileStream( @"views\img.jpg", FileMode.Open); string fileName = "img.jpg"; var response = new StreamResponse(() => file, MimeTypes.GetMimeType(fileName)); return(response.AsAttachment(fileName));; }
/// <summary> /// If job can't be found, streamResponse is set to error /// </summary> private Job GetJobById(uint jobId, ref StreamResponse streamResponse) { Job job = jobManager.GetJob(jobId); if (job == null) { streamResponse = ToStreamResponse(GetResponseData(true, Resources.JobRequestHandler_NoSuchJob_Message)); } return(job); }
/// <summary> /// If job can't be found, streamResponse is set to error /// </summary> private Job GetJobById(uint jobId, ref StreamResponse streamResponse) { Job job = jobManager.GetJob(jobId); if (job == null) { streamResponse = ToStreamResponse(GetResponseData(true, Resources.JobRequestHandler_NoSuchJob_Message)); } return job; }
public static int decodeStreamResponse(byte[] buffer, int offset, int length, StreamResponse r) { if (length < STREAM_RESPONSE_MESSAGE_LENGTH) { return 0; } if ((buffer[offset + 0] == PACKET_START_CHAR) && (buffer[offset + 1] == MSG_ID_STREAM_RESPONSE)) { if (!verifyChecksum(buffer, offset, STREAM_RESPONSE_CHECKSUM_INDEX)) { return 0; } r.stream_type = buffer[offset + 2]; r.gyro_fsr_dps = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_GYRO_FULL_SCALE_DPS_RANGE); r.accel_fsr_g = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_ACCEL_FULL_SCALE_G_RANGE); r.update_rate_hz = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_UPDATE_RATE_HZ); r.yaw_offset_degrees = decodeProtocolFloat(buffer, offset + STREAM_RESPONSE_YAW_OFFSET_DEGREES); r.q1_offset = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_QUAT1_OFFSET); r.q2_offset = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_QUAT2_OFFSET); r.q3_offset = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_QUAT3_OFFSET); r.q4_offset = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_QUAT4_OFFSET); r.flags = decodeProtocolUint16(buffer, offset + STREAM_RESPONSE_FLAGS); return STREAM_RESPONSE_MESSAGE_LENGTH; } return 0; }