Exemple #1
0
        private Stream ConvertSubtitles(Stream stream,
                                        string inputFormat,
                                        string outputFormat,
                                        long startTimeTicks,
                                        long?endTimeTicks,
                                        bool preserveOriginalTimestamps,
                                        CancellationToken cancellationToken)
        {
            var ms = _memoryStreamProvider.CreateNew();

            try
            {
                var reader = GetReader(inputFormat, true);

                var trackInfo = reader.Parse(stream, cancellationToken);

                FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);

                var writer = GetWriter(outputFormat);

                writer.Write(trackInfo, ms, cancellationToken);
                ms.Position = 0;
            }
            catch
            {
                ms.Dispose();
                throw;
            }

            return(ms);
        }
Exemple #2
0
        /// <summary>
        /// Modifies the HTML by adding common meta tags, css and js.
        /// </summary>
        /// <returns>Task{Stream}.</returns>
        public async Task <Stream> ModifyHtml(string path, Stream sourceStream, string mode, string appVersion, string localizationCulture)
        {
            using (sourceStream)
            {
                string html;

                using (var memoryStream = _memoryStreamFactory.CreateNew())
                {
                    await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);

                    var originalBytes = memoryStream.ToArray();

                    html = Encoding.UTF8.GetString(originalBytes, 0, originalBytes.Length);

                    if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
                    {
                    }
                    else if (!string.IsNullOrWhiteSpace(path) && !string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase))
                    {
                        var index = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
                        if (index != -1)
                        {
                            html  = html.Substring(index);
                            index = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
                            if (index != -1)
                            {
                                html = html.Substring(0, index + 7);
                            }
                        }
                        var mainFile = _fileSystem.ReadAllText(GetDashboardResourcePath("index.html"));

                        html = ReplaceFirst(mainFile, "<div class=\"mainAnimatedPages skinBody\"></div>", "<div class=\"mainAnimatedPages skinBody hide\">" + html + "</div>");
                    }

                    if (!string.IsNullOrWhiteSpace(localizationCulture))
                    {
                        var lang = localizationCulture.Split('-').FirstOrDefault();

                        html = html.Replace("<html", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\"");
                    }
                }

                html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));

                // Disable embedded scripts from plugins. We'll run them later once resources have loaded
                if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    html = html.Replace("<script", "<!--<script");
                    html = html.Replace("</script>", "</script>-->");
                }

                html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");

                var bytes = Encoding.UTF8.GetBytes(html);

                return(_memoryStreamFactory.CreateNew(bytes));
            }
        }
Exemple #3
0
        static Stream GetSubStream(Stream stream, IMemoryStreamFactory streamProvider)
        {
            if (stream is MemoryStream)
            {
                var other = (MemoryStream)stream;

                byte[] buffer;
                if (streamProvider.TryGetBuffer(other, out buffer))
                {
                    return(streamProvider.CreateNew(buffer));
                }
                return(streamProvider.CreateNew(other.ToArray()));
            }

            return(stream);
        }
Exemple #4
0
        /// <summary>
        /// Retrieve all users from the database
        /// </summary>
        /// <returns>IEnumerable{User}.</returns>
        public IEnumerable <User> RetrieveAllUsers()
        {
            var list = new List <User>();

            using (WriteLock.Read())
            {
                using (var connection = CreateConnection(true))
                {
                    foreach (var row in connection.Query("select guid,data from users"))
                    {
                        var id = row[0].ReadGuidFromBlob();

                        using (var stream = _memoryStreamProvider.CreateNew(row[1].ToBlob()))
                        {
                            stream.Position = 0;
                            var user = _jsonSerializer.DeserializeFromStream <User>(stream);
                            user.Id = id;
                            list.Add(user);
                        }
                    }
                }
            }

            return(list);
        }
Exemple #5
0
        private MemoryStream GetHeaders(bool closing, bool isWebSocketHandshake = false)
        {
            // SendHeaders works on shared headers
            lock (_response.headers_lock)
            {
                if (_response.HeadersSent)
                {
                    return(null);
                }
                var ms = _memoryStreamFactory.CreateNew();
                _response.SendHeaders(closing, ms);
                return(ms);
            }

            //lock (_response._headersLock)
            //{
            //    if (_response.SentHeaders)
            //    {
            //        return null;
            //    }

            //    MemoryStream ms = new MemoryStream();
            //    _response.SendHeaders(closing, ms, isWebSocketHandshake);
            //    return ms;
            //}
        }
