示例#1
0
        public string ImageFullUrl()
        {
            string retValue = "";

            if (!string.IsNullOrEmpty(RemoteImage))
            {
                if (RemoteImage.ToLower().Contains("http"))
                {
                    retValue = RemoteImage;
                }
                else
                {
                    if (string.IsNullOrEmpty(Modifier))
                    {
                        retValue = string.Format("{0}/{1}", SiteSettings.RemoteImageUrl, RemoteImage);
                    }
                    else
                    {
                        if (Modifier.StartsWith("?"))
                        {
                            retValue = string.Format("{0}/{1}{2}", SiteSettings.RemoteImageUrl, RemoteImage, Modifier);
                        }
                        else
                        {
                            retValue = string.Format("{0}/{1}?{2}", SiteSettings.RemoteImageUrl, RemoteImage, Modifier);
                        }
                    }
                }
            }
            else
            {
                retValue = LocalImageFullUrl();
            }
            return(retValue);
        }
示例#2
0
        public async Task <string> Delete(RemoteImage remoteImage)
        {
            _db.RemoteImages.Remove(remoteImage);
            await _db.SaveChangesAsync();

            return("success");
        }
示例#3
0
        public async Task <int> Add(RemoteImage remoteImage)
        {
            await _db.RemoteImages.AddAsync(remoteImage);

            await _db.SaveChangesAsync();

            return(remoteImage.Id);
        }
        public static Microsoft.MediaCenter.UI.Image GetMediaInfoImage(string name)
        {
            if (name.EndsWith("_"))
            {
                return(null);                    //blank codec or other type
            }
            name = name.ToLower().Replace("-", "_");
            name = name.Replace('/', '-');
            Guid id = ("MiImage" + Config.Instance.ViewTheme + name).GetMD5();

            //try to load from image cache first
            string path = CustomImageCache.Instance.GetImagePath(id, true);

            if (path != null)
            {
                return(new Image(path));              //was already cached
            }
            //not cached - get it from the server
            path = Kernel.ApiClient.GetMediaInfoImageUrl(name, Config.Instance.ViewTheme, new ImageOptions());
            var serverImage = new RemoteImage {
                Path = path
            };

            try
            {
                var image = serverImage.DownloadImage();
                Logger.ReportVerbose("===CustomImage " + path + " being cached on first access.  Shouldn't have to do this again...");
                //cache it and return resulting cached image
                return(new Image("file://" + CustomImageCache.Instance.CacheImage(id, image)));
            }
            catch (WebException)
            {
                //not there, get it from resources in default or the current theme if it exists
                string resourceRef = "resx://MediaBrowser/MediaBrowser.Resources/";
                //Logger.ReportInfo("============== Current Theme: " + Application.CurrentInstance.CurrentTheme.Name);
                System.Reflection.Assembly assembly = Kernel.Instance.FindPluginAssembly(Application.CurrentInstance.CurrentTheme.Name);
                if (assembly != null)
                {
                    //Logger.ReportInfo("============== Found Assembly. ");
                    if (assembly.GetManifestResourceInfo(name) != null)
                    {
                        //Logger.ReportInfo("============== Found Resource: " + name);
                        //cheap way to grab a valid reference to the current themes resources...
                        resourceRef = Application.CurrentInstance.CurrentTheme.PageArea.Substring(0, Application.CurrentInstance.CurrentTheme.PageArea.LastIndexOf("/") + 1);
                    }
                }
                //cache it
                Logger.ReportVerbose("===CustomImage " + resourceRef + name + " being cached on first access.  Should only have to do this once per session...");
                CustomImageCache.Instance.CacheResource(id, resourceRef + name);
                return(new Image(resourceRef + name));
            }
        }
