Example #1
0
        void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                var item = (BaseItem)e.Node.Tag;
                lblType.Text = item.GetType().Name;

                var json = FormatJson(_jsonSerializer.SerializeToString(item));

                if (item is IHasMediaStreams)
                {
                    var mediaStreams = _itemRepository.GetMediaStreams(new MediaStreamQuery
                    {
                        ItemId = item.Id
                    }).ToList();

                    if (mediaStreams.Count > 0)
                    {
                        json += "\n\nMedia Streams:\n\n" + FormatJson(_jsonSerializer.SerializeToString(mediaStreams));
                    }
                }

                txtJson.Text = json;
            }
        }
Example #2
0
        public void SaveCapabilities(string deviceId, ClientCapabilities capabilities)
        {
            using (WriteLock.Write())
            {
                using (var connection = CreateConnection())
                {
                    connection.RunInTransaction(db =>
                    {
                        using (var statement = db.PrepareStatement("update devices set Capabilities=@Capabilities where Id=@Id"))
                        {
                            statement.TryBind("@Id", deviceId);

                            if (capabilities == null)
                            {
                                statement.TryBindNull("@Capabilities");
                            }
                            else
                            {
                                statement.TryBind("@Capabilities", _json.SerializeToString(capabilities));
                            }

                            statement.MoveNext();
                        }
                    }, TransactionMode);
                }
            }
        }
Example #3
0
        private void UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
        {
            // The xml serializer will output differently if the type is not exact
            if (userPolicy.GetType() != typeof(UserPolicy))
            {
                var json = _jsonSerializer.SerializeToString(userPolicy);
                userPolicy = _jsonSerializer.DeserializeFromString <UserPolicy>(json);
            }

            var path = GetPolicyFilePath(user);

            Directory.CreateDirectory(Path.GetDirectoryName(path));

            lock (_policySyncLock)
            {
                _xmlSerializer.SerializeToFile(userPolicy, path);
                user.Policy = userPolicy;
            }

            if (fireEvent)
            {
                UserPolicyUpdated?.Invoke(this, new GenericEventArgs <User> {
                    Argument = user
                });
            }
        }
Example #4
0
        private void LogTraktResponseDataContract(TraktSyncResponse dataContract)
        {
            _logger.Debug("TraktResponse Added Movies: " + dataContract.added.movies);
            _logger.Debug("TraktResponse Added Shows: " + dataContract.added.shows);
            _logger.Debug("TraktResponse Added Seasons: " + dataContract.added.seasons);
            _logger.Debug("TraktResponse Added Episodes: " + dataContract.added.episodes);
            foreach (var traktMovie in dataContract.not_found.movies)
            {
                _logger.Error("TraktResponse not Found:" + _jsonSerializer.SerializeToString(traktMovie));
            }

            foreach (var traktShow in dataContract.not_found.shows)
            {
                _logger.Error("TraktResponse not Found:" + _jsonSerializer.SerializeToString(traktShow));
            }

            foreach (var traktSeason in dataContract.not_found.seasons)
            {
                _logger.Error("TraktResponse not Found:" + _jsonSerializer.SerializeToString(traktSeason));
            }

            foreach (var traktEpisode in dataContract.not_found.episodes)
            {
                _logger.Error("TraktResponse not Found:" + _jsonSerializer.SerializeToString(traktEpisode));
            }
        }
Example #5
0
        /* NOW EVERYTHING RELATED TO SCROBBLING */
        public async void markAsWatched(BaseItemDto MediaInfo, string userToken)
        {
            SimklHistory history = new SimklHistory();

            _logger.Info("Scrobbling mediainfo: " + _json.SerializeToString(MediaInfo));
            if (MediaInfo.IsMovie == true || MediaInfo.Type == "Movie")
            {
                history.movies.Add(new SimklMovie(MediaInfo));
            }
            else if (MediaInfo.IsSeries == true || MediaInfo.Type == "Episode")
            {
                // TODO: TV Shows scrobbling (WIP)
                history.shows.Add(SimklShow.createFromEpisode(MediaInfo));
            }
            _logger.Info("Scrobbling " + _json.SerializeToString(history));
            try
            {
                await SyncHistoryAsync(history, userToken);
            }
            catch (MediaBrowser.Model.Net.HttpException e) when(e.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                _logger.Error("Invalid user token " + userToken + ", deleting");
                Plugin.Instance.Configuration.deleteUserToken(userToken);
            }
        }
Example #6
0
        /// <summary>
        /// Create a new recording
        /// </summary>
        /// <param name="info">The TimerInfo</param>
        /// <param name="cancellationToken">The cancellationToken</param>
        /// <returns></returns>
        public async Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
        {
            var timerJson = _jsonSerializer.SerializeToString(info);

            _logger.Info($"[MythTV] Start CreateTimer Async for TimerInfo\n{timerJson}");

            await EnsureSetup();

            var options = GetRuleStreamOptions(info.ProgramId, info.StartDate, cancellationToken);

            using (var stream = await _httpClient.Get(options))
            {
                try
                {
                    var json = new DvrResponse().GetNewTimerJson(info, stream, _jsonSerializer, _logger);
                    var post = PostOptions(cancellationToken,
                                           ConvertJsonRecRuleToPost(json),
                                           "/Dvr/AddRecordSchedule");
                    await _httpClient.Post(post).ConfigureAwait(false);
                }
                catch (ExistingTimerException existing)
                {
                    _logger.Info($"[MythTV] found existing rule {existing.id}");
                    await CancelTimerAsync(existing.id, cancellationToken);
                }
            }
        }