Exemple #6
0
        public async Task <int> CalculateEpisodeCount(string seriesId, string preferredMetadataLanguage, CancellationToken cancellationToken)
        {
            var fullPath = _serverApplicationPaths.PluginsPath + "\\\\Statistics";

            _fileSystem.CreateDirectory(fullPath);

            var url = string.Format(SeriesGetZip, ApiKey, seriesId, NormalizeLanguage(preferredMetadataLanguage));

            using (var zipStream = await _httpClient.Get(new HttpRequestOptions
            {
                Url = url,
                ResourcePool = TvDbResourcePool,
                CancellationToken = cancellationToken
            }).ConfigureAwait(false))
            {
                DeleteXmlFiles(fullPath);

                using (var ms = _memoryStreamProvider.CreateNew())
                {
                    await zipStream.CopyToAsync(ms).ConfigureAwait(false);

                    ms.Position = 0;
                    _zipClient.ExtractAllFromZip(ms, fullPath, true);
                }
            }

            var downloadLangaugeXmlFile = Path.Combine(fullPath, NormalizeLanguage(preferredMetadataLanguage) + ".xml");

            var result = ExtractEpisodes(downloadLangaugeXmlFile);

            _fileSystem.DeleteDirectory(fullPath, true);
            return(result);
        }
Exemple #7
0
        private string DetectCharset(byte[] bytes)
        {
            try
            {
                using (var ms = _memoryStreamProvider.CreateNew(bytes))
                {
                    var detector = new CharsetDetector();
                    detector.Feed(ms);
                    detector.DataEnd();

                    var charset = detector.Charset;

                    if (!string.IsNullOrWhiteSpace(charset))
                    {
                        //_logger.Debug("UniversalDetector detected charset {0}", charset);
                    }

                    return(charset);
                }
            }
            catch (IOException ex)
            {
                _logger.ErrorException("Error attempting to determine web socket message charset", ex);
            }

            return(null);
        }
 private DisplayPreferences Get(IReadOnlyList <IResultSetValue> row)
 {
     using (var stream = _memoryStreamProvider.CreateNew(row[0].ToBlob()))
     {
         stream.Position = 0;
         return(_jsonSerializer.DeserializeFromStream <DisplayPreferences>(stream));
     }
 }
Exemple #9
0
        /// <summary>
        /// Serializes to bytes.
        /// </summary>
        /// <returns>System.Byte[][].</returns>
        /// <exception cref="System.ArgumentNullException">obj</exception>
        public static byte[] SerializeToBytes(this IJsonSerializer json, object obj, IMemoryStreamFactory streamProvider)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            using (var stream = streamProvider.CreateNew())
            {
                json.SerializeToStream(obj, stream);
                return(stream.ToArray());
            }
        }
Exemple #10
0
        public object Get(GetIcon request)
        {
            using (var response = _dlnaManager.GetIcon(request.Filename))
            {
                using (var ms = _memoryStreamProvider.CreateNew())
                {
                    response.Stream.CopyTo(ms);

                    ms.Position = 0;
                    var bytes = ms.ToArray();
                    return(ResultFactory.GetResult(bytes, "image/" + response.Format.ToString().ToLower()));
                }
            }
        }
Exemple #11
0
 internal static MemoryStream GetHeaders(HttpListenerResponse response, IMemoryStreamFactory memoryStreamFactory, bool closing)
 {
     // SendHeaders works on shared headers
     lock (response.headers_lock)
     {
         if (response.HeadersSent)
         {
             return(null);
         }
         MemoryStream ms = memoryStreamFactory.CreateNew();
         response.SendHeaders(closing, ms);
         return(ms);
     }
 }
Exemple #12
0
        private async Task SaveData(List <LocalItem> items, CancellationToken cancellationToken)
        {
            using (var stream = _memoryStreamProvider.CreateNew())
            {
                _json.SerializeToStream(items, stream);

                // Save to sync provider
                stream.Position = 0;
                var remotePath = GetRemotePath();
                _logger.Debug("Saving data.json to {0}. Remote path: {1}", _provider.Name, string.Join("/", remotePath));

                await _provider.SendFile(stream, remotePath, _target, new Progress <double>(), cancellationToken).ConfigureAwait(false);
            }
        }
Exemple #13
0
        private bool processFragments(WebSocketFrame first)
        {
            using (var buff = _memoryStreamFactory.CreateNew())
            {
                buff.WriteBytes(first.PayloadData.ApplicationData);
                if (!concatenateFragmentsInto(buff))
                {
                    return(false);
                }

                byte[] data;
                if (_compression != CompressionMethod.None)
                {
                    data = buff.DecompressToArray(_compression);
                }
                else
                {
                    data = buff.ToArray();
                }

                enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data));
                return(true);
            }
        }