示例#5
0
        public async Task SendActiveImage()
        {
            var context = ControllerContext.HttpContext;

            if (context.WebSockets.IsWebSocketRequest)
            {
                WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();

                var activeImage = await _remoteImages.GetActiveImage();

                int?lastId = -1;
                do
                {
                    activeImage = await _remoteImages.GetActiveImage();

                    if (activeImage == null && lastId != null)
                    {
                        var blackout = new RemoteImage {
                            Id = -1
                        };
                        var bytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(blackout, Formatting.None, new JsonSerializerSettings {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        }));
                        var arraySegment = new ArraySegment <byte>(bytes);
                        await socket.SendAsync(arraySegment, WebSocketMessageType.Text, true, CancellationToken.None);

                        lastId = null;
                    }
                    else if (activeImage?.Id != lastId)
                    {
                        var bytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(activeImage, Formatting.None, new JsonSerializerSettings {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        }));
                        var arraySegment = new ArraySegment <byte>(bytes);
                        await socket.SendAsync(arraySegment, WebSocketMessageType.Text, true, CancellationToken.None);

                        lastId = activeImage?.Id;
                    }
                    Thread.Sleep(500);
                }while (socket.State == WebSocketState.Open);
            }
            else
            {
                context.Response.StatusCode = 400;
            }
        }
示例#6
0
        public async Task <Image> AddRemote(RemoteImage remoteImage)
        {
            var image = new Image
            {
                Name         = remoteImage.DisplayName,
                RemoteHash   = remoteImage.SHA256Hash,
                Type         = ServerType.Vanilla, //TODO: Remove property?
                SupportsMods = !string.IsNullOrEmpty(remoteImage.ModDirectory),
                ModDirectory = remoteImage.ModDirectory ?? "",
                BuildStatus  = null
            };

            await _context.Images.AddAsync(image);

            await _context.SaveChangesAsync();

            return(image);
        }
示例#7
0
        public static string FetchAndSaveImage(string source, string dest)
        {
            RemoteImage img = new RemoteImage()
            {
                Path = source
            };
            string ext = Path.GetExtension(source).ToLower();
            string fn  = dest + ext;

            try
            {
                img.DownloadImage().Save(fn, ext == ".png" ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg);
                return(fn);
            }
            catch (Exception e)
            {
                Logger.ReportException("Error downloading and saving image " + fn, e);
                return(null);
            }
        }
示例#8
0
        public void OnOpenFileForRemoteImageCollection()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Filter = "csv files (*.csv)|*.csv";
            fileDialog.ShowDialog();
            if (fileDialog.CheckFileExists && fileDialog.FileName != "")
            {
                try
                {
                    var remoteImages = RemoteImage.ReadRemoteImagesFromFile(fileDialog.FileName);
                    remoteImages.ForEach((remoteImage) =>
                    {
                        RemoteImageCollection.Add(remoteImage);
                    });
                }
                catch
                {
                    MessageBox.Show("Помилка CSV файлу, будь ласка, перевірте CSV файл!", "Перевірте CSV файл");
                }
            }
        }
示例#9
0
        public void OnOpenFileForRemoteImageCollection()
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Filter = "csv files (*.csv)|*.csv";
            fileDialog.ShowDialog();
            if (fileDialog.CheckFileExists && fileDialog.FileName != "")
            {
                try
                {
                    var remoteImages = RemoteImage.ReadRemoteImagesFromFile(fileDialog.FileName);
                    remoteImages.ForEach((remoteImage) =>
                    {
                        RemoteImageCollection.Add(remoteImage);
                    });
                }
                catch
                {
                    MessageBox.Show("CSV File Error, Please Check the CSV File for Errors!", "Check CSV");
                }
            }
        }
        protected virtual string DownloadAndSaveImage(string source, string targetPath, string targetName)
        {
            //download and save locally
            RemoteImage img = new RemoteImage()
            {
                Path = source
            };
            string ext = Path.GetExtension(source).ToLower();
            string fn  = (Path.Combine(targetPath, targetName + ext));

            try
            {
                Kernel.IgnoreFileSystemMods = true;
                img.DownloadImage().Save(fn, ext == ".png" ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg);
                Kernel.IgnoreFileSystemMods = false;
                return(fn);
            }
            catch (Exception e)
            {
                Logger.ReportException("Error downloading and saving image " + fn, e);
                return(null);
            }
        }
