Exemplo n.º 1
0
        /// <summary>
        /// Basic constructor using default address and port settings
        /// </summary>
        public HttpServer()
        {
            config = new SharpConfig();
            mimeTypes = new MimeTypes();
            CallbackSys = new CallbackSubSystem();

            if (config.loaded)
            {
                Modules = new ModuleServices(config, ref CallbackSys);
                Modules.FindModules();

                try
                {
                    Debug.WriteLine("Attempting to bind to " + config.directive["Address"] + ":" + config.directive["Port"]);
                    tcpListener = new TcpListener(IPAddress.Parse(config.directive["Address"]), Convert.ToInt32(config.directive["Port"])); // will default to any address and port 80 on this constructor
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to bind to address or port. Exception: " + ex.Message);
                    Debug.WriteLine("Failed to bind to address or port. Exception: " + ex.Message);
                }
                PrepListenThread();
            }
            else
            {
                Console.WriteLine("config not loaded.");
            }
        }
        protected virtual MimeTypes GetRegisteredMimeTypes()
        {
            var mimeTypes = new MimeTypes();
            mimeTypes.RegisterBuiltinTypes();

            return mimeTypes;
        }
        public void Setup()
        {
            TestMimes = new MimeTypes();
            TestMimes.Register("text/plain", "text");
            TestMimes.Register("text/html", "html", new string[] {"application/xhtml+xml"});
			TestMimes.Register("application/xml", "xml", new string[] { "text/xml" });
            
        }
 public void Setup()
 {
     TestMimes = new MimeTypes();
     TestMimes.Register("text/plain", "text");
     TestMimes.Register("text/html", "html", new[] {"application/xhtml+xml"});
     TestMimes.Register("application/xml", "xml",new[] {"text/xml"});
 	Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
 }
Exemplo n.º 5
0
        public static MimeType[] Parse(string acceptHeader, MimeTypes mimes)
        {
            string[] splitHeaders = acceptHeader.Split(',');
            List<AcceptType> acceptTypes = new List<AcceptType>(splitHeaders.Length);

            for(int i = 0; i < splitHeaders.Length; i++)
            {
                string[] parms = splitHeaders[i].Split(';');
                AcceptType at = new AcceptType();
                at.Name = parms[0];
                at.Order = i;

                at.Q = parms.Length == 2 ? Convert.ToSingle(parms[1].Substring(2)) : 1;
                acceptTypes.Add(at);
            }

            AcceptType appXml = acceptTypes.Find(delegate(AcceptType at) { return at.Name == "application/xml"; });
            if (appXml != null)
            {
                Regex regEx = new Regex(@"\+xml$");

                int appXmlIndex;
                int idx = appXmlIndex = acceptTypes.IndexOf(appXml);

                while(idx < acceptTypes.Count)
                {
                    AcceptType at = acceptTypes[idx];
                    if (at.Q < appXml.Q)
                    {
                        break;
                    }

                    if (regEx.IsMatch(at.Name))
                    {
                        acceptTypes.Remove(at);
                        acceptTypes.Insert(appXmlIndex, at);
                        appXmlIndex++;
                    }
                    idx++;
                }
            }

            List<MimeType> returnTypes = new List<MimeType>();
            acceptTypes.Sort(new Comparison<AcceptType>(descendingAcceptTypes));
            foreach(AcceptType type in acceptTypes)
            {
//                returnTypes.AddRange(mimes.Where(m => m.MimeString == type.Name || m.Synonyms.Contains(type.Name)));                
                returnTypes.AddRange(mimes.FindAll(delegate(MimeType m)
                                                   {
                                                       return
                                                           m.MimeString == type.Name ||
                                                           m.Synonyms.Contains(type.Name);
                                                   }));
            }

            //return returnTypes.Distinct().ToArray();
			return returnTypes.ToArray();
        }
		private void DoResponse(string format, IControllerBridge bridge)
		{
			Responder hander = new Responder(bridge, bridge.ControllerAction);
			hander.Format = format;
			_renderers[format](hander);

			MimeTypes types = new MimeTypes();
			types.RegisterBuiltinTypes();

			MimeType usedType = types.Where(mime => mime.Symbol == format).First();
			bridge.SetResponseType(usedType);
		}
Exemplo n.º 7
0
		public static MimeType[] Parse(string acceptHeader, MimeTypes mimes)
		{
			
			var splitHeaders = acceptHeader.Split(',');
			var acceptTypes = new List<AcceptType>(splitHeaders.Length);

			for (int i = 0; i < splitHeaders.Length; i++)
			{
				var parms = splitHeaders[i].Split(';');
				AcceptType at = new AcceptType();
				at.Name = parms[0].Trim();
				at.Order = i;

				at.Q = parms.Length == 2 ? Convert.ToSingle(parms[1].Substring(2)) : 1;
				acceptTypes.Add(at);
			}

			var appXml = acceptTypes.Find(at => at.Name == "application/xml");
			if (appXml != null)
			{
				var regEx = new System.Text.RegularExpressions.Regex(@"\+xml$");

				int appXmlIndex;
				int idx = appXmlIndex = acceptTypes.IndexOf(appXml);

				while (idx < acceptTypes.Count)
				{
					var at = acceptTypes[idx];
					if (at.Q < appXml.Q)
					{
						break;
					}
					
					if(regEx.IsMatch(at.Name)) {
						acceptTypes.Remove(at);
						acceptTypes.Insert(appXmlIndex,at);
						appXmlIndex++;
					}
					idx++;
				}                
			}
																										
			var returnTypes = new List<MimeType>();
			foreach (var type in acceptTypes.OrderByDescending(at => at.Q))
			{
				returnTypes.AddRange(mimes.Where(m => m.MimeString == type.Name || m.Synonyms.Contains(type.Name)));                
			}


			return returnTypes.Distinct().ToArray();
		}
        public void Setup()
        {
        	mimes = new MimeTypes();
			mimes.RegisterBuiltinTypes();

            mocks = new MockRepository();
            bridge = mocks.DynamicMock<IControllerBridge>();
            format = new ResponseFormat(mimes);
            handlerInvoked = "";

            ResponseFormatInternal iformat = (ResponseFormatInternal)format;
            iformat.AddRenderer("xml", x => handlerInvoked = "xml");
            iformat.AddRenderer("html", x => handlerInvoked = "html");
        }
        public void IfRespondWithMimeAll_ThenFirstResponder_ShouldBeInvoked()
        {
            mocks = new MockRepository();
            bridge = mocks.DynamicMock<IControllerBridge>();

            using (mocks.Record())
            {
                SetupResult.For(bridge.ControllerAction).Return("Show");
            }
            
			string handlerInvoked = "";
			MimeTypes mimeTypes = new MimeTypes();
			mimeTypes.RegisterBuiltinTypes();

            format = (ResponseFormatInternal)new ResponseFormat(mimeTypes);
            format.AddRenderer("html", response => handlerInvoked = "html");
            format.AddRenderer("xml", response => handlerInvoked = "xml");

            format.RespondWith("all", bridge);
            Assert.AreEqual("html", handlerInvoked);
        }
Exemplo n.º 10
0
        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());
            }
        }
Exemplo n.º 11
0
        protected void RespondTo(Action<ResponseFormat> collectFormats)
        {
            MimeTypes registeredMimes = new MimeTypes();
            registeredMimes.RegisterBuiltinTypes();

            ResponseHandler handler = new ResponseHandler();
            handler.ControllerBridge = new ControllerBridge(this, _controllerAction);
            handler.AcceptedMimes = AcceptType.Parse(Request.Headers["Accept"], registeredMimes);
            handler.Format = new ResponseFormat();

            collectFormats(handler.Format);
            handler.Respond();
        }
Exemplo n.º 12
0
		public ResponseFormat(MimeTypes mimeTypes)
		{
			_renderers = new Dictionary<string, ResponderDelegate>();
			_order = new List<string>();
			_mimeTypes = mimeTypes;
		}