Example #7
0
        private async Task UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent)
        {
            // The xml serializer will output differently if the type is not exact
            if (userPolicy.GetType() != typeof(UserPolicy))
            {
                var json = _jsonSerializer.SerializeToString(userPolicy);
                userPolicy = _jsonSerializer.DeserializeFromString <UserPolicy>(json);
            }

            var path = GetPolifyFilePath(user);

            Directory.CreateDirectory(Path.GetDirectoryName(path));

            lock (_policySyncLock)
            {
                _xmlSerializer.SerializeToFile(userPolicy, path);
                user.Policy = userPolicy;
            }

            user.Configuration.IsAdministrator        = user.Policy.IsAdministrator;
            user.Configuration.EnableLiveTvManagement = user.Policy.EnableLiveTvManagement;
            user.Configuration.EnableLiveTvAccess     = user.Policy.EnableLiveTvAccess;
            user.Configuration.EnableMediaPlayback    = user.Policy.EnableMediaPlayback;
            user.Configuration.EnableContentDeletion  = user.Policy.EnableContentDeletion;

            await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false);
        }
Example #8
0
        /// <summary>
        /// Create a new recording
        /// </summary>
        /// <param name="info">The TimerInfo</param>
        /// <param name="cancellationToken">The cancellationToken</param>
        /// <returns></returns>
        public async Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
        {
            _logger.Info(string.Format("[MythTV] Start CreateTimer Async for ChannelId: {0} & Name: {1}", info.ChannelId, info.Name));
            EnsureSetup();

            using (var stream = await _httpClient.Get(GetOptions(cancellationToken, "/Dvr/GetRecordSchedule?Template=Default")).ConfigureAwait(false))
            {
                RecRule orgRule = DvrResponse.GetRecRule(stream, _jsonSerializer, _logger);
                if (orgRule != null)
                {
                    orgRule.Title    = info.Name;
                    orgRule.ChanId   = info.ChannelId;
                    orgRule.CallSign = await GetCallsign(info.ChannelId, cancellationToken);

                    orgRule.EndTime     = info.EndDate;
                    orgRule.StartTime   = info.StartDate;
                    orgRule.StartOffset = info.PrePaddingSeconds / 60;
                    orgRule.EndOffset   = info.PostPaddingSeconds / 60;
                    orgRule.Type        = "Single Record";

                    var postContent = ConvertJsonRecRuleToPost(_jsonSerializer.SerializeToString(orgRule));

                    var options = PostOptions(cancellationToken, postContent, "/Dvr/AddRecordSchedule");

                    using (var response = await _httpClient.Post(options).ConfigureAwait(false)) { }
                }
            }
        }