示例#11
0
    static Task <int> Main()
    {
        return(Deployment.RunAsync(() =>
        {
            // Get a reference to the remote image "nginx:1.15.6". Without specifying the repository, the Docker provider will
            // try to download it from the public Docker Hub.
            var remoteImage = new RemoteImage("nginx-image", new RemoteImageArgs
            {
                Name = "nginx:1.15.6",
                KeepLocally = true, // don't delete the image from the local cache when deleting this resource
            });

            // Launch a container using the nginx image we just downloaded.
            var container = new Container("nginx", new ContainerArgs
            {
                Image = remoteImage.Name,
                Ports =
                {
                    new ContainerPortsArgs
                    {
                        Internal = 80,
                        // external: defaults to an open ephemeral port
                        // protocol: defaults to TCP
                        // ip: defaults to 0.0.0.0
                    },
                },
            });

            var endpoints = container.Ports.Apply(ports => $"{ports![0].Ip}:{ports![0].External}");
            return new Dictionary <string, object?>
            {
                // Since the container is auto-named, export the name.
                { "name", container.Name },
                // Since the provider picked a random ephemeral port for this container, export the endpoint.
                { "endpoints", endpoints },
            };
        }));
示例#12
0
        public async Task <RemoteImage> UploadImage(IFormFile file)
        {
            if (file.Length > 0 && file.Length < MAX_FILE_SIZE)
            {
                var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (string.IsNullOrEmpty(ext) || !PERMITTED_EXTENSIONS.Contains(ext))
                {
                    throw new ArgumentException("File's extension is not allowed");
                }
                using (var reader = new BinaryReader(file.OpenReadStream()))
                {
                    var signatures  = FILE_SIGNATURES[ext];
                    var headerBytes = reader.ReadBytes(signatures.Max(m => m.Length));

                    if (!signatures.Any(signature =>
                                        headerBytes.Take(signature.Length).SequenceEqual(signature)))
                    {
                        throw new ArgumentException("File's signature is an not allowed");
                    }
                }
                var remoteImage = new RemoteImage();
                using (var ms = new MemoryStream())
                {
                    file.CopyTo(ms);
                    remoteImage.Data      = ms.ToArray();
                    remoteImage.Extension = ext.TrimStart('.');
                    remoteImage.IsActive  = false;
                    await _remoteImages.Add(remoteImage);
                }
                return(remoteImage);
            }
            else
            {
                throw new ArgumentException("File's size is not allowed (probably too big)");
            }
        }
示例#13
0
 public async Task InsertImageAsync(RemoteImage item)
 {
     await _db.InsertOrReplaceAsync(item);
 }
示例#14
0
        protected virtual void ProcessDocument(XmlDocument doc, bool ignoreImages)
        {
            Movie movie = Item as Movie;

            if (doc != null)
            {
                // This is problematic for foreign films we want to keep the alt title.
                //if (store.Name == null)
                //    store.Name = doc.SafeGetString("//movie/title");

                movie.Name = doc.SafeGetString("//movie/name");

                movie.Overview = doc.SafeGetString("//movie/overview");
                if (movie.Overview != null)
                {
                    movie.Overview = movie.Overview.Replace("\n\n", "\n");
                }

                movie.TagLine = doc.SafeGetString("//movie/tagline");
                movie.ImdbID  = doc.SafeGetString("//movie/imdb_id");

                movie.ImdbRating = doc.SafeGetSingle("//movie/rating", -1, 10);

                string release = doc.SafeGetString("//movie/released");
                if (!string.IsNullOrEmpty(release))
                {
                    movie.ProductionYear = Int32.Parse(release.Substring(0, 4));
                }

                movie.RunningTime = doc.SafeGetInt32("//movie/runtime");
                if (movie.MediaInfo != null && movie.MediaInfo.RunTime > 0)
                {
                    movie.RunningTime = movie.MediaInfo.RunTime;
                }

                movie.MpaaRating = doc.SafeGetString("//movie/certification");

                movie.Studios = null;
                foreach (XmlNode n in doc.SelectNodes("//studios/studio"))
                {
                    if (movie.Studios == null)
                    {
                        movie.Studios = new List <string>();
                    }
                    string name = n.SafeGetString("@name");
                    if (!string.IsNullOrEmpty(name))
                    {
                        movie.Studios.Add(name);
                    }
                }

                movie.Directors = null;
                foreach (XmlNode n in doc.SelectNodes("//cast/person[@job='Director']"))
                {
                    if (movie.Directors == null)
                    {
                        movie.Directors = new List <string>();
                    }
                    string name = n.SafeGetString("@name");
                    if (!string.IsNullOrEmpty(name))
                    {
                        movie.Directors.Add(name);
                    }
                }

                movie.Writers = null;
                foreach (XmlNode n in doc.SelectNodes("//cast/person[@job='Author']"))
                {
                    if (movie.Writers == null)
                    {
                        movie.Writers = new List <string>();
                    }
                    string name = n.SafeGetString("@name");
                    if (!string.IsNullOrEmpty(name))
                    {
                        movie.Writers.Add(name);
                    }
                }


                movie.Actors = null;
                foreach (XmlNode n in doc.SelectNodes("//cast/person[@job='Actor']"))
                {
                    if (movie.Actors == null)
                    {
                        movie.Actors = new List <Actor>();
                    }
                    string name = n.SafeGetString("@name");
                    string role = n.SafeGetString("@character");
                    if (!string.IsNullOrEmpty(name))
                    {
                        movie.Actors.Add(new Actor {
                            Name = name, Role = role
                        });
                    }
                }

                XmlNodeList   nodes  = doc.SelectNodes("//movie/categories/category[@type='genre']/@name");
                List <string> genres = new List <string>();
                foreach (XmlNode node in nodes)
                {
                    string n = MapGenre(node.InnerText);
                    if ((!string.IsNullOrEmpty(n)) && (!genres.Contains(n)))
                    {
                        genres.Add(n);
                    }
                }
                movie.Genres = genres;

                if (!ignoreImages)
                {
                    string img = doc.SafeGetString("//movie/images/image[@type='poster' and @size='" + Kernel.Instance.ConfigData.FetchedPosterSize + "']/@url");
                    if (img == null)
                    {
                        img = doc.SafeGetString("//movie/images/image[@type='poster' and @size='original']/@url"); //couldn't find preferred size
                    }
                    if (img != null)
                    {
                        if (Kernel.Instance.ConfigData.SaveLocalMeta)
                        {
                            //download and save locally
                            RemoteImage cover = new RemoteImage()
                            {
                                Path = img
                            };
                            string ext = Path.GetExtension(img).ToLower();
                            string fn  = (Path.Combine(Item.Path, "folder" + ext));
                            try
                            {
                                Kernel.IgnoreFileSystemMods = true;
                                cover.DownloadImage().Save(fn, ext == ".png" ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg);
                                Kernel.IgnoreFileSystemMods = false;
                                movie.PrimaryImagePath      = fn;
                            }
                            catch (Exception e)
                            {
                                Logger.ReportException("Error downloading and saving image " + fn, e);
                            }
                        }
                        else
                        {
                            movie.PrimaryImagePath = img;
                        }
                    }
                    movie.BackdropImagePaths = new List <string>();
                    int         bdNo = 0;
                    RemoteImage bd;
                    foreach (XmlNode n in doc.SelectNodes("//movie/images/image[@type='backdrop' and @size='original']/@url"))
                    {
                        if (Kernel.Instance.ConfigData.SaveLocalMeta)
                        {
                            bd = new RemoteImage()
                            {
                                Path = n.InnerText
                            };
                            string ext = Path.GetExtension(n.InnerText).ToLower();
                            string fn  = Path.Combine(Item.Path, "backdrop" + (bdNo > 0 ? bdNo.ToString() : "") + ext);
                            try
                            {
                                Kernel.IgnoreFileSystemMods = true;
                                bd.DownloadImage().Save(fn, ext == ".png" ? System.Drawing.Imaging.ImageFormat.Png : System.Drawing.Imaging.ImageFormat.Jpeg);
                                Kernel.IgnoreFileSystemMods = false;
                                movie.BackdropImagePaths.Add(fn);
                            }
                            catch (Exception e)
                            {
                                Logger.ReportException("Error downloading/saving image " + n.InnerText, e);
                            }
                            bdNo++;
                            if (bdNo >= Kernel.Instance.ConfigData.MaxBackdrops)
                            {
                                break;
                            }
                        }
                        else
                        {
                            movie.BackdropImagePaths.Add(n.InnerText);
                        }
                    }
                }
            }
        }