Exemplo n.º 13
0
        private void AddVideoResource(XmlWriter writer, BaseItem video, string deviceId, Filter filter, string contentFeatures, StreamInfo streamInfo)
        {
            writer.WriteStartElement(string.Empty, "res", NS_DIDL);

            var url = NormalizeDlnaMediaUrl(streamInfo.ToUrl(_serverAddress, _accessToken));

            var mediaSource = streamInfo.MediaSource;

            if (mediaSource.RunTimeTicks.HasValue)
            {
                writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", _usCulture));
            }

            if (filter.Contains("res@size"))
            {
                if (streamInfo.IsDirectStream || streamInfo.EstimateContentLength)
                {
                    var size = streamInfo.TargetSize;

                    if (size.HasValue)
                    {
                        writer.WriteAttributeString("size", size.Value.ToString(_usCulture));
                    }
                }
            }

            var totalBitrate     = streamInfo.TargetTotalBitrate;
            var targetSampleRate = streamInfo.TargetAudioSampleRate;
            var targetChannels   = streamInfo.TargetAudioChannels;

            var targetWidth  = streamInfo.TargetWidth;
            var targetHeight = streamInfo.TargetHeight;

            if (targetChannels.HasValue)
            {
                writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(_usCulture));
            }

            if (filter.Contains("res@resolution"))
            {
                if (targetWidth.HasValue && targetHeight.HasValue)
                {
                    writer.WriteAttributeString("resolution", string.Format("{0}x{1}", targetWidth.Value, targetHeight.Value));
                }
            }

            if (targetSampleRate.HasValue)
            {
                writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(_usCulture));
            }

            if (totalBitrate.HasValue)
            {
                writer.WriteAttributeString("bitrate", totalBitrate.Value.ToString(_usCulture));
            }

            var mediaProfile = _profile.GetVideoMediaProfile(streamInfo.Container,
                                                             streamInfo.TargetAudioCodec.FirstOrDefault(),
                                                             streamInfo.TargetVideoCodec.FirstOrDefault(),
                                                             streamInfo.TargetAudioBitrate,
                                                             targetWidth,
                                                             targetHeight,
                                                             streamInfo.TargetVideoBitDepth,
                                                             streamInfo.TargetVideoProfile,
                                                             streamInfo.TargetVideoLevel,
                                                             streamInfo.TargetFramerate ?? 0,
                                                             streamInfo.TargetPacketLength,
                                                             streamInfo.TargetTimestamp,
                                                             streamInfo.IsTargetAnamorphic,
                                                             streamInfo.IsTargetInterlaced,
                                                             streamInfo.TargetRefFrames,
                                                             streamInfo.TargetVideoStreamCount,
                                                             streamInfo.TargetAudioStreamCount,
                                                             streamInfo.TargetVideoCodecTag,
                                                             streamInfo.IsTargetAVC);

            var filename = url.Substring(0, url.IndexOf('?'));

            var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
               ? MimeTypes.GetMimeType(filename)
               : mediaProfile.MimeType;

            writer.WriteAttributeString("protocolInfo", string.Format(
                                            "http-get:*:{0}:{1}",
                                            mimeType,
                                            contentFeatures
                                            ));

            writer.WriteString(url);

            writer.WriteFullEndElement();
        }
Exemplo n.º 14
0
 public FileResponse(string filePath) :
     this(filePath, MimeTypes.GetMimeType(filePath))
 {
 }
Exemplo n.º 15
0
        /// <summary>
        /// Gets the save path.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="saveLocally">if set to <c>true</c> [save locally].</param>
        /// <returns>System.String.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// imageIndex
        /// or
        /// imageIndex
        /// </exception>
        private string GetStandardSavePath(BaseItem item, ImageType type, int?imageIndex, string mimeType, bool saveLocally)
        {
            var season    = item as Season;
            var extension = MimeTypes.ToExtension(mimeType);

            if (string.IsNullOrWhiteSpace(extension))
            {
                throw new ArgumentException(string.Format("Unable to determine image file extension from mime type {0}", mimeType));
            }

            if (type == ImageType.Thumb && saveLocally)
            {
                if (season != null && season.IndexNumber.HasValue)
                {
                    var seriesFolder = season.SeriesPath;

                    var seasonMarker = season.IndexNumber.Value == 0
                                           ? "-specials"
                                           : season.IndexNumber.Value.ToString("00", UsCulture);

                    var imageFilename = "season" + seasonMarker + "-landscape" + extension;

                    return(Path.Combine(seriesFolder, imageFilename));
                }

                if (item.IsInMixedFolder)
                {
                    return(GetSavePathForItemInMixedFolder(item, type, "landscape", extension));
                }

                return(Path.Combine(item.ContainingFolderPath, "landscape" + extension));
            }

            if (type == ImageType.Banner && saveLocally)
            {
                if (season != null && season.IndexNumber.HasValue)
                {
                    var seriesFolder = season.SeriesPath;

                    var seasonMarker = season.IndexNumber.Value == 0
                                           ? "-specials"
                                           : season.IndexNumber.Value.ToString("00", UsCulture);

                    var imageFilename = "season" + seasonMarker + "-banner" + extension;

                    return(Path.Combine(seriesFolder, imageFilename));
                }
            }

            string filename;
            var    folderName = item is MusicAlbum ||
                                item is MusicArtist ||
                                item is PhotoAlbum ||
                                item is Person ||
                                (saveLocally && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Legacy) ?
                                "folder" :
                                "poster";

            switch (type)
            {
            case ImageType.Art:
                filename = "clearart";
                break;

            case ImageType.BoxRear:
                filename = "back";
                break;

            case ImageType.Thumb:
                filename = "landscape";
                break;

            case ImageType.Disc:
                filename = item is MusicAlbum ? "cdart" : "disc";
                break;

            case ImageType.Primary:
                filename = saveLocally && item is Episode?_fileSystem.GetFileNameWithoutExtension(item.Path) : folderName;

                break;

            case ImageType.Backdrop:
                filename = GetBackdropSaveFilename(item.GetImages(type), "backdrop", "backdrop", imageIndex);
                break;

            case ImageType.Screenshot:
                filename = GetBackdropSaveFilename(item.GetImages(type), "screenshot", "screenshot", imageIndex);
                break;

            default:
                filename = type.ToString().ToLower();
                break;
            }

            if (string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase))
            {
                extension = ".jpg";
            }

            extension = extension.ToLower();

            string path = null;

            if (saveLocally)
            {
                if (type == ImageType.Primary && item is Episode)
                {
                    path = Path.Combine(_fileSystem.GetDirectoryName(item.Path), "metadata", filename + extension);
                }

                else if (item.IsInMixedFolder)
                {
                    path = GetSavePathForItemInMixedFolder(item, type, filename, extension);
                }

                if (string.IsNullOrEmpty(path))
                {
                    path = Path.Combine(item.ContainingFolderPath, filename + extension);
                }
            }

            // None of the save local conditions passed, so store it in our internal folders
            if (string.IsNullOrEmpty(path))
            {
                if (string.IsNullOrEmpty(filename))
                {
                    filename = folderName;
                }
                path = Path.Combine(item.GetInternalMetadataPath(), filename + extension);
            }

            return(path);
        }
Exemplo n.º 16
0
        static void HandleNimigemActivate(Uri uri)
        {
            var preformattedLines  = new List <GeminiLine>();
            var exitedPreformatted = false;
            var enteredPreformat   = false;
            var foundNimigemEdit   = false;

            var currentLine = _lineView.SelectedItem;

            var activatedLine = (GeminiLine)_lineView.Source.ToList()[currentLine];

            //check if it is hinted as a null payload link
            if (activatedLine.Line.StartsWith('\u2205'.ToString()))
            {
                //send null payload
                try
                {
                    SubmitNimigem(uri, Encoding.UTF8.GetBytes(""), "text/plain");
                }
                catch (Exception e)
                {
                    Dialogs.MsgBoxOK("Nimigem error", "Nimigem error: " + e.Message);
                }
                return;
            }

            //search back in the page for the linked text area
            //gather the previous nimigem lines and let the user edit the text
            while (currentLine >= 0)
            {
                var gemLine = (GeminiLine)_lineView.Source.ToList()[currentLine];

                if (gemLine.LineType == "```+")
                {
                    enteredPreformat = true;
                    foundNimigemEdit = true;        //strictly speaking this will ignore all nimigem areas that are empty...
                }

                if (enteredPreformat & gemLine.LineType != "```+")
                {
                    exitedPreformatted = true;
                }

                if (!exitedPreformatted && enteredPreformat && gemLine.LineType == "```+")
                {
                    //we found a line in the first preceeding preformatted area
                    preformattedLines.Add(gemLine);
                }

                currentLine--;
            }


            var sb = new StringBuilder();

            preformattedLines.Reverse();

            for (int n = 0; n < preformattedLines.Count; n++)
            {
                var editLine = preformattedLines[n];

                //nimigem spec requires any required preformatted markers inside
                //editable preformatted areas to be escaped with zero width space
                if (editLine.Line.StartsWith('\u200b'.ToString() + "```"))
                {
                    sb.Append(editLine.Line.Substring(1));      //trim leading zero width space used to escape preformatted markers
                }
                else
                {
                    sb.Append(editLine.Line);
                }

                //append newline to all except the last one
                if (n < preformattedLines.Count - 1)
                {
                    sb.Append("\n");
                }
            }

            if (foundNimigemEdit)
            {
                var userEdit = Dialogs.MultilineInputBox("Nimigem edit", "Edit the text to be sent to: " + uri.AbsoluteUri, sb.ToString());

                if (userEdit.ButtonPressed == TextDialogResponse.Buttons.Ok)
                {
                    try
                    {
                        //send as plain text, utf8
                        SubmitNimigem(uri, Encoding.UTF8.GetBytes(userEdit.Text), "text/plain");
                    }
                    catch (Exception e)
                    {
                        Dialogs.MsgBoxOK("Nimigem error", "Nimigem error: \n" + e.Message);
                    }
                }
            }
            else
            {
                //No associated preceding Nimigem editable preformatted area was found.
                //so send a file

                //show a dialog to choose a file
                var openDialog = new Terminal.Gui.OpenDialog("Nimigem upload", "Choose a file to send to the Nimigem server");
                Application.Run(openDialog);

                if (openDialog.FilePaths.Count > 0)
                {
                    var selectedPath = openDialog.FilePaths[0];
                    var bytes        = File.ReadAllBytes(selectedPath);
                    var extension    = Path.GetExtension(selectedPath);

                    // since text/gemini is not widely known but might be more common for users of a gemini client
                    // we test for it, otherwise we use the MimeTypes library to infer it
                    var mediaType = (extension == ".gmi" || extension == ".gemini") ? "text/gemini" : MimeTypes.GetMimeType(selectedPath);

                    try
                    {
                        SubmitNimigem(uri, bytes, mediaType);                       //send to the server
                    }
                    catch (Exception e)
                    {
                        Dialogs.MsgBoxOK("Nimigem error", "Nimigem error: \n" + e.Message);
                    }
                }
            }
        }