Example #9
0
        private async Task InsertOrUpdate(SyncJobItem jobItem, bool insert)
        {
            if (jobItem == null)
            {
                throw new ArgumentNullException("jobItem");
            }

            CheckDisposed();

            using (WriteLock.Write())
            {
                using (var connection = CreateConnection())
                {
                    string commandText;

                    if (insert)
                    {
                        commandText = "insert into SyncJobItems (Id, ItemId, ItemName, MediaSourceId, JobId, TemporaryPath, OutputPath, Status, TargetId, DateCreated, Progress, AdditionalFiles, MediaSource, IsMarkedForRemoval, JobItemIndex, ItemDateModifiedTicks) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    }
                    else
                    {
                        // cmd
                        commandText = "update SyncJobItems set ItemId=?,ItemName=?,MediaSourceId=?,JobId=?,TemporaryPath=?,OutputPath=?,Status=?,TargetId=?,DateCreated=?,Progress=?,AdditionalFiles=?,MediaSource=?,IsMarkedForRemoval=?,JobItemIndex=?,ItemDateModifiedTicks=? where Id=?";
                    }

                    var paramList = new List <object>();
                    paramList.Add(jobItem.ItemId);
                    paramList.Add(jobItem.ItemName);
                    paramList.Add(jobItem.MediaSourceId);
                    paramList.Add(jobItem.JobId);
                    paramList.Add(jobItem.TemporaryPath);
                    paramList.Add(jobItem.OutputPath);
                    paramList.Add(jobItem.Status.ToString());

                    paramList.Add(jobItem.TargetId);
                    paramList.Add(jobItem.DateCreated.ToDateTimeParamValue());
                    paramList.Add(jobItem.Progress);
                    paramList.Add(_json.SerializeToString(jobItem.AdditionalFiles));
                    paramList.Add(jobItem.MediaSource == null ? null : _json.SerializeToString(jobItem.MediaSource));
                    paramList.Add(jobItem.IsMarkedForRemoval);
                    paramList.Add(jobItem.JobItemIndex);
                    paramList.Add(jobItem.ItemDateModifiedTicks);

                    if (insert)
                    {
                        paramList.Insert(0, jobItem.Id.ToGuidParamValue());
                    }
                    else
                    {
                        paramList.Add(jobItem.Id.ToGuidParamValue());
                    }

                    connection.RunInTransaction(conn =>
                    {
                        conn.Execute(commandText, paramList.ToArray());
                    }, TransactionMode);
                }
            }
        }
Example #10
0
        public async Task <SearchFileResponse> getFromFile(string filename)
        {
            SimklFile f = new SimklFile {
                file = filename
            };

            _logger.Info("Posting: " + _json.SerializeToString(f));
            StreamReader r = new StreamReader(await _post("/search/file/", null, f));
            string       t = r.ReadToEnd();

            _logger.Debug("Response: " + t);
            return(_json.DeserializeFromString <SearchFileResponse>(t));
        }
Example #11
0
        /// <summary>
        /// Add or remove a list of movies to/from the users trakt.tv library
        /// </summary>
        /// <param name="movies">The movies to add</param>
        /// <param name="traktUser">The user who's library is being updated</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{TraktResponseDataContract}.</returns>
        public async Task <TraktResponseDataContract> SendLibraryUpdateAsync(List <Movie> movies, TraktUser traktUser, CancellationToken cancellationToken, EventType eventType)
        {
            if (movies == null)
            {
                throw new ArgumentNullException("movies");
            }
            if (traktUser == null)
            {
                throw new ArgumentNullException("traktUser");
            }

            if (eventType == EventType.Update)
            {
                return(null);
            }

            var moviesPayload = new List <object>();

            foreach (Movie m in movies)
            {
                var movieData = new
                {
                    title   = m.Name,
                    imdb_id = m.GetProviderId(MetadataProviders.Imdb),
                    year    = m.ProductionYear ?? 0
                };

                moviesPayload.Add(movieData);
            }

            var data = new Dictionary <string, string>();

            data.Add("username", traktUser.UserName);
            data.Add("password", traktUser.PasswordHash);
            data.Add("movies", _jsonSerializer.SerializeToString(moviesPayload));

            Stream response = null;

            if (eventType == EventType.Add)
            {
                response = await _httpClient.Post(TraktUris.MovieLibrary, data, Plugin.Instance.TraktResourcePool,
                                                  cancellationToken).ConfigureAwait(false);
            }
            else if (eventType == EventType.Remove)
            {
                response = await _httpClient.Post(TraktUris.MovieUnLibrary, data, Plugin.Instance.TraktResourcePool,
                                                  cancellationToken).ConfigureAwait(false);
            }

            return(_jsonSerializer.DeserializeFromStream <TraktResponseDataContract>(response));
        }
        private void PlaybackProgress(object sender, PlaybackProgressEventArgs e)
        {
            //we are only interested in video
            if (e.Item.MediaType != "Video")
            {
                return;
            }

            _logger.Debug("e.IsPaused: " + e.IsPaused.ToString());

            //var iType = _libraryManager.GetContentType(e.Item);

            var pauseControl = getPauseControl(e.DeviceId);

            _logger.Debug("pauseControl.wasPaused" + pauseControl.wasPaused.ToString());

            if (e.IsPaused & pauseControl.wasPaused == false)
            {
                _logger.Debug("Playback Paused event");
                _logger.Debug(_jsonSerializer.SerializeToString(e));
                getDeviceState(e.DeviceId).playerState = PlayerState.Paused;
                pauseControl.wasPaused = true;

                var DeviceOptions = Plugin.Instance.Configuration.Options.Where(i => i.embyDeviceID == e.DeviceId && i.Enabled);

                if (DeviceOptions.Count() > 0)
                {
                    var a = DeviceOptions.First();
                    //send dim-up command
                    sDim(DeviceOptions.First());
                }
            }
            else if (e.IsPaused == false & pauseControl.wasPaused)
            {
                _logger.Debug("Playback Resume event");
                _logger.Debug(_jsonSerializer.SerializeToString(e));
                getDeviceState(e.DeviceId).playerState = PlayerState.Playing;
                getPauseControl(e.DeviceId).wasPaused  = false;

                var DeviceOptions = Plugin.Instance.Configuration.Options.Where(i => i.embyDeviceID == e.DeviceId && i.Enabled);

                if (DeviceOptions.Count() > 0)
                {
                    var a = DeviceOptions.First();
                    //send dim-down command
                    sDim(DeviceOptions.First());
                }
            }
        }
Example #13
0
        public async Task SendMessage <T>(string name, T data, CancellationToken cancellationToken)
        {
            if (!IsSessionActive)
            {
                return;
            }

            if (string.IsNullOrEmpty(_senderId) || string.IsNullOrEmpty(_applicationId))
            {
                return;
            }

            string strData = _json.SerializeToString(data);
            var    req     = new FirebaseBody
            {
                to   = _token,
                data = new FirebaseData
                {
                    msgdata = strData
                }
            };

            var byteArray = Encoding.UTF8.GetBytes(_json.SerializeToString(req));

            var enableLogging = false;

#if DEBUG
            enableLogging = true;
#endif

            var options = new HttpRequestOptions
            {
                Url = "https://fcm.googleapis.com/fcm/send",
                RequestContentType  = "application/json",
                RequestContentBytes = byteArray,
                CancellationToken   = cancellationToken,
                LogRequest          = enableLogging,
                LogResponse         = enableLogging,
                LogErrors           = enableLogging
            };

            options.RequestHeaders["Authorization"] = string.Format("key={0}", _applicationId);
            options.RequestHeaders["Sender"]        = string.Format("id={0}", _senderId);

            using (var response = await _httpClient.Post(options).ConfigureAwait(false))
            {
            }
        }
Example #14
0
        public IEnumerable <ChannelInfo> GetInfo(Stream stream, IJsonSerializer json, ILogger logger)
        {
            logger.Info("[VDR] Start GetInfo");
            var root = json.DeserializeFromStream <RootObject>(stream);

            logger.Info("[VDR] got Root Object");
//	    logger.Info(string.Format("[VDR] Display Root Object: {0}", json.SerializeToString(root)));
            if (root != null && root.Channels != null)
            {
                logger.Info("[VDR] Parse Channel Response");
                UtilsHelper.DebugInformation(logger, string.Format("[VDR] InitiateResponse: {0}", json.SerializeToString(root)));
                return(root.Channels.Select(i => new ChannelInfo
                {
                    Name = i.name,
                    ChannelType = i.is_radio ? ChannelType.Radio : ChannelType.TV,
                    Number = i.number.ToString(_usCulture),
                    Id = i.channel_id,
                    ImageUrl = i.image ? string.Format("{0}/channels/image/{1}", _baseUrl, i.channel_id) : null,
                    HasImage = i.image
                }));
            }
            else
            {
                logger.Info("[VDR] Parse Channel Response failed");
                logger.Info(string.Format("[VDR] InitiateResponse: {0}", json.SerializeToString(root)));
            }
            return(new List <ChannelInfo>());
        }
Example #15
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

            var parameters = new Dictionary <string, string>
            {
                { "channel_tag", options.Channel },
                { "type", "note" },
                { "title", request.Name },
                { "body", request.Description }
            };

            _logger.LogDebug("Pushbullet to Token : {0} - {1} - {2}", options.Token, options.DeviceId, request.Description);

            var requestOptions = new HttpRequestOptions
            {
                Url                  = PluginConfiguration.Url,
                RequestContent       = _jsonSerializer.SerializeToString(parameters),
                RequestContentType   = "application/json",
                LogErrorResponseBody = true,
                RequestHeaders       = { ["Access-Token"] = options.Token }
            };

            await _httpClient.Post(requestOptions).ConfigureAwait(false);
        }
