public override string GetStreamURL() { // wait a few seconds till stream is ready Thread.Sleep(2500); return(String.Format(address, WCFUtil.GetCurrentHostname())); }
public override Stream ProvideCustomActionFile(string action, string param) { if (action == "playlist") { WCFUtil.SetContentType("application/vnd.apple.mpegurl"); string playlistPath = Path.Combine(TemporaryDirectory, "index.m3u8"); if (!File.Exists(playlistPath)) { Log.Warn("HTTPLiveStreamer: Client requested index.m3u8 that doesn't exist for identifier '{0}'", Identifier); return(Stream.Null); } // FFMpeg outputs the local segment paths in the playlist, replace with url string playlist = ReplacePathsWithURLs(playlistPath); if (playlist == string.Empty) { // The playlist file is empty until the first segment has finished being encoded, // wait for next segment to begin and retry. string segmentPath = Path.Combine(TemporaryDirectory, "000001.ts"); while (!File.Exists(segmentPath)) { System.Threading.Thread.Sleep(100); } playlist = ReplacePathsWithURLs(playlistPath); } return(new MemoryStream(Encoding.UTF8.GetBytes(playlist))); } return(base.ProvideCustomActionFile(action, param)); }
public bool InitStream(string identifier, string clientDescription, MediaSource source, int timeout) { if (!source.Exists) { Log.Warn("Tried to start stream for non-existing file {0}", source.GetDebugName()); return(false); } ActiveStream stream = new ActiveStream(); stream.Identifier = identifier; stream.ClientDescription = clientDescription; stream.StartTime = DateTime.Now; stream.Timeout = timeout; stream.LastActivity = DateTime.Now; stream.UseActivityForTimeout = false; stream.Context = new StreamContext(); stream.Context.Source = source; stream.Context.IsTv = source.MediaType == WebMediaType.TV; // Some clients such as WebMP proxy the streams before relying it to the client. We should give these clients the option to // forward the real IP address, so that we can show that one in the configurator too. However, to avoid abuse, we should show // the real IP of the client too, so make up some nice text string. string realIp = WCFUtil.GetHeaderValue("forwardedFor", "X-Forwarded-For"); stream.ClientIP = realIp == null?WCFUtil.GetClientIPAddress() : String.Format("{0} (via {1})", realIp, WCFUtil.GetClientIPAddress()); Streams[identifier] = stream; return(true); }
private bool IsClientAuthorized() { return(_authorizedHosts.Contains(WCFUtil.GetClientIPAddress()) || NetworkInformation.IsLocalAddress(WCFUtil.GetClientIPAddress()) || !Configuration.Authentication.Enabled || Configuration.Authentication.UnauthorizedStreams); }
public void BeforeSendReply(ref Message reply, object correlationState) { if (reply.Version != MessageVersion.None && reply.Headers.FindHeader("responseCode", WCFUtil.HEADER_NAMESPACE) == -1) { reply.Headers.Add(WCFUtil.CreateCustomSOAPHeader("responseCode", (int)HttpStatusCode.OK)); } }
public Stream ReadRecordingFile(int id) { try { WebRecordingFileInfo info = GetRecordingFileInfo(id); // read it as a regular file if (info.Exists && info.IsLocalFile && !info.OnNetworkDrive && File.Exists(info.Path)) { return(new FileStream(info.Path, FileMode.Open, FileAccess.Read)); } // try to load it from a network drive if (info.Exists && info.IsLocalFile && info.OnNetworkDrive) { using (var context = NetworkContextFactory.Create()) return(new FileStream(context.RewritePath(info.Path), FileMode.Open, FileAccess.Read)); } // failed Log.Warn("No method to read file for recording {0} with path {1}", id, info.Path); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); return(Stream.Null); } catch (Exception ex) { Log.Warn(String.Format("Failed to read file for recording {0}", id), ex); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError); return(Stream.Null); } }
public static Stream GetResizedImage(ImageMediaSource src, int?maxWidth, int?maxHeight) { // load file if (!src.Exists) { Log.Info("Requested resized image for non-existing source {0}", src.GetDebugName()); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); return(Stream.Null); } // create cache path string filename = String.Format("resize_{0}_{1}_{2}.jpg", src.GetUniqueIdentifier(), maxWidth, maxHeight); // check for existence on disk if (!cache.Contains(filename)) { Image orig; using (var impersonator = src.GetImpersonator()) { orig = Image.FromStream(src.Retrieve()); } if (!ResizeImage(orig, cache.GetPath(filename), maxWidth, maxHeight)) { WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError); return(Stream.Null); } } return(StreamImage(new ImageMediaSource(cache.GetPath(filename)))); }
public Stream ReadRecordingFile(int id) { try { WebRecordingFileInfo info = GetRecordingFileInfo(id); // return it as a simple file if (info.IsLocalFile && File.Exists(info.Path)) { return(new FileStream(info.Path, FileMode.Open, FileAccess.Read)); } // try to load it from a network drive if (info.OnNetworkDrive && info.Exists) { using (NetworkShareImpersonator impersonation = new NetworkShareImpersonator()) { return(new FileStream(info.Path, FileMode.Open, FileAccess.Read)); } } // failed Log.Warn("No method to read file for recording {0}", id); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); return(Stream.Null); } catch (Exception ex) { Log.Warn(String.Format("Failed to read file for recording {0}", id), ex); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError); return(Stream.Null); } }
public virtual Stream ProvideCustomActionFile(string action, string param) { switch (action) { case "segment": if (keepSegments > 0) { RemoveOldSegments(param); } WCFUtil.SetContentType("video/MP2T"); string segmentPath = Path.Combine(TemporaryDirectory, Path.GetFileName(param)); if (!File.Exists(segmentPath)) { Log.Warn("HTTPLiveStreamer: Client requested non-existing segment file {0}", segmentPath); return(Stream.Null); } return(new FileStream(segmentPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)); case "playlist": WCFUtil.SetContentType("application/vnd.apple.mpegurl"); string playlistPath = Path.Combine(TemporaryDirectory, "index.m3u8"); if (!File.Exists(playlistPath)) { Log.Warn("HTTPLiveStreamer: Client requested index.m3u8 that doesn't exist for identifier '{0}'", Identifier); return(Stream.Null); } // Having CRLF instead of LF in the playlist is allowed by the spec, but causes problems for VLC during playback, so strip them. return(StripCarriageReturn(playlistPath)); default: Log.Warn("HTTPLiveStreamer: Request invalid action '{0}' with param '{1}'", action, param); return(Stream.Null); } }
public Stream RetrieveStream(string identifier) { if (!Streams.ContainsKey(identifier)) { Log.Warn("Client called RetrieveStream() for non-existing identifier", identifier); WCFUtil.SetResponseCode(HttpStatusCode.NotFound); return(Stream.Null); } lock (Streams[identifier]) { WCFUtil.SetContentType(Streams[identifier].Context.Profile.MIME); if (Streams[identifier].OutputStream == null) { Log.Warn("Encountered null stream in RetrieveStream for identifier {0}", identifier); WCFUtil.SetResponseCode(HttpStatusCode.NotFound); return(Stream.Null); } WCFUtil.SetContentType(Streams[identifier].Context.Profile.MIME); Streams[identifier].LastActivity = DateTime.Now; if (Streams[identifier].Transcoder is IRetrieveHookTranscoder) { (Streams[identifier].Transcoder as IRetrieveHookTranscoder).RetrieveStreamCalled(); } return(Streams[identifier].OutputStream); } }
public WebBoolResult AuthorizeStreaming() { if (!_authorizedHosts.Contains(WCFUtil.GetClientIPAddress())) { _authorizedHosts.Add(WCFUtil.GetClientIPAddress()); } return(true); }
public Stream Download(string clientDescription, WebMediaType type, int?provider, string itemId, long?position) { // validate source first MediaSource source = new MediaSource(type, provider, itemId); if (!source.Exists) { throw new FileNotFoundException(); } // create context DownloadContext context = new DownloadContext() { ClientDescription = clientDescription, Source = source, StartTime = DateTime.Now, Stream = new ReadTrackingStreamWrapper(source.Retrieve()), MediaInfo = MediaInfoHelper.LoadMediaInfoOrSurrogate(source) // for playerposition view }; // seek to start position if wanted/needed if (position != null && position > 0) { if (context.Stream.CanSeek) { context.Stream.Seek(position.Value, SeekOrigin.Begin); } else { Log.Warn("Download: Cannot seek on stream, failed to set start position to {0}", position); } } // see comment in Streaming.cs:151 string realIp = WCFUtil.GetHeaderValue("forwardedFor", "X-Forwarded-For"); context.ClientIP = realIp == null?WCFUtil.GetClientIPAddress() : String.Format("{0} (via {1})", realIp, WCFUtil.GetClientIPAddress()); // set headers for downloading WCFUtil.AddHeader("Content-Disposition", "attachment; filename=\"" + source.GetFileInfo().Name + "\""); if (source.MediaType != WebMediaType.TV) { WCFUtil.SetContentLength(source.GetFileInfo().Size); } // FIXME: there has to be a better way to do this string mime = MIME.GetFromFilename(source.GetFileInfo().Name); if (mime != null) { WCFUtil.SetContentType(mime); } // finally, save the context and return runningDownloads.Add(context); return(context.Stream); }
public bool Publish() { // old style services foreach (var srv in Installation.GetInstalledServices()) { if (srv.ToWebService() == null || !ZeroconfDiscoverer.serviceTypes.ContainsKey(srv.ToWebService().Value)) { continue; } Dictionary <string, string> additionalData = new Dictionary <string, string>(); additionalData["hwAddr"] = String.Join(";", NetworkInformation.GetMACAddresses()); additionalData["netbios-name"] = System.Environment.MachineName; if (ExternalAddress.GetAddress() != null) { additionalData["external-ip"] = ExternalAddress.GetAddress(); } NetService net = new NetService(ZeroconfDiscoverer.DOMAIN, ZeroconfDiscoverer.serviceTypes[srv.ToWebService().Value], Configuration.Services.GetServiceName(), srv.Port); net.AllowMultithreadedCallbacks = true; net.TXTRecordData = NetService.DataFromTXTRecordDictionary(additionalData); net.DidPublishService += new NetService.ServicePublished(PublishedService); net.DidNotPublishService += new NetService.ServiceNotPublished(FailedToPublishService); net.Publish(); publishedServices.Add(net); } // new style service sets foreach (WebServiceSet set in Detector.CreateSetComposer().ComposeUnique()) { Log.Debug("Publishing service set {0}", set); Dictionary <string, string> additionalData = new Dictionary <string, string>(); additionalData["mac"] = String.Join(";", NetworkInformation.GetMACAddresses()); additionalData["netbios-name"] = Environment.MachineName != null ? Environment.MachineName : String.Empty; additionalData["external-ip"] = ExternalAddress.GetAddress() != null?ExternalAddress.GetAddress() : String.Empty; additionalData["meta"] = WCFUtil.GetCurrentRoot().Remove(WCFUtil.GetCurrentRoot().LastIndexOf("/MPExtended/") + 1); additionalData["mas"] = set.MAS != null ? set.MAS : String.Empty; additionalData["masstream"] = set.MASStream != null ? set.MASStream : String.Empty; additionalData["tas"] = set.TAS != null ? set.TAS : String.Empty; additionalData["tasstream"] = set.TASStream != null ? set.TASStream : String.Empty; additionalData["ui"] = set.UI != null ? set.UI : String.Empty; NetService net = new NetService(ZeroconfDiscoverer.DOMAIN, SET_SERVICE_TYPE, Configuration.Services.GetServiceName(), Configuration.Services.Port); net.AllowMultithreadedCallbacks = true; net.TXTRecordData = NetService.DataFromTXTRecordDictionary(additionalData); net.DidPublishService += new NetService.ServicePublished(PublishedService); net.DidNotPublishService += new NetService.ServiceNotPublished(FailedToPublishService); net.Publish(); publishedServices.Add(net); } return(true); }
public virtual string GetStreamURL() { if (Context.Profile.TranscoderParameters.ContainsKey("rtspOutput") && Context.Profile.TranscoderParameters["rtspOutput"] == "yes") { Thread.Sleep(2500); // FIXME return("rtsp://" + WCFUtil.GetCurrentHostname() + ":5544/" + Identifier + ".sdp"); } else { return(WCFUtil.GetCurrentRoot() + "StreamingService/stream/RetrieveStream?identifier=" + Identifier); } }
public void RetrieveStreamCalled() { WCFUtil.SetContentLength(Context.Source.GetFileInfo().Size); // there has to be a better way to do this object mime = RegistryReader.ReadKey(Microsoft.Win32.RegistryHive.ClassesRoot, Path.GetExtension(Context.Source.GetFileInfo().Name), "Content Type"); if (mime != null) { WCFUtil.SetContentType(mime.ToString()); } }
public ServiceSetComposer CreateSetComposer() { ServiceSetComposer composer = new ServiceSetComposer(hinter); var address = WCFUtil.GetCurrentRoot(); composer.OurAddress = address.Remove(address.LastIndexOf("/MPExtended/") + 1); composer.HasActiveMAS = HasActiveMAS; composer.HasActiveTAS = HasActiveTAS; composer.HasActiveWSS = HasActiveWSS; composer.HasActiveUI = HasUI; return(composer); }
public Stream RetrieveStream(string identifier) { lock (Streams[identifier]) { WebOperationContext.Current.OutgoingResponse.ContentType = Streams[identifier].Context.Profile.MIME; if (Streams[identifier].OutputStream == null) { Log.Warn("Encountered null stream in RetrieveStream for identifier {0}", identifier); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); return(Stream.Null); } return(Streams[identifier].OutputStream); } }
public string GetFullMuxerString() { /* In the end, we should return something like this: * :standard{access=livehttp{seglen=10,delsegs=false,numsegs=0,index=C:\dir\index.m3u8,index-url=http://ip/###.ts},mux=ts{use-key-frames},dst=C:\dir\###.ts} * * As input we get this: * context.Profile.CodecParameters["muxer"] = ts{use-key-frames} * context.Profile.CodecParameters["httpLiveOptions"] = seglen=10,delsegs=false,numsegs=0 */ string indexUrl = WCFUtil.GetCurrentRoot() + "StreamingService/stream/CustomTranscoderData?identifier=" + Identifier + "&action=segment¶meters=######.ts"; string liveHttpOptions = Context.Profile.TranscoderParameters["httpLiveOptions"] + ",index=" + Path.Combine(TemporaryDirectory, "index.m3u8") + ",index-url=" + indexUrl; string destination = Path.Combine(TemporaryDirectory, "######.ts"); return(":standard{access=livehttp{" + liveHttpOptions + "},mux=" + Context.Profile.TranscoderParameters["muxer"] + ",dst=" + destination + "}"); }
public void RetrieveStreamCalled() { // Don't return a length when we're streaming TV, as we don't know the full length of the stream, since we are // reading from a timeshifting buffer. See dicussion in bug #394 and #319. if (Context.Source.MediaType != WebMediaType.TV) { WCFUtil.SetContentLength(Context.Source.GetFileInfo().Size); } // there has to be a better way to do this object mime = RegistryReader.ReadKey(Microsoft.Win32.RegistryHive.ClassesRoot, Path.GetExtension(Context.Source.GetFileInfo().Name), "Content Type"); if (mime != null) { WCFUtil.SetContentType(mime.ToString()); } }
public Stream DoStream(WebMediaType type, int?provider, string itemId, string clientDescription, string profileName, long startPosition, int?idleTimeout) { if (!IsClientAuthorized()) { Log.Warn("Host {0} isn't authorized to call DoStream", WCFUtil.GetClientIPAddress()); WCFUtil.SetResponseCode(HttpStatusCode.Unauthorized); return(Stream.Null); } // calculate timeout, which is by default 5 minutes for direct streaming and 5 seconds for transcoded streams var profile = Configuration.StreamingProfiles.Transcoders.FirstOrDefault(x => x.Name == profileName); if (profile == null) { Log.Warn("Called DoStream with non-existing profile {0}", profileName); return(Stream.Null); } int timeout = profile.Transcoder == typeof(Transcoders.Direct).FullName ? 5 * 60 : 5; if (idleTimeout.HasValue) { timeout = idleTimeout.Value; } // This only works with profiles that actually return something in the RetrieveStream method (i.e. no RTSP or CustomTranscoderData) string identifier = String.Format("dostream-{0}", new Random().Next(10000, 99999)); StreamLog.Debug(identifier, "DoStream: using timeout={0}", timeout); if (!InitStream(type, provider, itemId, null, clientDescription, identifier, timeout)) { StreamLog.Info(identifier, "DoStream: InitStream() failed"); FinishStream(identifier); return(Stream.Null); } if (String.IsNullOrEmpty(StartStream(identifier, profileName, startPosition))) { StreamLog.Info(identifier, "DoStream: StartStream failed"); FinishStream(identifier); return(Stream.Null); } StreamLog.Info(identifier, "DoStream: succeeded, returning stream"); return(RetrieveStream(identifier)); }
public WebBoolResult DeleteRecording(int id) { Log.Info("Deleting recording {0}, as requested by client {1}", id, WCFUtil.GetClientIPAddress()); try { bool retVal = _tvControl.DeleteRecording(id); if (!retVal) { Log.Warn("Failed to delete recording, TV Server returned false"); } return(retVal); } catch (Exception ex) { Log.Warn("Failed to delete recoding", ex); return(false); } }
public Stream GetMediaItem(WebStreamMediaType type, int?provider, string itemId) { MediaSource source = new MediaSource(type, provider, itemId); try { if (!source.Exists) { throw new FileNotFoundException(); } return(source.Retrieve()); } catch (Exception ex) { WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); Log.Info(String.Format("GetMediaItem() failed for {0}", source.GetDebugName()), ex); return(Stream.Null); } }
public Stream GetMediaItem(string clientDescription, WebMediaType type, int?provider, string itemId, long?startPosition) { if (!IsClientAuthorized()) { Log.Warn("Host {0} isn't authorized to call GetMediaItem", WCFUtil.GetClientIPAddress()); WCFUtil.SetResponseCode(HttpStatusCode.Unauthorized); return(Stream.Null); } try { return(_downloads.Download(clientDescription, type, provider, itemId, startPosition)); } catch (Exception ex) { WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); Log.Info(String.Format("GetMediaItem() failed for type={0}; provider={1}; itemId={2}", type, provider, itemId), ex); return(Stream.Null); } }
public Stream CustomTranscoderData(string identifier, string action, string parameters) { if (!Streams.ContainsKey(identifier)) { Log.Warn("Client called CustomTranscoderData() for non-existing identifier {0}", identifier); WCFUtil.SetResponseCode(HttpStatusCode.NotFound); return(Stream.Null); } lock (Streams[identifier]) { if (!(Streams[identifier].Transcoder is ICustomActionTranscoder)) { return(Stream.Null); } Streams[identifier].LastActivity = DateTime.Now; return(((ICustomActionTranscoder)Streams[identifier].Transcoder).CustomActionData(action, parameters)); } }
private static Stream StreamPostprocessedImage(ImageMediaSource src, int?maxWidth, int?maxHeight, string borders, string format) { if (!src.Exists) { Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName()); WCFUtil.SetResponseCode(HttpStatusCode.NotFound); return(Stream.Null); } if (borders != null && (!maxWidth.HasValue || !maxHeight.HasValue)) { Log.Error("ResizeImage() called with a borders value but width or height is null"); WCFUtil.SetResponseCode(HttpStatusCode.BadRequest); return(Stream.Null); } if (format == null) { format = src.Extension.Substring(1); } Func <Stream> streamFactory = ProcessAndCacheImage(src, maxWidth, maxHeight, borders, format); if (streamFactory == null) { return(Stream.Null); } try { // return image to client WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000"); WCFUtil.SetContentType(GetMime(format)); return(streamFactory()); } catch (Exception ex) { Log.Warn(String.Format("Failed to post-process and stream image {0}", src.GetDebugName()), ex); return(Stream.Null); } }
public Stream RetrieveFile(int?provider, WebMediaType mediatype, WebFileType filetype, string id, int offset) { try { string path = GetPathList(provider, mediatype, filetype, id).ElementAt(offset); WebFileInfo info = GetFileInfo(provider, mediatype, filetype, id, offset); // first try to read the file if (info.IsLocalFile && File.Exists(path)) { return(new FileStream(path, FileMode.Open, FileAccess.Read)); } // maybe the plugin has some magic if (!info.IsLocalFile && info.Exists && !info.OnNetworkDrive) { return(GetLibrary(provider, mediatype).GetFile(path)); } // try to load it from a network drive if (info.OnNetworkDrive && info.Exists) { using (NetworkShareImpersonator impersonation = new NetworkShareImpersonator()) { return(new FileStream(path, FileMode.Open, FileAccess.Read)); } } // fail Log.Warn("Requested non-existing or non-accessible file mediatype={0} filetype={1} id={2} offset={3}", mediatype, filetype, id, offset); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); return(Stream.Null); } catch (Exception ex) { Log.Info("Failed to retrieve file for mediatype=" + mediatype + ", filetype=" + filetype + ", id=" + id + " and offset=" + offset, ex); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError); return(Stream.Null); } }
public bool Setup() { siteRoot = WCFUtil.GetCurrentRoot() + "StreamingService/stream/CustomTranscoderData?identifier=" + identifier + "&action=segment¶meters="; TemporaryDirectory = Path.Combine(Path.GetTempPath(), "MPExtended.Services.StreamingService.HTTPLiveStreaming-" + new Random().Next()); Directory.CreateDirectory(TemporaryDirectory); Log.Debug("HTTPLiveStreaming: created temporary directory {0}", TemporaryDirectory); string arguments = String.Format("- {0} segment playlist.m3u8 {2} {3}", SEGMENT_LENGTH, TemporaryDirectory, siteRoot, SEGMENT_BUFFER); string segmenter = @"..\..\..\..\Libraries\Streaming\segmenter\segmenter.exe"; ProcessStartInfo start = new ProcessStartInfo(segmenter, arguments); start.UseShellExecute = false; start.RedirectStandardInput = true; start.RedirectStandardOutput = false; start.RedirectStandardError = true; start.WindowStyle = DebugOutput ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden; start.CreateNoWindow = !DebugOutput; start.WorkingDirectory = TemporaryDirectory; Log.Info("HTTPLiveStreaming: segmenter arguments: {0}", arguments); try { segmenterApplication = new Process(); segmenterApplication.StartInfo = start; segmenterApplication.Start(); ThreadManager.Start("HTTPLiveSegmenter", MonitorThread); } catch (Exception ex) { Log.Error("HTTPLiveStreaming: failed to start segmenter", ex); return(false); } return(true); }
private static Stream StreamImage(ImageMediaSource src) { if (!src.Exists) { Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName()); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); return(Stream.Null); } Dictionary <string, string> commonMimeTypes = new Dictionary <string, string>() { { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".png", "image/png" }, { ".gif", "image/gif" }, { ".bmp", "image/x-ms-bmp" }, }; string mime = commonMimeTypes.ContainsKey(src.Extension) ? commonMimeTypes[src.Extension] : "application/octet-stream"; WCFUtil.SetContentType(mime); return(src.Retrieve()); }
public static Stream GetResizedImage(ImageMediaSource src, int?maxWidth, int?maxHeight) { // load file if (!src.Exists) { Log.Info("Requested resized image for non-existing source {0}", src.GetDebugName()); WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound); return(Stream.Null); } // create cache path string tmpDir = Path.Combine(Path.GetTempPath(), "MPExtended", "imagecache"); if (!Directory.Exists(tmpDir)) { Directory.CreateDirectory(tmpDir); } string cachedPath = Path.Combine(tmpDir, String.Format("rs_{0}_{1}_{2}.jpg", src.GetUniqueIdentifier(), maxWidth, maxHeight)); // check for existence on disk if (!File.Exists(cachedPath)) { Image orig; using (var impersonator = src.GetImpersonator()) { orig = Image.FromStream(src.Retrieve()); } if (!ResizeImage(orig, cachedPath, maxWidth, maxHeight)) { WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError); return(Stream.Null); } } return(StreamImage(new ImageMediaSource(cachedPath))); }
public bool InitStream(string identifier, string clientDescription, MediaSource source) { if (!source.Exists) { Log.Warn("Tried to start stream for non-existing file {0}", source.GetDebugName()); return(false); } ActiveStream stream = new ActiveStream(); stream.Identifier = identifier; stream.ClientDescription = clientDescription; stream.ClientIP = WCFUtil.GetClientIPAddress(); stream.StartTime = DateTime.Now; stream.Context = new StreamContext(); stream.Context.Source = source; stream.Context.IsTv = source.MediaType == WebStreamMediaType.TV; lock (Streams) { Streams[identifier] = stream; } return(true); }