Exemplo n.º 17
0
        public async Task Invoke(
            HttpContext context,
            IMediaService mediaService,
            IFolderService folderService,
            IPermissionService permissionService,
            IWorkContext workContext,
            MediaSettings mediaSettings,
            MediaHelper mediaHelper,
            Lazy <IEnumerable <IMediaHandler> > mediaHandlers,
            ILogger <MediaMiddleware> logger)
        {
            var mediaFileId = context.GetRouteValueAs <int>("id");
            var path        = context.GetRouteValueAs <string>("path");

            if (context.Request.Method != HttpMethods.Get && context.Request.Method != HttpMethods.Head)
            {
                await NotFound(null);

                return;
            }

            var method = context.Request.Method;

            MediaFileInfo mediaFile = null;
            MediaPathData pathData  = null;

            if (mediaFileId == 0)
            {
                // This is most likely a request for a default placeholder image
                pathData = new MediaPathData(path);
            }
            else if (!mediaHelper.TokenizePath(path, false, out pathData))
            {
                // Missing or malformed Uri: get file metadata from DB by id, but only when current user has media manage rights
                if (!(await permissionService.AuthorizeAsync(Permissions.Media.Update)))
                {
                    await NotFound(null);

                    return;
                }

                mediaFile = await mediaService.GetFileByIdAsync(mediaFileId, MediaLoadFlags.AsNoTracking);

                if (mediaFile == null || mediaFile.FolderId == null || mediaFile.Deleted)
                {
                    await NotFound(mediaFile?.MimeType);

                    return;
                }

                pathData = new MediaPathData(folderService.GetNodeById(mediaFile.FolderId.Value), mediaFile.Name)
                {
                    Extension = mediaFile.Extension,
                    MimeType  = mediaFile.MimeType
                };
            }

            var q = await CreateImageQuery(context, pathData.MimeType, pathData.Extension);

            // Security: check allowed thumnail sizes and return 404 if disallowed.
            var thumbMaxWidth    = q.MaxWidth;
            var thumbMaxHeight   = q.MaxHeight;
            var thumbSizeAllowed = IsThumbnailSizeAllowed(thumbMaxWidth) && (thumbMaxHeight == thumbMaxWidth || IsThumbnailSizeAllowed(thumbMaxHeight));

            if (!thumbSizeAllowed)
            {
                await NotFound(pathData.MimeType);

                return;
            }

            // Create the handler context
            var handlerContext = new MediaHandlerContext
            {
                ApplicationContext = _appContext,
                HttpContext        = context,
                CurrentCustomer    = workContext.CurrentCustomer,
                PermissionService  = permissionService,
                MediaFileId        = mediaFileId,
                RawPath            = path,
                MediaService       = mediaService,
                PathData           = pathData,
                ImageQuery         = q
            };

            handlerContext.SetSourceFile(mediaFile);

            var handlers = mediaHandlers.Value.OrderBy(x => x.Order).ToArray();

            // Run every registered media handler to obtain a thumbnail for the requested media file
            IMediaHandler currentHandler;

            for (var i = 0; i < handlers.Length; i++)
            {
                currentHandler = handlers[i];

                // Execute handler
                await currentHandler.ExecuteAsync(handlerContext);

                if (handlerContext.Exception != null)
                {
                    var isThumbExtractFail = handlerContext.Exception is ExtractThumbnailException;
                    var statusCode         = isThumbExtractFail ? StatusCodes.Status204NoContent : StatusCodes.Status500InternalServerError;
                    var statusMessage      = isThumbExtractFail ? handlerContext.Exception.InnerException?.Message : handlerContext.Exception.Message;

                    await SendStatus(statusCode, statusMessage.EmptyNull());

                    return;
                }

                if (handlerContext.Executed || handlerContext.ResultFile != null)
                {
                    // Get out if the handler produced a result file or has been executed in any way
                    break;
                }
            }

            try
            {
                var responseFile = handlerContext.ResultFile ?? await handlerContext.GetSourceFileAsync();

                if (responseFile == null || !responseFile.Exists)
                {
                    await NotFound(pathData.MimeType);

                    return;
                }

                if (string.Equals(responseFile.Extension, "." + pathData.Extension, StringComparison.CurrentCultureIgnoreCase))
                {
                    pathData.MimeType = MimeTypes.MapNameToMimeType(responseFile.Extension);
                }

                // Create FileStreamResult object
                var fileResult = CreateFileResult(responseFile, pathData);

                // Cache control
                ApplyResponseCaching(context, mediaSettings);

                // INFO: Although we are outside of the MVC pipeline we gonna use ActionContext anyway, because "FileStreamResult"
                // does everything we need (ByteRange, ETag etc.), so wo we gonna use it instead of reinventing the wheel.
                // A look at the MVC source code reveals that HttpContext is the only property that gets accessed, therefore we can omit
                // all the other stuff like ActionDescriptor or ModelState (which we cannot access or create from a middleware anyway).
                await fileResult.ExecuteResultAsync(new ActionContext { HttpContext = context, RouteData = context.GetRouteData() });
            }
            finally
            {
                var imageProcessor = context.RequestServices.GetRequiredService <IImageProcessor>();
                logger.Debug("ImageProcessor TOTAL: {0} ms.", imageProcessor.TotalProcessingTimeMs);
            }

            #region Functions

            bool IsThumbnailSizeAllowed(int?size)
            {
                return(size.GetValueOrDefault() == 0 ||
                       mediaSettings.IsAllowedThumbnailSize(size.Value) ||
                       permissionService.Authorize(Permissions.Media.Update, workContext.CurrentCustomer));
            }

            async Task NotFound(string mime)
            {
                context.Response.ContentType = mime.NullEmpty() ?? "text/html";
                context.Response.StatusCode  = 404;
                await context.Response.WriteAsync("404: Not Found");
            }

            async Task SendStatus(int code, string message)
            {
                context.Response.StatusCode = code;
                await context.Response.WriteAsync(message);
            }

            #endregion
        }
Exemplo n.º 18
0
 /// <summary>
 /// 返回特定文件扩展名的Content-Type,如果未找到任何对应关系,则返回默认值
 /// </summary>
 /// <param name="fileExtension"></param>
 /// <returns></returns>
 public string GetMimeFromExtension(string fileExtension)
 {
     fileExtension = (fileExtension ?? string.Empty).ToLower();
     return(MimeTypes.ContainsKey(fileExtension) ? MimeTypes[fileExtension] : DefaultMime);
 }
Exemplo n.º 19
0
        public async Task <Tuple <string, string, DateTime> > ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var originalImage = options.Image;

            if (!originalImage.IsLocalFile)
            {
                originalImage = await _libraryManager().ConvertImageToLocal(options.Item, originalImage, options.ImageIndex).ConfigureAwait(false);
            }

            var originalImagePath = originalImage.Path;
            var dateModified      = originalImage.DateModified;

            if (!_imageEncoder.SupportsImageEncoding)
            {
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            if (options.CropWhiteSpace && _imageEncoder.SupportsImageEncoding)
            {
                var tuple = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            if (options.Enhancers.Count > 0)
            {
                var tuple = await GetEnhancedImage(new ItemImageInfo
                {
                    DateModified = dateModified,
                    Type         = originalImage.Type,
                    Path         = originalImagePath
                }, options.Item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            if (options.HasDefaultOptions(originalImagePath))
            {
                // 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;

            try
            {
                originalImageSize = GetImageSize(originalImagePath, dateModified, true);
                if (options.HasDefaultOptions(originalImagePath, originalImageSize.Value))
                {
                    // Just spit out the original file if all the options are default
                    return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
                }
            }
            catch
            {
                originalImageSize = null;
            }

            var newSize = GetNewImageSize(options, originalImageSize);
            var quality = options.Quality;

            var outputFormat  = GetOutputFormat(options.SupportedOutputFormats[0]);
            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.BackgroundColor, options.ForegroundLayer);

            var imageProcessingLockTaken = false;

            try
            {
                CheckDisposed();

                if (!_fileSystem.FileExists(cacheFilePath))
                {
                    var newWidth  = Convert.ToInt32(newSize.Width);
                    var newHeight = Convert.ToInt32(newSize.Height);

                    _fileSystem.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
                    var tmpPath = Path.ChangeExtension(Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString("N")), Path.GetExtension(cacheFilePath));
                    _fileSystem.CreateDirectory(Path.GetDirectoryName(tmpPath));

                    await _imageProcessingSemaphore.WaitAsync().ConfigureAwait(false);

                    imageProcessingLockTaken = true;

                    _imageEncoder.EncodeImage(originalImagePath, tmpPath, AutoOrient(options.Item), newWidth, newHeight, quality, options, outputFormat);
                    CopyFile(tmpPath, cacheFilePath);

                    return(new Tuple <string, string, DateTime>(tmpPath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(tmpPath)));
                }

                return(new Tuple <string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath)));
            }
            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
            {
                if (imageProcessingLockTaken)
                {
                    _imageProcessingSemaphore.Release();
                }
            }
        }