Example #16
0
        /// <summary>
        ///     Posts data to url, authenticating with <see cref="TraktUser"/>.
        /// </summary>
        /// <param name="traktUser">If null, authentication headers not added.</param>
        private async Task <Stream> PostToTrakt(string url, object data, CancellationToken cancellationToken,
                                                TraktUser traktUser)
        {
            var requestContent = data == null ? string.Empty : _jsonSerializer.SerializeToString(data);

            if (traktUser != null && traktUser.ExtraLogging)
            {
                _logger.Debug(requestContent);
            }
            var options = GetHttpRequestOptions();

            options.Url = url;
            options.CancellationToken = cancellationToken;
            options.RequestContent    = requestContent.AsMemory();

            if (traktUser != null)
            {
                await SetRequestHeaders(options, traktUser).ConfigureAwait(false);
            }

            await Plugin.Instance.TraktResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                var retryResponse = await Retry(async() => await _httpClient.Post(options).ConfigureAwait(false)).ConfigureAwait(false);

                return(retryResponse.Content);
            }
            finally
            {
                Plugin.Instance.TraktResourcePool.Release();
            }
        }
Example #17
0
        public IEnumerable<ChannelInfo> GetChannels(Stream stream, IJsonSerializer json,ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.channelsJSONObject.rtn != null && root.channelsJSONObject.rtn.Error)
            {
                logger.Error(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
                throw new ApplicationException(root.channelsJSONObject.rtn.Message ?? "Failed to download channel information.");
            }

            if (root.channelsJSONObject != null && root.channelsJSONObject.Channels != null)
            {
                UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] ChannelResponse: {0}", json.SerializeToString(root)));
                return root.channelsJSONObject.Channels.Select(i => new ChannelInfo
                {
                    Name = i.channel.channelName,
                    Number = i.channel.channelFormattedNumber.ToString(_usCulture),
                    Id = i.channel.channelOID.ToString(_usCulture),
                    ImageUrl = string.IsNullOrEmpty(i.channel.channelIcon) ? null : (_baseUrl + "/" + i.channel.channelIcon),
                    HasImage = !string.IsNullOrEmpty(i.channel.channelIcon)
                });
            }

            return new List<ChannelInfo>();
        }