Exemple #14
0
        void Init()
        {
            if (ssl_stream != null)
            {
                //ssl_stream.AuthenticateAsServer(client_cert, true, (SslProtocols)ServicePointManager.SecurityProtocol, false);
                //_streamFactory.AuthenticateSslStreamAsServer(ssl_stream, cert);
            }

            context_bound = false;
            i_stream      = null;
            o_stream      = null;
            prefix        = null;
            chunked       = false;
            ms            = _memoryStreamFactory.CreateNew();
            position      = 0;
            input_state   = InputState.RequestLine;
            line_state    = LineState.None;
            context       = new HttpListenerContext(this, _logger, _cryptoProvider, _memoryStreamFactory, _textEncoding);
        }
Exemple #15
0
        public async Task SaveImage(IHasImages item, Stream source, string mimeType, ImageType type, int?imageIndex, bool?saveLocallyWithMedia, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(mimeType))
            {
                throw new ArgumentNullException("mimeType");
            }

            var saveLocally = item.SupportsLocalMetadata && item.IsSaveLocalMetadataEnabled() && !item.IsOwnedItem && !(item is Audio);

            if (item is User)
            {
                saveLocally = true;
            }

            if (type != ImageType.Primary && item is Episode)
            {
                saveLocally = false;
            }

            var locationType = item.LocationType;

            if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
            {
                saveLocally = false;

                var season = item as Season;

                // If season is virtual under a physical series, save locally if using compatible convention
                if (season != null && _config.Configuration.ImageSavingConvention == ImageSavingConvention.Compatible)
                {
                    var series = season.Series;

                    if (series != null && series.SupportsLocalMetadata && series.IsSaveLocalMetadataEnabled())
                    {
                        saveLocally = true;
                    }
                }
            }
            if (saveLocallyWithMedia.HasValue && !saveLocallyWithMedia.Value)
            {
                saveLocally = saveLocallyWithMedia.Value;
            }

            if (!imageIndex.HasValue && item.AllowsMultipleImages(type))
            {
                imageIndex = item.GetImages(type).Count();
            }

            var index = imageIndex ?? 0;

            var paths = GetSavePaths(item, type, imageIndex, mimeType, saveLocally);

            var retryPaths = GetSavePaths(item, type, imageIndex, mimeType, false);

            // If there are more than one output paths, the stream will need to be seekable
            var memoryStream = _memoryStreamProvider.CreateNew();

            using (source)
            {
                await source.CopyToAsync(memoryStream).ConfigureAwait(false);
            }

            source = memoryStream;

            var currentImage            = GetCurrentImage(item, type, index);
            var currentImageIsLocalFile = currentImage != null && currentImage.IsLocalFile;
            var currentImagePath        = currentImage == null ? null : currentImage.Path;

            var savedPaths = new List <string>();

            using (source)
            {
                var currentPathIndex = 0;

                foreach (var path in paths)
                {
                    source.Position = 0;
                    string retryPath = null;
                    if (paths.Length == retryPaths.Length)
                    {
                        retryPath = retryPaths[currentPathIndex];
                    }
                    var savedPath = await SaveImageToLocation(source, path, retryPath, cancellationToken).ConfigureAwait(false);

                    savedPaths.Add(savedPath);
                    currentPathIndex++;
                }
            }

            // Set the path into the item
            SetImagePath(item, type, imageIndex, savedPaths[0]);

            // Delete the current path
            if (currentImageIsLocalFile && !savedPaths.Contains(currentImagePath, StringComparer.OrdinalIgnoreCase))
            {
                var currentPath = currentImagePath;

                _logger.Debug("Deleting previous image {0}", currentPath);

                _libraryMonitor.ReportFileSystemChangeBeginning(currentPath);

                try
                {
                    var currentFile = _fileSystem.GetFileInfo(currentPath);

                    // This will fail if the file is hidden
                    if (currentFile.Exists)
                    {
                        if (currentFile.IsHidden)
                        {
                            _fileSystem.SetHidden(currentFile.FullName, false);
                        }

                        _fileSystem.DeleteFile(currentFile.FullName);
                    }
                }
                finally
                {
                    _libraryMonitor.ReportFileSystemChangeComplete(currentPath, false);
                }
            }
        }