Exemplo n.º 20
0
        public async Task <Tuple <string, string, DateTime> > ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var          originalImage = options.Image;
            IHasMetadata 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;

            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.Count > 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;
            }

            var photo      = item as Photo;
            var autoOrient = false;
            ImageOrientation?orientation = null;

            if (photo != null && photo.Orientation.HasValue && photo.Orientation.Value != ImageOrientation.TopLeft)
            {
                autoOrient  = true;
                orientation = photo.Orientation;
            }

            if (options.HasDefaultOptions(originalImagePath) && (!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 Tuple<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);
            }
        }
Exemplo n.º 21
0
        /// <inheritdoc />
        public async Task <(string Path, string?MimeType, DateTime DateModified)> ProcessImage(ImageProcessingOptions options)
        {
            ItemImageInfo originalImage = options.Image;
            BaseItem      item          = options.Item;

            string          originalImagePath = originalImage.Path;
            DateTime        dateModified      = originalImage.DateModified;
            ImageDimensions?originalImageSize = null;

            if (originalImage.Width > 0 && originalImage.Height > 0)
            {
                originalImageSize = new ImageDimensions(originalImage.Width, originalImage.Height);
            }

            var mimeType = MimeTypes.GetMimeType(originalImagePath);

            if (!_imageEncoder.SupportsImageEncoding)
            {
                return(originalImagePath, mimeType, dateModified);
            }

            var supportedImageInfo = await GetSupportedImage(originalImagePath, dateModified).ConfigureAwait(false);

            originalImagePath = supportedImageInfo.Path;

            // Original file doesn't exist, or original file is gif.
            if (!File.Exists(originalImagePath) || string.Equals(mimeType, MediaTypeNames.Image.Gif, StringComparison.OrdinalIgnoreCase))
            {
                return(originalImagePath, mimeType, dateModified);
            }

            dateModified = supportedImageInfo.DateModified;
            bool requiresTransparency = _transparentImageTypes.Contains(Path.GetExtension(originalImagePath));

            bool             autoOrient  = false;
            ImageOrientation?orientation = null;

            if (item is Photo photo)
            {
                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(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
            }

            int quality = options.Quality;

            ImageFormat outputFormat  = GetOutputFormat(options.SupportedOutputFormats, requiresTransparency);
            string      cacheFilePath = GetCacheFilePath(
                originalImagePath,
                options.Width,
                options.Height,
                options.MaxWidth,
                options.MaxHeight,
                options.FillWidth,
                options.FillHeight,
                quality,
                dateModified,
                outputFormat,
                options.AddPlayedIndicator,
                options.PercentPlayed,
                options.UnplayedCount,
                options.Blur,
                options.BackgroundColor,
                options.ForegroundLayer);

            try
            {
                if (!File.Exists(cacheFilePath))
                {
                    string resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, cacheFilePath, autoOrient, orientation, quality, options, outputFormat);

                    if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
                    {
                        return(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
                    }
                }

                return(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath));
            }
            catch (Exception ex)
            {
                // If it fails for whatever reason, return the original image
                _logger.LogError(ex, "Error encoding image");
                return(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified);
            }
        }
Exemplo n.º 22
0
        public async Task <Tuple <string, string, DateTime> > ProcessImage(ImageProcessingOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var        originalImage = options.Image;
            IHasImages 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;

            if (!_imageEncoder.SupportsImageEncoding)
            {
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            if (options.Enhancers.Count > 0)
            {
                if (item == null)
                {
                    item = _libraryManager().GetItemById(options.ItemId);
                }

                var tuple = await GetEnhancedImage(new ItemImageInfo
                {
                    DateModified = dateModified,
                    Type         = originalImage.Type,
                    Path         = originalImagePath
                }, item, options.ImageIndex, options.Enhancers).ConfigureAwait(false);

                originalImagePath = tuple.Item1;
                dateModified      = tuple.Item2;
            }

            if (options.HasDefaultOptions(originalImagePath))
            {
                // 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))
            {
                // Just spit out the original file if all the options are default
                _logger.Info("Returning original image {0}", originalImagePath);
                return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
            }

            var newSize = ImageHelper.GetNewImageSize(options, originalImageSize);
            var quality = options.Quality;

            var outputFormat  = GetOutputFormat(options.SupportedOutputFormats[0]);
            var cacheFilePath = GetCacheFilePath(originalImagePath, newSize, quality, dateModified, outputFormat, options.AddPlayedIndicator, options.PercentPlayed, options.UnplayedCount, options.Blur, options.BackgroundColor, options.ForegroundLayer);

            try
            {
                CheckDisposed();

                if (!_fileSystem.FileExists(cacheFilePath))
                {
                    _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath));
                    var tmpPath = Path.ChangeExtension(Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString("N")), Path.GetExtension(cacheFilePath));
                    _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath));

                    if (item == null && string.Equals(options.ItemType, typeof(Photo).Name, StringComparison.OrdinalIgnoreCase))
                    {
                        item = _libraryManager().GetItemById(options.ItemId);
                    }

                    var resultPath = _imageEncoder.EncodeImage(originalImagePath, dateModified, tmpPath, AutoOrient(item), quality, options, outputFormat);

                    if (string.Equals(resultPath, originalImagePath, StringComparison.OrdinalIgnoreCase))
                    {
                        return(new Tuple <string, string, DateTime>(originalImagePath, MimeTypes.GetMimeType(originalImagePath), dateModified));
                    }

                    CopyFile(tmpPath, cacheFilePath);

                    return(new Tuple <string, string, DateTime>(tmpPath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(tmpPath)));
                }

                return(new Tuple <string, string, DateTime>(cacheFilePath, GetMimeType(outputFormat, cacheFilePath), _fileSystem.GetLastWriteTimeUtc(cacheFilePath)));
            }
            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));
            }
        }
Exemplo n.º 23
0
        // sends a multipart mail to the server
        void SendMultipartMail(MailMessageWrapper msg)
        {
            // generate the boundary between attachments
            string boundary = MailUtil.GenerateBoundary();

            // set the Content-Type header to multipart/mixed
            string bodyContentType = msg.Header.ContentType;

            msg.Header.ContentType = String.Concat("multipart/mixed;\r\n   boundary=", boundary);

            // write the header
            smtp.WriteHeader(msg.Header);

            // write the first part text part
            // before the attachments
            smtp.WriteBoundary(boundary);

            MailHeader partHeader = new MailHeader();

            partHeader.ContentType = bodyContentType;

            // Add all the custom headers to body part as specified in
            //Fields property of MailMessageWrapper

            //Remove fields specific for authenticating to SMTP server.
            //Need to incorporate AUTH command in SmtpStream to handle
            //Authorization info. Its a temporary fix for Bug no 68829.
            //Will dig some more on SMTP AUTH command, and then implement
            //Authorization. - Sanjay

            if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] != null)
            {
                msg.Fields.Data.Remove("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate");
            }
            if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/sendusername"] != null)
            {
                msg.Fields.Data.Remove("http://schemas.microsoft.com/cdo/configuration/sendusername");
            }
            if (msg.Fields.Data ["http://schemas.microsoft.com/cdo/configuration/sendpassword"] != null)
            {
                msg.Fields.Data.Remove("http://schemas.microsoft.com/cdo/configuration/sendpassword");
            }
            partHeader.Data.Add(msg.Fields.Data);

            smtp.WriteHeader(partHeader);

            // FIXME: probably need to use QP or Base64 on everything higher
            // then 8-bit .. like utf-16
            smtp.WriteBytes(msg.BodyEncoding.GetBytes(msg.Body));

            smtp.WriteBoundary(boundary);

            // now start to write the attachments

            for (int i = 0; i < msg.Attachments.Count; i++)
            {
                MailAttachment a        = (MailAttachment)msg.Attachments[i];
                FileInfo       fileInfo = new FileInfo(a.Filename);
                MailHeader     aHeader  = new MailHeader();

                aHeader.ContentType =
                    String.Concat(MimeTypes.GetMimeType(fileInfo.Name), "; name=\"", fileInfo.Name, "\"");

                aHeader.ContentDisposition      = String.Concat("attachment; filename=\"", fileInfo.Name, "\"");
                aHeader.ContentTransferEncoding = a.Encoding.ToString();
                smtp.WriteHeader(aHeader);

                // perform the actual writing of the file.
                // read from the file stream and write to the tcp stream
                FileStream ins = fileInfo.OpenRead();

                // create an apropriate encoder
                IAttachmentEncoder encoder;
                if (a.Encoding == MailEncoding.UUEncode)
                {
                    encoder = new UUAttachmentEncoder(644, fileInfo.Name);
                }
                else
                {
                    encoder = new Base64AttachmentEncoder();
                }

                encoder.EncodeStream(ins, smtp.Stream);

                ins.Close();
                smtp.WriteLine("");

                // if it is the last attachment write
                // the final boundary otherwise write
                // a normal one.
                if (i < (msg.Attachments.Count - 1))
                {
                    smtp.WriteBoundary(boundary);
                }
                else
                {
                    smtp.WriteFinalBoundary(boundary);
                }
            }
        }