Example #18
0
        public IEnumerable <RecordingInfo> GetRecordings(Stream stream, IJsonSerializer json, ILogger logger)
        {
            logger.Info("[VDR] Start GetRecordings");
            var root = json.DeserializeFromStream <RootObject>(stream);

            logger.Info("[VDR] got Root Object");
//	    logger.Info(string.Format("[VDR] Display Root Object: {0}", json.SerializeToString(root)));
//      List<RecordingInfo> channels = new List<RecordingInfo>();
            if (root != null && root.recordings != null)
            {
                logger.Info("[VDR] Parse Recording Response");
                //UtilsHelper.DebugInformation(logger,string.Format("[VDR] ChannelResponse: {0}", json.SerializeToString(root)));
                return(root.recordings.Select(i => new RecordingInfo
                {
                    Id = i.number.ToString(),
                    ChannelId = i.channel_id,
                    Name = i.event_title,
                    EpisodeTitle = i.event_short_text,
                    Overview = i.event_description,
                    StartDate = ApiHelper.DateTimeFromUnixTimestampSeconds(i.event_start_time).ToUniversalTime(),
                    EndDate = ApiHelper.DateTimeFromUnixTimestampSeconds(i.event_start_time).ToUniversalTime().AddSeconds(i.event_duration)
                }));
            }
            else
            {
                logger.Info("[VDR] Parse Recording Response failed");
                logger.Info(string.Format("[VDR] RecordingResponse: {0}", json.SerializeToString(root)));
            }
            return(new List <RecordingInfo>());
        }
Example #19
0
        private async Task AppendLocalization(Stream stream, string culture, List <string> excludePhrases)
        {
            var dictionary = _localization.GetJavaScriptLocalizationDictionary(culture);

            if (excludePhrases.Count > 0)
            {
                var removes = new List <string>();

                foreach (var pair in dictionary)
                {
                    if (excludePhrases.Any(i => pair.Key.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1 || pair.Value.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1))
                    {
                        removes.Add(pair.Key);
                    }
                }

                foreach (var remove in removes)
                {
                    dictionary.Remove(remove);
                }
            }

            var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(dictionary);

            var bytes = Encoding.UTF8.GetBytes(js);
            await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
        }
Example #20
0
        private async Task RespondToV2Message(string messageText, IpEndPointInfo endpoint, Encoding encoding)
        {
            var parts = messageText.Split('|');

            var localUrl = await _appHost.GetLocalApiUrl().ConfigureAwait(false);

            if (!string.IsNullOrEmpty(localUrl))
            {
                var response = new ServerDiscoveryInfo
                {
                    Address = localUrl,
                    Id      = _appHost.SystemId,
                    Name    = _appHost.FriendlyName
                };

                await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint).ConfigureAwait(false);

                if (parts.Length > 1)
                {
                    _appHost.EnableLoopback(parts[1]);
                }
            }
            else
            {
                _logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
            }
        }
Example #21
0
        public IEnumerable <TimerInfo> GetTimers(Stream stream, IJsonSerializer json, ILogger logger)
        {
            logger.Info("[VDR] Start GetTimers");
            var root = json.DeserializeFromStream <RootObject>(stream);

            logger.Info("[VDR] got Root Object");
//	    logger.Info(string.Format("[VDR] Display Root Object: {0}", json.SerializeToString(root)));
            if (root != null && root.timers != null)
            {
                logger.Info("[VDR] Parse Recording Response");
                //UtilsHelper.DebugInformation(logger,string.Format("[VDR] ChannelResponse: {0}", json.SerializeToString(root)));
                return(root.timers.Select(i => new TimerInfo
                {
                    Name = i.filename,
                    ChannelId = i.channel,
                    Id = i.id,
                    StartDate = DateTime.Parse(i.start_timestamp),
                    EndDate = DateTime.Parse(i.stop_timestamp),
                    Priority = i.priority
                }));
            }
            else
            {
                logger.Info("[VDR] Parse Timer Response failed");
                logger.Info(string.Format("[VDR] TimerResponse: {0}", json.SerializeToString(root)));
            }
            return(new List <TimerInfo>());
        }
        private async Task AppendLocalization(Stream stream)
        {
            var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(GetLocalizationCulture()));

            var bytes = Encoding.UTF8.GetBytes(js);
            await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
        }