Exemplo n.º 24
0
        public CCAClientStack()
        {
            var resourceGroup = new ResourceGroup("cca-client", new ResourceGroupArgs {
                Location = "SouthIndia"
            });

            var storageAccount = new Account("ccasite", new AccountArgs
            {
                ResourceGroupName      = resourceGroup.Name,
                EnableHttpsTrafficOnly = true,
                AccountReplicationType = "LRS",
                AccountTier            = "Standard",
                AccountKind            = "StorageV2",
                StaticWebsite          = new AccountStaticWebsiteArgs
                {
                    IndexDocument = "index.html"
                }
            });

            var cdnProfile = new Profile("CCA-CDN", new ProfileArgs
            {
                Location          = resourceGroup.Location,
                ResourceGroupName = resourceGroup.Name,
                Sku = "Standard_Microsoft",
            });

            var cdnEndpoint = new Endpoint("cca", new EndpointArgs
            {
                Name              = "cca",
                ProfileName       = cdnProfile.Name,
                Location          = resourceGroup.Location,
                ResourceGroupName = resourceGroup.Name,
                OriginHostHeader  = storageAccount.PrimaryWebHost,
                Origins           =
                {
                    new EndpointOriginArgs
                    {
                        Name      = "ccasite",
                        HostName  = storageAccount.PrimaryWebHost,
                        HttpPort  = 80,
                        HttpsPort = 443
                    }
                },
                DeliveryRules =
                {
                    new EndpointDeliveryRuleArgs
                    {
                        Name  = "SPA",
                        Order = 1,
                        UrlFileExtensionConditions =
                        {
                            new EndpointDeliveryRuleUrlFileExtensionConditionArgs
                            {
                                Operator        = "LessThan",
                                NegateCondition = false,
                                MatchValues     =
                                {
                                    "1"
                                },
                            }
                        },
                        UrlRewriteAction = new EndpointDeliveryRuleUrlRewriteActionArgs
                        {
                            Destination           = "/index.html",
                            PreserveUnmatchedPath = false,
                            SourcePattern         = "/"
                        }
                    }
                }
            });

            foreach (var file in Directory.GetFiles("../client/build", "*", SearchOption.AllDirectories))
            {
                var relativePath = Path.GetRelativePath("../client/build", file);
                var fileName     = Path.GetFileName(file);

                _ = new Blob(relativePath, new BlobArgs
                {
                    Name = relativePath,
                    StorageAccountName   = storageAccount.Name,
                    StorageContainerName = "$web",
                    Type        = "Block",
                    Source      = new FileAsset(file),
                    ContentType = MimeTypes.GetMimeType(fileName),
                });
            }

            StaticEndpoint = storageAccount.PrimaryWebEndpoint;
            CdnEndpoint    = cdnEndpoint.HostName;
        }
Exemplo n.º 25
0
 /// <summary>
 /// Determines whether the specified <see cref="MimeTypes" /> is equal to the current
 /// <see cref="MimeTypes" />.
 /// </summary>
 /// <returns>
 /// <c>true</c> if the specified <see cref="MimeTypes" /> is equal to the current instance; otherwise,
 /// <c>false</c>.
 /// </returns>
 /// <param name="other">
 /// The <see cref="MimeTypes" /> to compare with the current instance.
 /// </param>
 public bool Equals(MimeTypes other)
 {
     return other != null && string.Equals(this.Value, other.Value);
 }
Exemplo n.º 26
0
 /// <summary>
 /// Creates new file result and finds MIME type from known mime types in twino
 /// </summary>
 public FileResult(Stream stream, string filename)
 {
     Code    = HttpStatusCode.OK;
     Headers = new Dictionary <string, string>();
     Set(stream, MimeTypes.GetMimeType(filename), filename);
 }
Exemplo n.º 27
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetDashboardConfigurationPage request)
        {
            var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));

            return(ResultFactory.GetStaticResult(RequestContext, page.Plugin.Version.ToString().GetMD5(), page.Plugin.AssemblyDateLastModified, null, MimeTypes.GetMimeType("page.html"), () => ModifyHtml(page.GetHtmlStream())));
        }
Exemplo n.º 28
0
        /// <summary>
        ///     Writes all the string and binary <see cref="Property">properties</see> as a <see cref="CFStream" /> to the
        ///     given <paramref name="storage" />
        /// </summary>
        /// <param name="storage">The <see cref="CFStorage" /></param>
        /// <param name="index">The <see cref="Attachment"/> index</param>
        /// <returns>
        ///     Total size of the written <see cref="Attachment"/> object and it's <see cref="Properties"/>
        /// </returns>
        internal long WriteProperties(CFStorage storage, int index)
        {
            var propertiesStream = new AttachmentProperties();

            // PR_ATTACHMENT_FLAGS
            // PR_ATTACHMENT_HIDDEN
            // PR_ATTACHMENT_LINKID
            // PR_ATTACH_ENCODING
            // PR_ATTACH_FLAGS
            // PR_ATTACH_MIME_TAG_W
            // PR_ATTACH_NUM-- > 1 ?
            // PR_OBJECT_TYPE

            propertiesStream.AddProperty(PropertyTags.PR_ATTACH_NUM, index, PropertyFlags.PROPATTR_READABLE);
            propertiesStream.AddProperty(PropertyTags.PR_INSTANCE_KEY, Mapi.GenerateInstanceKey(), PropertyFlags.PROPATTR_READABLE);
            propertiesStream.AddProperty(PropertyTags.PR_RECORD_KEY, Mapi.GenerateRecordKey(), PropertyFlags.PROPATTR_READABLE);
            propertiesStream.AddProperty(PropertyTags.PR_RENDERING_POSITION, RenderingPosition, PropertyFlags.PROPATTR_READABLE);

            if (!string.IsNullOrEmpty(FileName))
            {
                propertiesStream.AddProperty(PropertyTags.PR_DISPLAY_NAME_W, FileName);
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_FILENAME_W, GetShortFileName(FileName));
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_LONG_FILENAME_W, FileName);
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_EXTENSION_W, Path.GetExtension(FileName));

                if (!string.IsNullOrEmpty(ContentId))
                {
                    propertiesStream.AddProperty(PropertyTags.PR_ATTACH_CONTENT_ID_W, ContentId);
                }

                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_MIME_TAG_W, MimeTypes.GetMimeType(FileName));
            }

            propertiesStream.AddProperty(PropertyTags.PR_ATTACH_METHOD, Type);

            switch (Type)
            {
            case AttachmentType.ATTACH_BY_VALUE:
            case AttachmentType.ATTACH_EMBEDDED_MSG:
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_DATA_BIN, Stream.ToByteArray());
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_SIZE, Stream.Length);
                break;

            case AttachmentType.ATTACH_BY_REF_ONLY:
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_DATA_BIN, new byte[0]);
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_SIZE, _file.Length);
                propertiesStream.AddProperty(PropertyTags.PR_ATTACH_LONG_PATHNAME_W, _file.FullName);
                break;

            //case AttachmentType.ATTACH_EMBEDDED_MSG:
            //    var msgStorage = storage.AddStorage(PropertyTags.PR_ATTACH_DATA_BIN.Name);
            //    var cf = new CompoundFile(Stream);
            //    Storage.Copy(cf.RootStorage, msgStorage);
            //    propertiesStream.AddProperty(PropertyTags.PR_ATTACH_SIZE, Stream.Length);
            //    propertiesStream.AddProperty(PropertyTags.PR_ATTACH_ENCODING, 0);
            //    break;

            case AttachmentType.ATTACH_BY_REFERENCE:
            case AttachmentType.ATTACH_BY_REF_RESOLVE:
            case AttachmentType.NO_ATTACHMENT:
            case AttachmentType.ATTACH_OLE:
                throw new NotSupportedException("AttachByReference, AttachByRefResolve, NoAttachment and AttachOle are not supported");
            }

            if (IsInline)
            {
                propertiesStream.AddProperty(PropertyTags.PR_ATTACHMENT_HIDDEN, true);
            }

            var utcNow = DateTime.UtcNow;

            propertiesStream.AddProperty(PropertyTags.PR_CREATION_TIME, utcNow);
            propertiesStream.AddProperty(PropertyTags.PR_LAST_MODIFICATION_TIME, utcNow);
            propertiesStream.AddProperty(PropertyTags.PR_STORE_SUPPORT_MASK, StoreSupportMaskConst.StoreSupportMask, PropertyFlags.PROPATTR_READABLE);

            return(propertiesStream.WriteProperties(storage));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Gets the compatible save paths.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="type">The type.</param>
        /// <param name="imageIndex">Index of the image.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <returns>IEnumerable{System.String}.</returns>
        /// <exception cref="System.ArgumentNullException">imageIndex</exception>
        private string[] GetCompatibleSavePaths(BaseItem item, ImageType type, int?imageIndex, string mimeType)
        {
            var season = item as Season;

            var extension = MimeTypes.ToExtension(mimeType);

            // Backdrop paths
            if (type == ImageType.Backdrop)
            {
                if (!imageIndex.HasValue)
                {
                    throw new ArgumentNullException(nameof(imageIndex));
                }

                if (imageIndex.Value == 0)
                {
                    if (item.IsInMixedFolder)
                    {
                        return(new[] { GetSavePathForItemInMixedFolder(item, type, "fanart", extension) });
                    }

                    if (season != null && season.IndexNumber.HasValue)
                    {
                        var seriesFolder = season.SeriesPath;

                        var seasonMarker = season.IndexNumber.Value == 0
                                               ? "-specials"
                                               : season.IndexNumber.Value.ToString("00", UsCulture);

                        var imageFilename = "season" + seasonMarker + "-fanart" + extension;

                        return(new[] { Path.Combine(seriesFolder, imageFilename) });
                    }

                    return(new[]
                    {
                        Path.Combine(item.ContainingFolderPath, "fanart" + extension)
                    });
                }

                var outputIndex = imageIndex.Value;

                if (item.IsInMixedFolder)
                {
                    return(new[] { GetSavePathForItemInMixedFolder(item, type, "fanart" + outputIndex.ToString(UsCulture), extension) });
                }

                var extraFanartFilename = GetBackdropSaveFilename(item.GetImages(ImageType.Backdrop), "fanart", "fanart", outputIndex);

                var list = new List <string>
                {
                    Path.Combine(item.ContainingFolderPath, "extrafanart", extraFanartFilename + extension)
                };

                if (EnableExtraThumbsDuplication)
                {
                    list.Add(Path.Combine(item.ContainingFolderPath, "extrathumbs", "thumb" + outputIndex.ToString(UsCulture) + extension));
                }
                return(list.ToArray());
            }

            if (type == ImageType.Primary)
            {
                if (season != null && season.IndexNumber.HasValue)
                {
                    var seriesFolder = season.SeriesPath;

                    var seasonMarker = season.IndexNumber.Value == 0
                                           ? "-specials"
                                           : season.IndexNumber.Value.ToString("00", UsCulture);

                    var imageFilename = "season" + seasonMarker + "-poster" + extension;

                    return(new[] { Path.Combine(seriesFolder, imageFilename) });
                }

                if (item is Episode)
                {
                    var seasonFolder = _fileSystem.GetDirectoryName(item.Path);

                    var imageFilename = _fileSystem.GetFileNameWithoutExtension(item.Path) + "-thumb" + extension;

                    return(new[] { Path.Combine(seasonFolder, imageFilename) });
                }

                if (item.IsInMixedFolder || item is MusicVideo)
                {
                    return(new[] { GetSavePathForItemInMixedFolder(item, type, string.Empty, extension) });
                }

                if (item is MusicAlbum || item is MusicArtist)
                {
                    return(new[] { Path.Combine(item.ContainingFolderPath, "folder" + extension) });
                }

                return(new[] { Path.Combine(item.ContainingFolderPath, "poster" + extension) });
            }

            // All other paths are the same
            return(new[] { GetStandardSavePath(item, type, imageIndex, mimeType, true) });
        }
Exemplo n.º 30
0
        public async Task <FileStorage> UploadAsync(byte[] file, string filename)
        {
            string extension;

            if (filename.Contains("."))
            {
                extension = filename.Split('.').Last();
            }
            else
            {
                extension = "xxx";
            }

            #region Debugging
            // For create new folder
            //var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            //{
            //    Name = "ScienceDocument",
            //    MimeType = "application/vnd.google-apps.folder"
            //};
            //var request = _service.Files.Create(fileMetadata);
            //request.Fields = "id";
            //var newfolder = request.Execute();
            //Console.WriteLine("Folder ID: " + newfolder.Id);
            //var newfolderID = newfolder.Id;
            //var myPerm = new Permission()
            //{
            //    Type = "user",
            //    Role = "writer",
            //    EmailAddress = "*****@*****.**"
            //};
            //var newfolderID = "1-oS2zC5YYA75E1_RJR5zQLgiT6hyiMdt";
            //_service.Permissions.Create(myPerm, newfolderID).Execute();
            //

            //Folder List
            //FilesResource.ListRequest listRequest = _service.Files.List();
            //listRequest.Q = $"trashed=false and parents='{folderID}'";
            ////listRequest.Q = $"trashed=false and mimeType='application/vnd.google-apps.folder'";
            //listRequest.PageSize = 10;
            //listRequest.Fields = "nextPageToken, files";
            //IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;

            //foreach (var f in files)
            //{
            //    await DeleteAsync(f.Id, f.Name);
            //}

            #endregion
            try
            {
                var hash = BitConverter.ToString(CalculateHash(file)).Replace("-", "").ToLower();

                var listRequest = service.Files.List();
                listRequest.Q      = $"'{folderID}' in parents" + " and appProperties has { key = 'hash' and value='" + hash + "' }";
                listRequest.Fields = "nextPageToken, files(id, name, size)";
                var fileList = await listRequest.ExecuteAsync();

                if (fileList.Files.Count > 0)
                {
                    return new FileStorage()
                           {
                               FileId      = fileList.Files[0].Id,
                               FileName    = fileList.Files[0].Name,
                               FileType    = extension,
                               Description = filename,
                               Size        = fileList.Files[0].Size.GetValueOrDefault(),
                               Hash        = hash,
                               Plan        = "google"
                           }
                }
                ;

                var metaData = new Dictionary <string, string>();
                metaData.Add("hash", hash);
                using (MemoryStream s1 = new MemoryStream(file))
                {
                    var uuidName = Guid.NewGuid().ToString() + "." + extension;

                    var uploadRequest = service.Files.Create(new Google.Apis.Drive.v3.Data.File()
                    {
                        Name    = uuidName,
                        Parents = new List <string> {
                            folderID
                        },
                        CopyRequiresWriterPermission = true,
                        AppProperties = metaData,
                        Description   = filename
                    }, s1, MimeTypes.GetMimeType(uuidName));

                    uploadRequest.Fields = "id,name,size,mimeType,createdTime,webContentLink,webViewLink,size,mimeType,modifiedTime,description,appProperties";
                    await uploadRequest.UploadAsync();

                    var uploadedFile = uploadRequest.ResponseBody;
                    await service.Permissions.Create(allAccess, uploadedFile.Id).ExecuteAsync();

                    return(new FileStorage()
                    {
                        FileId = uploadedFile.Id,
                        FileName = uploadedFile.Name,
                        Description = uploadedFile.Description,
                        FileType = extension,
                        Size = file.Length,
                        Hash = uploadedFile.AppProperties["hash"],
                        Plan = "google",
                    });
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                if (e.InnerException != null)
                {
                    Debug.WriteLine(e.InnerException.Message);
                }
                throw;
            }
        }
Exemplo n.º 31
0
 public FileResponse(string filePath, Context context)
     : this(filePath, MimeTypes.GetMimeType(filePath), context)
 {
 }
Exemplo n.º 32
0
        private void AddAudioResource(XmlElement container, Audio audio, string deviceId, Filter filter)
        {
            var res = container.OwnerDocument.CreateElement(string.Empty, "res", NS_DIDL);

            var sources = _dtoService.GetMediaSources(audio);

            var streamInfo = new StreamBuilder().BuildAudioItem(new AudioOptions
            {
                ItemId       = audio.Id.ToString("N"),
                MediaSources = sources,
                Profile      = _profile,
                DeviceId     = deviceId
            });

            var url = streamInfo.ToDlnaUrl(_serverAddress);

            //res.AppendChild(container.OwnerDocument.CreateCDataSection(url));
            res.InnerText = url;

            var mediaSource = sources.First(i => string.Equals(i.Id, streamInfo.MediaSourceId));

            if (mediaSource.RunTimeTicks.HasValue)
            {
                res.SetAttribute("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", _usCulture));
            }

            if (filter.Contains("res@size"))
            {
                if (streamInfo.IsDirectStream || streamInfo.EstimateContentLength)
                {
                    var size = streamInfo.TargetSize;

                    if (size.HasValue)
                    {
                        res.SetAttribute("size", size.Value.ToString(_usCulture));
                    }
                }
            }

            var targetAudioBitrate = streamInfo.TargetAudioBitrate;
            var targetSampleRate   = streamInfo.TargetAudioSampleRate;
            var targetChannels     = streamInfo.TargetAudioChannels;

            if (targetChannels.HasValue)
            {
                res.SetAttribute("nrAudioChannels", targetChannels.Value.ToString(_usCulture));
            }

            if (targetSampleRate.HasValue)
            {
                res.SetAttribute("sampleFrequency", targetSampleRate.Value.ToString(_usCulture));
            }

            if (targetAudioBitrate.HasValue)
            {
                res.SetAttribute("bitrate", targetAudioBitrate.Value.ToString(_usCulture));
            }

            var mediaProfile = _profile.GetAudioMediaProfile(streamInfo.Container,
                                                             streamInfo.AudioCodec,
                                                             targetChannels,
                                                             targetAudioBitrate);

            var filename = url.Substring(0, url.IndexOf('?'));

            var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
                ? MimeTypes.GetMimeType(filename)
                : mediaProfile.MimeType;

            var contentFeatures = new ContentFeatureBuilder(_profile).BuildAudioHeader(streamInfo.Container,
                                                                                       streamInfo.TargetAudioCodec,
                                                                                       targetAudioBitrate,
                                                                                       targetSampleRate,
                                                                                       targetChannels,
                                                                                       streamInfo.IsDirectStream,
                                                                                       streamInfo.RunTimeTicks,
                                                                                       streamInfo.TranscodeSeekInfo);

            res.SetAttribute("protocolInfo", String.Format(
                                 "http-get:*:{0}:{1}",
                                 mimeType,
                                 contentFeatures
                                 ));

            container.AppendChild(res);
        }