Example #23
0
        private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
        {
            _targetPath = targetFile;
            _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile));

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow  = true,
                    UseShellExecute = false,

                    // Must consume both stdout and stderr or deadlocks may occur
                    //RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,

                    FileName  = _mediaEncoder.EncoderPath,
                    Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _process = process;

            var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;

            _logger.Info(commandLineLogMessage);

            var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");

            _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));

            // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
            _logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);

            var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);

            _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length);

            process.Exited += (sender, args) => OnFfMpegProcessExited(process);

            process.Start();

            cancellationToken.Register(Stop);

            // MUST read both stdout and stderr asynchronously or a deadlock may occurr
            //process.BeginOutputReadLine();

            onStarted();

            // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
            StartStreamingLog(process.StandardError.BaseStream, _logFileStream);

            return(_taskCompletionSource.Task);
        }
        public void SetUserInfoSync(List <MediaBrowser.Model.Dto.UserItemDataDto> dtos, List <LibItem> itemRefs, string userName, string userId, CancellationToken cancellationToken)
        {
            var newRecs = new List <UserInfoRec>();
            var upRecs  = new List <UserInfoRec>();

            lock (_userLock)
            {
                dtos.ForEach(dto =>
                {
                    var sJson = json.SerializeToString(dto).ToString();
                    logger.LogDebug("Updating ItemId '{0}' for UserId: '{1}'", dto.ItemId, userId);

                    LibItem itemref = itemRefs.Where(x => x.Id.ToString("N") == dto.ItemId).FirstOrDefault();
                    if (itemref != null)
                    {
                        var oldRec = userInfoRecs.Select(u => u.ItemId == dto.ItemId && u.UserId == userId).FirstOrDefault();
                        var newRec = new UserInfoRec()
                        {
                            ItemId       = dto.ItemId,
                            Json         = sJson,
                            UserId       = userId,
                            LastModified = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds),
                            MediaType    = itemref.ItemType,
                            //LibraryName = itemref.CollectionName
                        };
                        if (oldRec == null)
                        {
                            newRecs.Add(newRec);
                        }
                        else
                        {
                            newRec.Id = oldRec.Id;
                            upRecs.Add(newRec);
                        }
                    }
                });

                if (newRecs.Count > 0)
                {
                    userInfoRecs.Insert(newRecs);
                }
                if (upRecs.Count > 0)
                {
                    var data = userInfoRecs.Select();

                    foreach (var rec in upRecs)
                    {
                        data.Where(d => d.Id == rec.Id).ToList().ForEach(u =>
                        {
                            u.ItemId       = rec.ItemId;
                            u.Json         = rec.Json;
                            u.UserId       = rec.UserId;
                            u.LastModified = rec.LastModified;
                            u.MediaType    = rec.MediaType;
                        });
                    }
                    userInfoRecs.Commit(data);
                }
            }
        }
        /// <inheritdoc/>
        public void SaveResult(SmartMatchResult result, CancellationToken cancellationToken)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            cancellationToken.ThrowIfCancellationRequested();

            using (WriteLock.Write())
            {
                using (var connection = CreateConnection())
                {
                    connection.RunInTransaction(
                        db =>
                    {
                        var commandText = "replace into SmartMatch (Id, ItemName, DisplayName, OrganizerType, MatchStrings) values (@Id, @ItemName, @DisplayName, @OrganizerType, @MatchStrings)";

                        using (var statement = db.PrepareStatement(commandText))
                        {
                            statement.TryBind("@Id", result.Id.ToGuidBlob());

                            statement.TryBind("@ItemName", result.ItemName);
                            statement.TryBind("@DisplayName", result.DisplayName);
                            statement.TryBind("@OrganizerType", result.OrganizerType.ToString());
                            statement.TryBind("@MatchStrings", _jsonSerializer.SerializeToString(result.MatchStrings));

                            statement.MoveNext();
                        }
                    },
                        TransactionMode);
                }
            }
        }
Example #26
0
        /// <summary>
        /// POST 请求
        /// </summary>
        /// <typeparam name="TResult"> Type of the result. </typeparam>
        /// <param name="url"> URL of the resource. </param>
        /// <param name="param"> The parameter. </param>
        /// <returns>
        /// An asynchronous result that yields an ApiResult&lt;BaiduFaceApiReault&lt;TResult&gt;&gt;
        /// </returns>
        public async Task <BaiduApiResult <TResult> > DoPost <TResult>(string url, object param)
        {
            var token = await GetAccessTokenAsync();

            if (token == null)
            {
                return("令牌不正确。");
            }
            var s = url.IndexOf('?') > 0 ? "&" : "?";

            url = $"{url}{s}access_token={token.access_token}";
            try
            {
                var json = jsonSerializer.SerializeToString(param);

                var resp = await client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json"));

                if (resp.IsSuccessStatusCode)
                {
                    json = await resp.Content.ReadAsStringAsync();

                    return(jsonSerializer.DeserializeFromString <BaiduApiResult <TResult> >(json));
                }

                return($"请求出错:{resp.ReasonPhrase}");
            }
            catch (Exception ex)
            {
                return($"请求出错:{ex.Message}");
            }
        }
Example #27
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

            var parameters = new Dictionary <string, string>
            {
                { "text", $"{request.Name} \n {request.Description}" },
            };

            if (!string.IsNullOrEmpty(options.Username))
            {
                parameters.Add("username", options.Username);
            }
            if (!string.IsNullOrEmpty(options.IconUrl))
            {
                parameters.Add("icon_url", options.IconUrl);
            }

            _logger.LogDebug("Notification to Slack : {0} - {1}", options.WebHookUrl, request.Description);
            var httpRequest = new HttpRequestOptions
            {
                Url                = options.WebHookUrl,
                RequestContent     = _serializer.SerializeToString(parameters),
                RequestContentType = "application/json",
            };

            await _httpClient.Post(httpRequest).ConfigureAwait(false);
        }