Exemplo n.º 33
0
        private void AddAudioResource(DlnaOptions options, XmlWriter writer, BaseItem audio, string deviceId, Filter filter, StreamInfo streamInfo = null)
        {
            writer.WriteStartElement(string.Empty, "res", NS_DIDL);

            if (streamInfo == null)
            {
                var sources = _mediaSourceManager.GetStaticMediaSources(audio, true, _user);

                streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions
                {
                    ItemId       = audio.Id,
                    MediaSources = sources.ToArray(),
                    Profile      = _profile,
                    DeviceId     = deviceId
                });
            }

            var url = NormalizeDlnaMediaUrl(streamInfo.ToUrl(_serverAddress, _accessToken));

            var mediaSource = streamInfo.MediaSource;

            if (mediaSource.RunTimeTicks.HasValue)
            {
                writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", _usCulture));
            }

            if (filter.Contains("res@size"))
            {
                if (streamInfo.IsDirectStream || streamInfo.EstimateContentLength)
                {
                    var size = streamInfo.TargetSize;

                    if (size.HasValue)
                    {
                        writer.WriteAttributeString("size", size.Value.ToString(_usCulture));
                    }
                }
            }

            var targetAudioBitrate  = streamInfo.TargetAudioBitrate;
            var targetSampleRate    = streamInfo.TargetAudioSampleRate;
            var targetChannels      = streamInfo.TargetAudioChannels;
            var targetAudioBitDepth = streamInfo.TargetAudioBitDepth;

            if (targetChannels.HasValue)
            {
                writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(_usCulture));
            }

            if (targetSampleRate.HasValue)
            {
                writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(_usCulture));
            }

            if (targetAudioBitrate.HasValue)
            {
                writer.WriteAttributeString("bitrate", targetAudioBitrate.Value.ToString(_usCulture));
            }

            var mediaProfile = _profile.GetAudioMediaProfile(streamInfo.Container,
                                                             streamInfo.TargetAudioCodec.FirstOrDefault(),
                                                             targetChannels,
                                                             targetAudioBitrate,
                                                             targetSampleRate,
                                                             targetAudioBitDepth);

            var filename = url.Substring(0, url.IndexOf('?'));

            var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
                ? MimeTypes.GetMimeType(filename)
                : mediaProfile.MimeType;

            var contentFeatures = new ContentFeatureBuilder(_profile).BuildAudioHeader(streamInfo.Container,
                                                                                       streamInfo.TargetAudioCodec.FirstOrDefault(),
                                                                                       targetAudioBitrate,
                                                                                       targetSampleRate,
                                                                                       targetChannels,
                                                                                       targetAudioBitDepth,
                                                                                       streamInfo.IsDirectStream,
                                                                                       streamInfo.RunTimeTicks ?? 0,
                                                                                       streamInfo.TranscodeSeekInfo);

            writer.WriteAttributeString("protocolInfo", string.Format(
                                            "http-get:*:{0}:{1}",
                                            mimeType,
                                            contentFeatures
                                            ));

            writer.WriteString(url);

            writer.WriteFullEndElement();
        }
Exemplo n.º 34
0
        private async Task ProcessUrl(FileDownloadManagerContext context, HttpClient client, FileDownloadManagerItem item)
        {
            try
            {
                var count    = 0;
                var canceled = false;
                var bytes    = new byte[_bufferSize];

                using (var response = await client.GetAsync(item.Url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        if (response.Content.Headers.ContentType != null)
                        {
                            var contentType = response.Content.Headers.ContentType.MediaType;
                            if (contentType.HasValue() && !contentType.IsCaseInsensitiveEqual(item.MimeType))
                            {
                                // Update mime type and local path.
                                var extension = MimeTypes.MapMimeTypeToExtension(contentType).NullEmpty() ?? ".jpg";

                                item.MimeType = contentType;
                                item.Path     = Path.ChangeExtension(item.Path, extension.EnsureStartsWith("."));
                            }
                        }

                        //Task <Stream> task = client.GetStreamAsync(item.Url);
                        Task <Stream> task = response.Content.ReadAsStreamAsync();
                        await         task;

                        using (var srcStream = task.Result)
                            using (var dstStream = File.Open(item.Path, FileMode.Create))
                            {
                                while ((count = srcStream.Read(bytes, 0, bytes.Length)) != 0 && !canceled)
                                {
                                    dstStream.Write(bytes, 0, count);

                                    if (context.CancellationToken != null && context.CancellationToken.IsCancellationRequested)
                                    {
                                        canceled = true;
                                    }
                                }
                            }

                        item.Success = !task.IsFaulted && !canceled;
                    }
                    else
                    {
                        item.Success      = false;
                        item.ErrorMessage = response.StatusCode.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    item.Success      = false;
                    item.ErrorMessage = ex.ToAllMessages();

                    var webExc = ex.InnerException as WebException;
                    if (webExc != null)
                    {
                        item.ExceptionStatus = webExc.Status;
                    }

                    if (context.Logger != null)
                    {
                        context.Logger.Error(ex, item.ToString());
                    }
                }
                catch { }
            }
        }
Exemplo n.º 35
0
        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));
        }
Exemplo n.º 36
0
        /// <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 isJs       = false;
            var isTemplate = false;

            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);

                    isJs       = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase);
                    isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html");
                }
            }

            if (plugin != null && stream != null)
            {
                if (isJs)
                {
                    return(_resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.js"), () => Task.FromResult(stream)));
                }
                if (isTemplate)
                {
                    return(_resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => Task.FromResult(stream)));
                }

                return(_resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator(DashboardUIPath).ModifyHtml("dummy.html", stream, null, _appHost.ApplicationVersion, null)));
            }

            throw new ResourceNotFoundException();
        }
Exemplo n.º 37
0
		private MimeType[] GetAcceptedTypes(MimeTypes registeredMimes)
		{
			var mimeTypes = new List<MimeType>();
			var originalUrl = Request.Uri.GetLeftPart(UriPartial.Authority) + Request.Url;
			var lastSegment = new Uri(originalUrl).Segments.Last();
			
			if (lastSegment.Contains(".") && (lastSegment.LastIndexOf(".") < lastSegment.Length - 1))
			{
				var extension = lastSegment.Substring(lastSegment.LastIndexOf(".") + 1);
				var mimeType = registeredMimes.GetMimeTypeForExtension(extension);

				if (mimeType != null)
					mimeTypes.Add(mimeType);
			}

			mimeTypes.AddRange(AcceptType.Parse(AcceptHeader, registeredMimes));			
			
			return mimeTypes.Distinct().ToArray();
		}
Exemplo n.º 38
0
        public async Task <ActionResult> GetLiveHlsStream(
            [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,
            [FromQuery] int?maxWidth,
            [FromQuery] int?maxHeight,
            [FromQuery] bool?enableSubtitlesInManifest)
        {
            VideoRequestDto 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,
                MaxHeight                   = maxHeight,
                MaxWidth                    = maxWidth,
                EnableSubtitlesInManifest   = enableSubtitlesInManifest ?? true
            };

            // CTS lifecycle is managed internally.
            var cancellationTokenSource = new CancellationTokenSource();

            using var state = await StreamingHelpers.GetStreamingState(
                      streamingRequest,
                      Request,
                      _authContext,
                      _mediaSourceManager,
                      _userManager,
                      _libraryManager,
                      _serverConfigurationManager,
                      _mediaEncoder,
                      _encodingHelper,
                      _dlnaManager,
                      _deviceManager,
                      _transcodingJobHelper,
                      TranscodingJobType,
                      cancellationTokenSource.Token)
                              .ConfigureAwait(false);

            TranscodingJobDto?job = null;
            var playlistPath      = Path.ChangeExtension(state.OutputFilePath, ".m3u8");

            if (!System.IO.File.Exists(playlistPath))
            {
                var transcodingLock = _transcodingJobHelper.GetTranscodingLock(playlistPath);
                await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);

                try
                {
                    if (!System.IO.File.Exists(playlistPath))
                    {
                        // If the playlist doesn't already exist, startup ffmpeg
                        try
                        {
                            job = await _transcodingJobHelper.StartFfMpeg(
                                state,
                                playlistPath,
                                GetCommandLineArguments(playlistPath, state),
                                Request,
                                TranscodingJobType,
                                cancellationTokenSource)
                                  .ConfigureAwait(false);

                            job.IsLiveOutput = true;
                        }
                        catch
                        {
                            state.Dispose();
                            throw;
                        }

                        minSegments = state.MinSegments;
                        if (minSegments > 0)
                        {
                            await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationTokenSource.Token).ConfigureAwait(false);
                        }
                    }
                }
                finally
                {
                    transcodingLock.Release();
                }
            }

            job ??= _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);

            if (job != null)
            {
                _transcodingJobHelper.OnTranscodeEndRequest(job);
            }

            var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state);

            return(Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8")));
        }
Exemplo n.º 39
0
        /// <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;
            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);

                await new ProgressiveFileCopier(state.DirectStreamProvider, null, _transcodingJobHelper, CancellationToken.None)
                {
                    AllowEndOfFile = false
                }.WriteToAsync(_httpContextAccessor.HttpContext.Response.Body, CancellationToken.None)
                .ConfigureAwait(false);

                // TODO (moved from MediaBrowser.Api): Don't hardcode contentType
                return(new FileStreamResult(_httpContextAccessor.HttpContext.Response.Body, 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 = System.IO.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)
                {
                    await new ProgressiveFileCopier(state.MediaPath, null, _transcodingJobHelper, CancellationToken.None)
                    {
                        AllowEndOfFile = false
                    }.WriteToAsync(_httpContextAccessor.HttpContext.Response.Body, CancellationToken.None)
                    .ConfigureAwait(false);

                    return(new FileStreamResult(_httpContextAccessor.HttpContext.Response.Body, 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));
        }
Exemplo n.º 40
0
        public async Task <ActionResult> GetAudioStream(
            [FromRoute] Guid itemId,
            [FromRoute] 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?transcodingReasons,
            [FromQuery] int?audioStreamIndex,
            [FromQuery] int?videoStreamIndex,
            [FromQuery] EncodingContext?context,
            [FromQuery] Dictionary <string, string>?streamOptions)
        {
            bool isHeadRequest = Request.Method == System.Net.WebRequestMethods.Http.Head;

            var cancellationTokenSource = new CancellationTokenSource();

            StreamingRequestDto streamingRequest = new StreamingRequestDto
            {
                Id                          = itemId,
                Container                   = container,
                Static                      = @static ?? true,
                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 ?? true,
                StartTimeTicks              = startTimeTicks,
                Width                       = width,
                Height                      = height,
                VideoBitRate                = videoBitRate,
                SubtitleStreamIndex         = subtitleStreamIndex,
                SubtitleMethod              = subtitleMethod,
                MaxRefFrames                = maxRefFrames,
                MaxVideoBitDepth            = maxVideoBitDepth,
                RequireAvc                  = requireAvc ?? true,
                DeInterlace                 = deInterlace ?? true,
                RequireNonAnamorphic        = requireNonAnamorphic ?? true,
                TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
                CpuCoreLimit                = cpuCoreLimit,
                LiveStreamId                = liveStreamId,
                EnableMpegtsM2TsMode        = enableMpegtsM2TsMode ?? true,
                VideoCodec                  = videoCodec,
                SubtitleCodec               = subtitleCodec,
                TranscodeReasons            = transcodingReasons,
                AudioStreamIndex            = audioStreamIndex,
                VideoStreamIndex            = videoStreamIndex,
                Context                     = context ?? EncodingContext.Static,
                StreamOptions               = streamOptions
            };

            using var state = await StreamingHelpers.GetStreamingState(
                      streamingRequest,
                      Request,
                      _authContext,
                      _mediaSourceManager,
                      _userManager,
                      _libraryManager,
                      _serverConfigurationManager,
                      _mediaEncoder,
                      _fileSystem,
                      _subtitleEncoder,
                      _configuration,
                      _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();
                return(await FileStreamResponseHelpers.GetStaticRemoteStreamResult(state, isHeadRequest, this, httpClient).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,
                           this));
            }

            // Need to start ffmpeg (because media can't be returned directly)
            var encodingOptions            = _serverConfigurationManager.GetEncodingOptions();
            var encodingHelper             = new EncodingHelper(_mediaEncoder, _fileSystem, _subtitleEncoder, _configuration);
            var ffmpegCommandLineArguments = encodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, outputPath);

            return(await FileStreamResponseHelpers.GetTranscodedFile(
                       state,
                       isHeadRequest,
                       this,
                       _transcodingJobHelper,
                       ffmpegCommandLineArguments,
                       Request,
                       _transcodingJobType,
                       cancellationTokenSource).ConfigureAwait(false));
        }
Exemplo n.º 41
0
 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";
 }
Exemplo n.º 42
0
 public IActionResult DownloadFile(string filePath)
 {
     return(PhysicalFile(filePath, MimeTypes.GetMimeType(filePath), Path.GetFileName(filePath)));
 }
Exemplo n.º 43
0
        /// <summary>
        /// Refreshes from provider.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="refreshOptions">The refresh options.</param>
        /// <param name="savedOptions">The saved options.</param>
        /// <param name="downloadedImages">The downloaded images.</param>
        /// <param name="result">The result.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private async Task RefreshFromProvider(IHasImages item,
                                               IDynamicImageProvider provider,
                                               ImageRefreshOptions refreshOptions,
                                               MetadataOptions savedOptions,
                                               ICollection <ImageType> downloadedImages,
                                               RefreshResult result,
                                               CancellationToken cancellationToken)
        {
            try
            {
                var images = provider.GetSupportedImages(item);

                foreach (var imageType in images)
                {
                    if (!IsEnabled(savedOptions, imageType, item))
                    {
                        continue;
                    }

                    if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
                    {
                        _logger.Debug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);

                        var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false);

                        if (response.HasImage)
                        {
                            if (!string.IsNullOrEmpty(response.Path))
                            {
                                if (response.Protocol == MediaProtocol.Http)
                                {
                                    _logger.Debug("Setting image url into item {0}", item.Id);
                                    item.SetImage(new ItemImageInfo
                                    {
                                        Path = response.Path,
                                        Type = imageType
                                    }, 0);
                                }
                                else
                                {
                                    var mimeType = MimeTypes.GetMimeType(response.Path);

                                    var stream = _fileSystem.GetFileStream(response.Path, FileMode.Open, FileAccess.Read, FileShare.Read, true);

                                    await _providerManager.SaveImage(item, stream, mimeType, imageType, null, response.InternalCacheKey, cancellationToken).ConfigureAwait(false);
                                }
                            }
                            else
                            {
                                var mimeType = "image/" + response.Format.ToString().ToLower();

                                await _providerManager.SaveImage(item, response.Stream, mimeType, imageType, null, response.InternalCacheKey, cancellationToken).ConfigureAwait(false);
                            }

                            downloadedImages.Add(imageType);
                            result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                _logger.ErrorException("Error in {0}", ex, provider.Name);
            }
        }
Exemplo n.º 44
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "train/{profileName}/{typeName?}")] HttpRequest req,
            string profileName,
            string typeName,
            ILogger logger)
        {
            var profile = ProfileFactory.Get(profileName);

            if (profile == null)
            {
                return(new NotFoundResult());
            }

            var profileParser = ParserFactory.GetParser(profile.Type, logger);

            if (profileParser == null)
            {
                logger.LogWarning($"Profile parser for {profile.Type.ToString()} is not implemented!");
                return(new NotFoundResult());
            }

            IProfileParser targetProfileParser = ParserFactory.GetParser(typeName ?? "", logger);

            if (targetProfileParser == null)
            {
                var userAgent    = req.Headers["user-agent"];
                var probableType = GuessTypeFromUserAgent(userAgent);
                targetProfileParser = ParserFactory.GetParser(probableType, logger);
                logger.LogInformation("Attempt to guess target type from user agent, UserAgent={userAgent}, Result={targetType}", userAgent, targetProfileParser.GetType());
            }

            string newProfile;
            var    profileContent = await profile.Download();

            var fileName = $"{profileName}{targetProfileParser.ExtName()}";

            if (profile.AllowDirectAccess && profileParser.GetType() == targetProfileParser.GetType())
            {
                newProfile = profileContent;
            }
            else
            {
                var servers = profileParser.Parse(profileContent);
                logger.LogInformation($"Download profile `{profile.Name}` and get {servers.Length} servers");

                foreach (var filter in profile.Filters)
                {
                    var previousCount = servers.Length;
                    servers = filter.Do(servers);
                    logger.LogInformation($"Performed filter `{filter.GetType()}`, result: {servers.Length} servers");
                    if (servers.Length == 0)
                    {
                        break;
                    }
                }

                IEncodeOptions options = null;
                switch (targetProfileParser)
                {
                case SurgeParser surgeParser:
                    var surgeOptions = new SurgeEncodeOptions();
                    surgeOptions.ProfileURL = GetCurrentURL(req);
                    options = surgeOptions;
                    break;

                case ClashParser clashParser:
                    var clashOptions = new ClashEncodeOptions();
                    clashOptions.EnhancedMode = req.Query.ContainsKey("enhanced-mode") ? req.Query["enhanced-mode"].ToString() : "";
                    options = clashOptions;
                    break;
                }

                newProfile = targetProfileParser.Encode(servers, options);
            }

            var result = new FileContentResult(Encoding.UTF8.GetBytes(newProfile), $"{MimeTypes.GetMimeType(fileName)}; charset=UTF-8");

            result.FileDownloadName = fileName;
            return(result);
        }