Example #28
0
        /// <summary>
        /// Restart module with the given name.
        /// </summary>
        /// <param name="moduleName"> Module name. </param>
        /// <param name="ct"> Cancellation token. </param>
        public async Task <MethodResultModel> RestartModule(
            string moduleName,
            CancellationToken ct)
        {
            var payload = new Dictionary <string, string> {
                { "schemaVersion", "1.0" },
                { "id", moduleName },
            };

            var parameters = new MethodParameterModel {
                Name        = "RestartModule",
                JsonPayload = _serializer.SerializeToString(payload)
            };

            var moduleRestartResponse = await TestHelper.CallMethodAsync(
                _iotHubClient,
                _iotHubPublisherDeviceName,
                "$edgeAgent",
                parameters,
                _context,
                ct
                ).ConfigureAwait(false);

            return(moduleRestartResponse);
        }
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

            var parameters = new Dictionary <string, string>
            {
                // {"device_iden", options.DeviceId},
                { "channel_tag", options.Channel },
                { "type", "note" },
                { "title", request.Name },
                { "body", request.Description }
            };

            _logger.LogDebug("Pushbullet to Token : {0} - {1} - {2}", options.Token, options.DeviceId, request.Description);

            string authInfo = options.Token;

            authInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));

            var requestOptions = new HttpRequestOptions
            {
                Url                  = "https://api.pushbullet.com/v2/pushes",
                RequestContent       = _jsonSerializer.SerializeToString(parameters),
                BufferContent        = false,
                RequestContentType   = "application/json",
                LogErrorResponseBody = true,
                DecompressionMethod  = CompressionMethod.None,
                EnableKeepAlive      = false
            };

            requestOptions.RequestHeaders["Authorization"] = "Basic " + authInfo;
            await _httpClient.Post(requestOptions).ConfigureAwait(false);
        }
Example #30
0
        /// <summary>
        /// Returns the optimized result for the IRequestContext.
        /// Does not use or store results in any cache.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public object ToOptimizedResult <T>(IRequest request, T dto)
        {
            var compressionType = GetCompressionType(request);

            if (compressionType == null)
            {
                var contentType = request.ResponseContentType;

                switch (GetRealContentType(contentType))
                {
                case "application/xml":
                case "text/xml":
                case "text/xml; charset=utf-8":     //"text/xml; charset=utf-8" also matches xml
                    return(SerializeToXmlString(dto));

                case "application/json":
                case "text/json":
                    return(_jsonSerializer.SerializeToString(dto));
                }
            }

            // Do not use the memoryStreamFactory here, they don't place nice with compression
            using (var ms = new MemoryStream())
            {
                ContentTypes.Instance.SerializeToStream(request, dto, ms);
                ms.Position = 0;

                var responseHeaders = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                return(GetCompressedResult(ms, compressionType, responseHeaders, false, request.ResponseContentType).Result);
            }
        }
Example #31
0
        private object ToOptimizedResultInternal <T>(IRequest request, T dto, IDictionary <string, string> responseHeaders = null)
        {
            var contentType = request.ResponseContentType;

            switch (GetRealContentType(contentType))
            {
            case "application/xml":
            case "text/xml":
            case "text/xml; charset=utf-8":     //"text/xml; charset=utf-8" also matches xml
                return(GetHttpResult(request, SerializeToXmlString(dto), contentType, false, responseHeaders));

            case "application/json":
            case "text/json":
                return(GetHttpResult(request, _jsonSerializer.SerializeToString(dto), contentType, false, responseHeaders));

            default:
                break;
            }

            var isHeadRequest = string.Equals(request.Verb, "head", StringComparison.OrdinalIgnoreCase);

            var ms       = new MemoryStream();
            var writerFn = RequestHelper.GetResponseWriter(HttpListenerHost.Instance, contentType);

            writerFn(dto, ms);

            ms.Position = 0;

            if (isHeadRequest)
            {
                return(GetHttpResult(request, new byte[] { }, contentType, true, responseHeaders));
            }

            return(GetHttpResult(request, ms, contentType, true, responseHeaders));
        }
        public IEnumerable<ProgramInfo> GetPrograms(Stream stream, IJsonSerializer json, string channelId, ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);
            logger.Debug("[NextPvr] GetPrograms Response: {0}",json.SerializeToString(root));

            var listings = root.Guide.Listings;

            return listings.Where(i => string.Equals(i.Channel.channelOID.ToString(_usCulture), channelId, StringComparison.OrdinalIgnoreCase))
                .SelectMany(i => i.EPGEvents.Select(e => GetProgram(i.Channel, e.epgEventJSONObject.epgEvent)));
        }
        public bool? RecordingError(Stream stream, IJsonSerializer json,ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.epgEventJSONObject != null && root.epgEventJSONObject.rtn != null)
            {
                UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] RecordingError Response: {0}", json.SerializeToString(root)));
                return root.epgEventJSONObject.rtn.Error;
            }
            return null;
        }
        public bool LoggedIn(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.SIDValidation != null)
            {
                logger.Debug("[NextPvr] connection validation: {0}", json.SerializeToString(root));
                return root.SIDValidation.validated;
            }
            logger.Error("[NextPvr] Failed to validate your connection with NextPvr.");
            throw new ApplicationException("Failed to validate your connection with NextPvr.");
        }
Example #35
0
        public VLCObj GetVLCResponse(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.JSONVlcObject.VLC_Obj != null && root.JSONVlcObject.VLC_Obj.isVlcAvailable == true)
            {
                UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] VLC Response: {0}", json.SerializeToString(root)));
                return root.JSONVlcObject.VLC_Obj;
            }
            logger.Error("[NextPvr] Failed to load the VLC from NEWA");
            throw new ApplicationException("Failed to load the VLC from NEWA.");
        }
        public ClientKeys GetClientKeys(Stream stream, IJsonSerializer json,ILogger logger)
        {
            var root = json.DeserializeFromStream<RootObject>(stream);

            if (root.clientKeys != null && root.clientKeys.sid != null && root.clientKeys.salt != null)
            {
                logger.Debug("[NextPvr] ClientKeys: {0}", json.SerializeToString(root));
                return root.clientKeys;
            }
            logger.Error("[NextPvr] Failed to load the ClientKeys from NextPvr.");
            throw new ApplicationException("Failed to load the ClientKeys from NextPvr.");
        }
        public SeriesTimerInfo GetDefaultTimerInfo(Stream stream, IJsonSerializer json, ILogger logger)
        {
            var root = GetScheduleSettings(stream, json);
            logger.Debug("[NextPvr] GetDefaultTimerInfo Response: {0}", json.SerializeToString(root));

            return new SeriesTimerInfo
            {
                PostPaddingSeconds = root.post_padding_min * 60,
                PrePaddingSeconds = root.pre_padding_min * 60,
                RecordAnyChannel = root.allChannels,
                RecordAnyTime = root.recordAnyTimeslot,
                RecordNewOnly = root.onlyNew
            };
        }
        public IEnumerable<SeriesTimerInfo> GetSeriesTimers(Stream stream, IJsonSerializer json,ILogger logger)
        {
            if (stream == null)
            {
                logger.Error("[NextPvr] GetSeriesTimers stream == null");
                throw new ArgumentNullException("stream");
            }

            var root = json.DeserializeFromStream<RootObject>(stream);
            UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] GetSeriesTimers Response: {0}", json.SerializeToString(root)));

            return root.ManageResults
                .EPGEvents
                .Select(i => i.epgEventJSONObject)

                // Seeing epgEventJSONObject coming back null for some responses
                .Where(i => i != null)

                // Seeing recurring parents coming back with these reponses, for some reason
                .Where(i => i.recurr != null)
                .Select(GetSeriesTimerInfo);
        }
Example #39
0
 public static RecRule GetRecRule(Stream stream, IJsonSerializer json, ILogger logger)
 {
     var root = ParseRecRule(stream, json);
     UtilsHelper.DebugInformation(logger, string.Format("[MythTV] GetRecRule Response: {0}", json.SerializeToString(root)));
     return root.RecRule;
 }
Example #40
0
 public static CaptureCardList ParseCaptureCardList(Stream stream, IJsonSerializer json, ILogger logger)
 {
     var root = json.DeserializeFromStream<RootCaptureObject>(stream);
     UtilsHelper.DebugInformation(logger, string.Format("[MythTV] ParseCaptureCardList Response: {0}", json.SerializeToString(root)));
     return root.CaptureCardList;
 }
Example #41
0
 public Rtn GetVLCReturn(Stream stream, IJsonSerializer json, ILogger logger)
 {
     var root = json.DeserializeFromStream<RootObject>(stream);
     UtilsHelper.DebugInformation(logger,string.Format("[NextPvr] VLC Return: {0}", json.SerializeToString(root)));
     return root.JSONVlcObject.rtn;
 }
Example #42
0
        public static SeriesTimerInfo GetDefaultTimerInfo(Stream stream, IJsonSerializer json, ILogger logger)
        {
            SeriesTimerInfo val = null;

            var root = ParseRecRule(stream, json);
            UtilsHelper.DebugInformation(logger, string.Format("[MythTV] GetDefaultTimerInfo Response: {0}", json.SerializeToString(root)));
            

            //var root = ParseRecRules(stream, json);

            //foreach (var item in root.RecRuleList.RecRules)
            //{
            //    if (!item.Inactive && item.ChanId == "0")
            //    {
                    val = new SeriesTimerInfo()
                    {
                        PrePaddingSeconds = root.RecRule.StartOffset * 60,
                        PostPaddingSeconds = root.RecRule.EndOffset * 60,
                        RecordAnyChannel = !((root.RecRule.Filter & RecFilter.ThisChannel) == RecFilter.ThisChannel),
                        RecordAnyTime = !((root.RecRule.Filter & RecFilter.ThisDayTime) == RecFilter.ThisDayTime),
                        RecordNewOnly = ((root.RecRule.Filter & RecFilter.NewEpisode) == RecFilter.NewEpisode),
                        //IsPostPaddingRequired = root.RecRule.EndOffset != 0,
                        //IsPrePaddingRequired = root.RecRule.StartOffset != 0,
                    };
            //        break;
            //    }
            //}

            return val;
        }