Exemplo n.º 1
0
        private async Task PostAsync(TestNotification request)
        {
            var options = GetOptions(request.UserID);

            var parameters = new Dictionary <string, string>
            {
                { "token", options.Token },
                { "user", options.UserKey },
                { "title", "Test Notification" },
                { "message", "This is a test notification from MediaBrowser" }
            };

            _logger.Debug("Pushover <TEST> to {0} - {1}", options.Token, options.UserKey);

            var httpRequestOptions = new HttpRequestOptions
            {
                Url = "https://api.pushover.net/1/messages.json",
                CancellationToken = CancellationToken.None
            };

            httpRequestOptions.SetPostData(parameters);

            using (await _httpClient.Post(httpRequestOptions).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 2
0
        public async Task PostAsync(TestNotification request)
        {
            var options = GetOptions(request.UserID);

            var slackMessage = new SlackMessage {
                channel = options.Channel, icon_emoji = options.Emoji, username = options.UserName, text = "This is a test notification from Emby"
            };

            var parameters = new Dictionary <string, string> {
            };

            parameters.Add("payload", _jsonSerializer.SerializeToString(slackMessage));

            _logger.Debug("Slack <TEST> to {0}", options.Channel);

            var httpRequestOptions = new HttpRequestOptions
            {
                Url = options.SlackWebHookURI,
                CancellationToken = CancellationToken.None
            };

            httpRequestOptions.SetPostData(parameters);

            using (await _httpClient.Post(httpRequestOptions).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 3
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

            var parameters = new Dictionary <string, string>
            {
                { "apikey", options.Token },
                { "application", "Emby" }
            };

            if (string.IsNullOrEmpty(request.Description))
            {
                parameters.Add("event", request.Name);
                parameters.Add("description", "-");
            }
            else
            {
                parameters.Add("event", request.Name);
                parameters.Add("description", request.Description);
            }

            _logger.Debug("NotifyMyAndroid to {0} - {1} - {2}", options.Token, request.Name, request.Description);

            var httpRequestOptions = new HttpRequestOptions
            {
                Url = "https://www.notifymyandroid.com/publicapi/notify",
                CancellationToken = cancellationToken
            };

            httpRequestOptions.SetPostData(parameters);

            using (await _httpClient.Post(httpRequestOptions).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 4
0
        private async Task PostAsync(TestNotification request)
        {
            var options = GetOptions(request.UserID);

            var parameters = new Dictionary <string, string>
            {
                { "AuthorizationToken", options.Token },
                { "Title", "Test Notification" },
                { "Body", "This is a test notification from MediaBrowser" }
            };

            _logger.Debug("PushAlot <TEST> to {0}", options.Token);

            var httpRequestOptions = new HttpRequestOptions
            {
                Url = "https://pushalot.com/api/sendmessage",
                CancellationToken = CancellationToken.None
            };

            httpRequestOptions.SetPostData(parameters);

            using (await _httpClient.Post(httpRequestOptions).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 5
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

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

            _logger.Debug("PushBullet to Token : {0} - {1} - {2}", options.Token, options.DeviceId, request.Description);
            var    _httpRequest = new HttpRequestOptions();
            string authInfo     = options.Token;

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

            _httpRequest.RequestHeaders["Authorization"] = "Basic " + authInfo;

            _httpRequest.Url = "https://api.pushbullet.com/v2/pushes";

            _httpRequest.SetPostData(parameters);

            using (await _httpClient.Post(_httpRequest).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 6
0
        private async Task UpdateServerRegistration(string wanApiAddress)
        {
            var url = "Servers";

            url  = GetConnectUrl(url);
            url += "?id=" + ConnectServerId;

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None
            };

            options.SetPostData(new Dictionary <string, string>
            {
                { "name", _appHost.FriendlyName },
                { "url", wanApiAddress },
                { "systemid", _appHost.SystemId }
            });

            options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);

            // No need to examine the response
            using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
            {
            }
        }
Exemplo n.º 7
0
        public async Task <ConnectSupporterSummary> GetConnectSupporterSummary()
        {
            if (!_securityManager.IsMBSupporter)
            {
                return(new ConnectSupporterSummary());
            }

            var url = GetConnectUrl("keyAssociation");

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None
            };

            var postData = new Dictionary <string, string>
            {
                { "serverId", ConnectServerId },
                { "supporterKey", _securityManager.SupporterKey }
            };

            options.SetPostData(postData);

            SetServerAccessToken(options);
            SetApplicationHeader(options);

            // No need to examine the response
            using (var stream = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
            {
                return(_json.DeserializeFromStream <ConnectSupporterSummary>(stream));
            }
        }
Exemplo n.º 8
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

            var parameters = new Dictionary <string, string>
            {
                { "AuthorizationToken", options.Token },
            };

            if (string.IsNullOrEmpty(request.Description))
            {
                parameters.Add("Body", request.Name);
            }
            else
            {
                parameters.Add("Title", request.Name);
                parameters.Add("Body", request.Description);
            }

            _logger.Debug("PushAlot to {0}", options.Token);

            var httpRequestOptions = new HttpRequestOptions
            {
                Url = "https://pushalot.com/api/sendmessage",
                CancellationToken = cancellationToken
            };

            httpRequestOptions.SetPostData(parameters);

            using (await _httpClient.Post(httpRequestOptions).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 9
0
        public async Task PostAsync(TestNotification request)
        {
            var options = GetOptions(request.UserID);

            var parameters = new Dictionary <string, string>
            {
                { "type", "note" },
                { "title", "Test Notification" },
                { "body", "This is a test notification from MediaBrowser" }
            };

            var _httpRequest = new HttpRequestOptions();

            //Create Basic HTTP Auth Header...

            string authInfo = options.Token;

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

            _httpRequest.RequestHeaders["Authorization"] = "Basic " + authInfo;

            _httpRequest.Url = "https://api.pushbullet.com/v2/pushes";

            _httpRequest.SetPostData(parameters);

            using (await _httpClient.Post(_httpRequest).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 10
0
        private async Task PostAsync(TestNotification request)
        {
            var options = GetOptions(request.UserID);

            var parameters = new Dictionary <string, string>
            {
                { "apikey", options.Token },
                { "event", "Test Notification" },
                { "description", "This is a test notification from MediaBrowser" },
                { "application", "Emby" }
            };

            _logger.Debug("NotifyMyAndroid <TEST> to {0}", options.Token);

            var httpRequestOptions = new HttpRequestOptions
            {
                Url = "https://www.notifymyandroid.com/publicapi/notify",
                CancellationToken = CancellationToken.None
            };

            httpRequestOptions.SetPostData(parameters);

            using (await _httpClient.Post(httpRequestOptions).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 11
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

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

            // message parameter is required. If it is sent as null
            // put name as message

            if (string.IsNullOrEmpty(request.Description))
            {
                body.Add("message", HttpUtility.UrlEncode(request.Name));
            }
            else
            {
                if (!string.IsNullOrEmpty(request.Name))
                {
                    body.Add("title", HttpUtility.UrlEncode(request.Name));
                }
                body.Add("message", HttpUtility.UrlEncode(request.Description));
            }

            body.Add("priority", options.Priority.ToString());

            var requestOptions = new HttpRequestOptions
            {
                Url = options.Url.TrimEnd('/') + $"/message?token={options.Token}"
            };

            requestOptions.SetPostData(body);

            await _httpClient.Post(requestOptions).ConfigureAwait(false);
        }
Exemplo n.º 12
0
        public async Task Authenticate(string username, string passwordMd5)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException("username");
            }

            if (string.IsNullOrWhiteSpace(passwordMd5))
            {
                throw new ArgumentNullException("passwordMd5");
            }

            var options = new HttpRequestOptions
            {
                Url = GetConnectUrl("user/authenticate")
            };

            options.SetPostData(new Dictionary <string, string>
            {
                { "userName", username },
                { "password", passwordMd5 }
            });

            SetApplicationHeader(options);

            // No need to examine the response
            using (var response = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
            {
            }
        }
Exemplo n.º 13
0
        private async Task <UserLinkResult> SendNewUserInvitation(string fromName, string email)
        {
            var url = GetConnectUrl("users/invite");

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None
            };

            var postData = new Dictionary <string, string>
            {
                { "email", email },
                { "requesterUserName", fromName }
            };

            options.SetPostData(postData);
            SetApplicationHeader(options);

            // No need to examine the response
            using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
            {
            }

            return(new UserLinkResult
            {
                IsNewUserInvitation = true,
                GuestDisplayName = email
            });
        }
Exemplo n.º 14
0
        public async Task RemoveConnectSupporter(string id)
        {
            if (!_securityManager.IsMBSupporter)
            {
                throw new InvalidOperationException();
            }

            var url = GetConnectUrl("keyAssociation");

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None
            };

            var postData = new Dictionary <string, string>
            {
                { "serverId", ConnectServerId },
                { "supporterKey", _securityManager.SupporterKey },
                { "userId", id }
            };

            options.SetPostData(postData);

            SetServerAccessToken(options);
            SetApplicationHeader(options);

            // No need to examine the response
            using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
            {
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Performs a POST request
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="postData">Params to add to the POST data.</param>
        /// <returns>stream on success, null on failure</returns>
        public async Task <Stream> Post(HttpRequestOptions options, Dictionary <string, string> postData)
        {
            options.SetPostData(postData);

            var response = await Post(options).ConfigureAwait(false);

            return(response.Content);
        }
Exemplo n.º 16
0
        private async Task <UserLinkResult> InviteUserInternal(string sendingUserId, string connectUsername)
        {
            if (string.IsNullOrWhiteSpace(connectUsername))
            {
                throw new ArgumentNullException("connectUsername");
            }

            var connectUser = await GetConnectUser(new ConnectUserQuery
            {
                Name = connectUsername
            }, CancellationToken.None).ConfigureAwait(false);

            if (!connectUser.IsActive)
            {
                throw new ArgumentException("The Media Browser account has been disabled.");
            }

            var url = GetConnectUrl("ServerAuthorizations");

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None
            };

            var accessToken = Guid.NewGuid().ToString("N");
            var sendingUser = GetUser(sendingUserId);

            var postData = new Dictionary <string, string>
            {
                { "serverId", ConnectServerId },
                { "userId", connectUser.Id },
                { "userType", "Guest" },
                { "accessToken", accessToken },
                { "requesterUserName", sendingUser.ConnectUserName }
            };

            options.SetPostData(postData);

            SetServerAccessToken(options);

            var result = new UserLinkResult();

            // No need to examine the response
            using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
            {
                var response = _json.DeserializeFromStream <ServerUserAuthorizationResponse>(stream);

                result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
            }

            await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);

            return(result);
        }
Exemplo n.º 17
0
        public static async Task Track(IHttpClient _httpClient, IApplicationHost _appHost, IServerConfigurationManager _serverConfigurationManager, string sessionControl, string task, CancellationToken cancellationToken)
        {
            var config = Plugin.Instance.Configuration;

            if (string.IsNullOrEmpty(config.InstallationID))
            {
                config.InstallationID = Guid.NewGuid().ToString();
                Plugin.Instance.SaveConfiguration();
            }

            try
            {
                string version = Plugin.Instance.Version.ToString();

                var values = new Dictionary <string, string>
                {
                    { "v", "1" },
                    { "t", "event" },
                    { "tid", "UA-92060336-1" },
                    { "cid", config.InstallationID },
                    { "ec", task },
                    { "ea", version },
                    { "el", config.ChannelRefreshCount.ToString() },
                    { "an", "BlurN" },
                    { "aid", "MediaBrowser.Channels.BlurN" },
                    { "av", version },
                    { "ds", "app" },
                    { "sc", sessionControl },
                    { "ul", _serverConfigurationManager.Configuration.UICulture.ToLower() },
                    { "z", new Random().Next(1, 2147483647).ToString() }
                };

                var options = new HttpRequestOptions
                {
                    Url = "https://www.google-analytics.com/collect",
                    CancellationToken      = cancellationToken,
                    LogRequest             = false,
                    LogErrors              = false,
                    BufferContent          = false,
                    LogErrorResponseBody   = false,
                    EnableDefaultUserAgent = true,
                    EnableHttpCompression  = true,
                    DecompressionMethod    = CompressionMethod.Gzip
                };

                options.SetPostData(values);

                var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Plugin.DebugLogger($"Failed to track usage with GA: {ex.Message}");
            }
        }
Exemplo n.º 18
0
        private async Task CancelAuthorizationByConnectUserId(string connectUserId)
        {
            if (string.IsNullOrWhiteSpace(connectUserId))
            {
                throw new ArgumentNullException("connectUserId");
            }
            if (string.IsNullOrWhiteSpace(ConnectServerId))
            {
                throw new ArgumentNullException("ConnectServerId");
            }

            var url = GetConnectUrl("ServerAuthorizations");

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None,
                BufferContent     = false
            };

            var postData = new Dictionary <string, string>
            {
                { "serverId", ConnectServerId },
                { "userId", connectUserId }
            };

            options.SetPostData(postData);

            SetServerAccessToken(options);
            SetApplicationHeader(options);

            try
            {
                // No need to examine the response
                using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
                {
                }
            }
            catch (HttpException ex)
            {
                // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation

                if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
                {
                    throw;
                }

                _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
            }
        }
Exemplo n.º 19
0
        public async Task ReportAppUsage(ClientInfo app, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(app.DeviceId))
            {
                throw new ArgumentException("Client info must have a device Id");
            }

            _logger.Info("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}",
                         app.AppName ?? "Unknown App",
                         app.AppVersion ?? "Unknown",
                         app.DeviceId,
                         app.DeviceName ?? "Unknown");

            cancellationToken.ThrowIfCancellationRequested();

            var data = new Dictionary <string, string>
            {
                { "feature", app.AppName ?? "Unknown App" },
                { "serverid", _applicationHost.SystemId },
                { "deviceid", app.DeviceId },
                { "mac", app.DeviceId },
                { "ver", app.AppVersion ?? "Unknown" },
                { "platform", app.DeviceName },
            };

            var logErrors = false;

#if DEBUG
            logErrors = true;
#endif
            var options = new HttpRequestOptions
            {
                Url = MbAdminUrl + "service/registration/ping",
                CancellationToken = cancellationToken,

                // Seeing block length errors
                EnableHttpCompression = false,

                LogRequest    = false,
                LogErrors     = logErrors,
                BufferContent = false
            };

            options.SetPostData(data);

            using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 20
0
        private async Task RemoveLink(User user, string connectUserId)
        {
            if (!string.IsNullOrWhiteSpace(connectUserId))
            {
                var url = GetConnectUrl("ServerAuthorizations");

                var options = new HttpRequestOptions
                {
                    Url = url,
                    CancellationToken = CancellationToken.None
                };

                var postData = new Dictionary <string, string>
                {
                    { "serverId", ConnectServerId },
                    { "userId", connectUserId }
                };

                options.SetPostData(postData);

                SetServerAccessToken(options);

                try
                {
                    // No need to examine the response
                    using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
                    {
                    }
                }
                catch (HttpException ex)
                {
                    // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation

                    if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
                    {
                        throw;
                    }

                    _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
                }
            }

            user.ConnectAccessKey = null;
            user.ConnectUserName  = null;
            user.ConnectUserId    = null;
            user.ConnectLinkType  = UserLinkType.LinkedUser;

            await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
        }
Exemplo n.º 21
0
        public async Task ReportServerUsage(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var data = new Dictionary <string, string>
            {
                { "feature", _applicationHost.Name },
                { "mac", _applicationHost.SystemId },
                { "serverid", _applicationHost.SystemId },
                { "deviceid", _applicationHost.SystemId },
                { "ver", _applicationHost.ApplicationVersion.ToString() },
                { "platform", _applicationHost.OperatingSystemDisplayName },
                { "isservice", _applicationHost.IsRunningAsService.ToString().ToLower() }
            };

            var users = _userManager.Users.ToList();

            data["localusers"]  = users.Count(i => !i.ConnectLinkType.HasValue).ToString(CultureInfo.InvariantCulture);
            data["guests"]      = users.Count(i => i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest).ToString(CultureInfo.InvariantCulture);
            data["linkedusers"] = users.Count(i => i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.LinkedUser).ToString(CultureInfo.InvariantCulture);

            data["plugins"] = string.Join(",", _applicationHost.Plugins.Select(i => i.Id).ToArray());

            var logErrors = false;

#if DEBUG
            logErrors = true;
#endif
            var options = new HttpRequestOptions
            {
                Url = MbAdminUrl + "service/registration/ping",
                CancellationToken = cancellationToken,

                // Seeing block length errors
                EnableHttpCompression = false,

                LogRequest    = false,
                LogErrors     = logErrors,
                BufferContent = false
            };

            options.SetPostData(data);

            using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 22
0
        private async Task TryUploadUserPreferences(User user, CancellationToken cancellationToken)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (string.IsNullOrEmpty(user.ConnectUserId))
            {
                return;
            }
            if (string.IsNullOrEmpty(ConnectAccessKey))
            {
                return;
            }

            var url = GetConnectUrl("user/preferences");

            url += "?userId=" + user.ConnectUserId;
            url += "&key=userpreferences";

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken
            };

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

            postData["data"] = _json.SerializeToString(ConnectUserPreferences.FromUserConfiguration(user.Configuration));
            options.SetPostData(postData);

            SetServerAccessToken(options);
            SetApplicationHeader(options);

            try
            {
                // No need to examine the response
                using (var stream = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
                {
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error uploading user preferences", ex);
            }
        }
Exemplo n.º 23
0
        private async Task UpdateServerRegistration(string wanApiAddress, string localAddress)
        {
            if (string.IsNullOrWhiteSpace(wanApiAddress))
            {
                throw new ArgumentNullException("wanApiAddress");
            }

            if (string.IsNullOrWhiteSpace(ConnectServerId))
            {
                throw new ArgumentNullException("ConnectServerId");
            }

            var url = "Servers";

            url  = GetConnectUrl(url);
            url += "?id=" + ConnectServerId;

            var postData = new Dictionary <string, string>
            {
                { "name", _appHost.FriendlyName },
                { "url", wanApiAddress },
                { "systemId", _appHost.SystemId }
            };

            if (!string.IsNullOrWhiteSpace(localAddress))
            {
                postData["localAddress"] = localAddress;
            }

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None,
                BufferContent     = false
            };

            options.SetPostData(postData);

            SetServerAccessToken(options);
            SetApplicationHeader(options);

            // No need to examine the response
            using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
            {
            }
        }
Exemplo n.º 24
0
        protected async Task <TResponse> Post <TRequest, TResponse>(TRequest request) where TRequest : BaseAuthedRequest where TResponse : BaseResponse
        {
            var data = request.ToDictionary();

            //Append the signature
            Helpers.AppendSignature(ref data);

            var options = new HttpRequestOptions
            {
                Url                   = BuildPostUrl(request.Secure),
                ResourcePool          = Plugin.LastfmResourcePool,
                RequestContentType    = "application/json",
                CancellationToken     = CancellationToken.None,
                TimeoutMs             = 120000,
                LogErrorResponseBody  = false,
                LogRequest            = true,
                BufferContent         = false,
                EnableHttpCompression = false,
                EnableKeepAlive       = false
            };

            options.SetPostData(data);

            using (var httpResponseInfo = await _httpClient.Post(options))
            {
                try
                {
                    var result = _jsonSerializer.DeserializeFromStream <TResponse>(httpResponseInfo.Content);

                    //Lets Log the error here to ensure all errors are logged
                    if (result.IsError())
                    {
                        Plugin.Logger.Error(result.message);
                    }

                    return(result);
                }
                catch (Exception e)
                {
                    Plugin.Logger.Debug(e.Message);
                }

                return(null);
            }
        }
Exemplo n.º 25
0
        private async Task CreateServerRegistration(string wanApiAddress, string localAddress)
        {
            if (string.IsNullOrWhiteSpace(wanApiAddress))
            {
                throw new ArgumentNullException("wanApiAddress");
            }

            var url = "Servers";

            url = GetConnectUrl(url);

            var postData = new Dictionary <string, string>
            {
                { "name", _appHost.FriendlyName },
                { "url", wanApiAddress },
                { "systemId", _appHost.SystemId }
            };

            if (!string.IsNullOrWhiteSpace(localAddress))
            {
                postData["localAddress"] = localAddress;
            }

            var options = new HttpRequestOptions
            {
                Url = url,
                CancellationToken = CancellationToken.None,
                BufferContent     = false
            };

            options.SetPostData(postData);
            SetApplicationHeader(options);

            using (var response = await _httpClient.Post(options).ConfigureAwait(false))
            {
                var data = _json.DeserializeFromStream <ServerRegistrationResponse>(response.Content);

                _data.ServerId  = data.Id;
                _data.AccessKey = data.AccessKey;

                CacheData();
            }
        }
Exemplo n.º 26
0
        public async Task SendNotification(UserNotification request, CancellationToken cancellationToken)
        {
            var options = GetOptions(request.User);

            var parameters = new Dictionary <string, string>
            {
                { "token", options.Token },
                { "user", options.UserKey },
            };

            // TODO: Improve this with escaping based on what PushOver api requires
            var messageTitle = request.Name.Replace("&", string.Empty);

            if (!string.IsNullOrEmpty(options.DeviceName))
            {
                parameters.Add("device", options.DeviceName);
            }

            if (string.IsNullOrEmpty(request.Description))
            {
                parameters.Add("message", messageTitle);
            }
            else
            {
                parameters.Add("title", messageTitle);
                parameters.Add("message", request.Description);
            }

            _logger.Debug("PushOver to Token : {0} - {1} - {2}", options.Token, options.UserKey, request.Description);

            var httpRequestOptions = new HttpRequestOptions
            {
                Url = "https://api.pushover.net/1/messages.json",
                CancellationToken = cancellationToken
            };

            httpRequestOptions.SetPostData(parameters);

            using (await _httpClient.Post(httpRequestOptions).ConfigureAwait(false))
            {
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Send a POST request to the LastFM Api
        /// </summary>
        /// <typeparam name="TRequest">The type of the request</typeparam>
        /// <typeparam name="TResponse">The type of the response</typeparam>
        /// <param name="request">The request</param>
        /// <returns>A response with type TResponse</returns>
        public async Task <TResponse> Post <TRequest, TResponse>(TRequest request) where TRequest : BaseRequest where TResponse : BaseResponse
        {
            var data = request.ToDictionary();

            //Append the signature
            Helpers.AppendSignature(ref data);

            var options = new HttpRequestOptions
            {
                Url                   = BuildPostUrl(request.Secure),
                ResourcePool          = Plugin.LastfmResourcePool,
                CancellationToken     = CancellationToken.None,
                EnableHttpCompression = false,
            };

            options.SetPostData(EscapeDictionary(data));

            using (var response = await _httpClient.Post(options))
            {
                using (var stream = response.Content)
                {
                    try
                    {
                        var result = _jsonSerializer.DeserializeFromStream <TResponse>(stream);

                        //Lets Log the error here to ensure all errors are logged
                        if (result.IsError())
                        {
                            Plugin.Logger.Error(result.Message);
                        }

                        return(result);
                    }
                    catch (Exception e)
                    {
                        Plugin.Logger.Debug(e.Message);
                    }
                }

                return(null);
            }
        }
        private async Task PostAsync(TestNotification request)
        {
            var options = GetOptions(request.UserId);

            var body = new Dictionary <string, string>
            {
                { "message", HttpUtility.UrlEncode("This is a test notification from Jellyfin") },
                { "title", HttpUtility.UrlEncode("Test Notification") },
                { "priority", options.Priority.ToString() }
            };

            var requestOptions = new HttpRequestOptions
            {
                Url = options.Url.TrimEnd('/') + $"/message?token={options.Token}"
            };

            requestOptions.SetPostData(body);

            await _httpClient.Post(requestOptions).ConfigureAwait(false);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Gets all available packages.
        /// </summary>
        /// <returns>Task{List{PackageInfo}}.</returns>
        public async Task <List <PackageInfo> > GetAvailablePackages(CancellationToken cancellationToken,
                                                                     bool withRegistration      = true,
                                                                     string packageType         = null,
                                                                     Version applicationVersion = null)
        {
            if (withRegistration)
            {
                var data = new Dictionary <string, string>
                {
                    { "key", _securityManager.SupporterKey },
                    { "mac", _applicationHost.SystemId },
                    { "systemid", _applicationHost.SystemId }
                };

                var options = new HttpRequestOptions
                {
                    Url = "https://www.mb3admin.com/admin/service/package/retrieveall?includeAllRuntimes=true",
                    CancellationToken = cancellationToken
                };

                options.SetPostData(data);

                using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
                {
                    using (var json = response.Content)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        var packages = _jsonSerializer.DeserializeFromStream <PackageInfo[]>(json);

                        return(FilterPackages(packages, packageType, applicationVersion));
                    }
                }
            }
            else
            {
                var packages = await GetAvailablePackagesWithoutRegistrationInfo(cancellationToken).ConfigureAwait(false);

                return(FilterPackages(packages, packageType, applicationVersion));
            }
        }
Exemplo n.º 30
0
        public async Task ReportServerUsage(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var data = new Dictionary <string, string>
            {
                { "feature", _applicationHost.Name },
                { "mac", _applicationHost.SystemId },
                { "serverid", _applicationHost.SystemId },
                { "deviceid", _applicationHost.SystemId },
                { "ver", _applicationHost.ApplicationVersion.ToString() },
                { "platform", _applicationHost.OperatingSystemDisplayName }
            };

            data["plugins"] = string.Join(",", _applicationHost.Plugins.Select(i => i.Id).ToArray());

            var logErrors = false;

#if DEBUG
            logErrors = true;
#endif
            var options = new HttpRequestOptions
            {
                Url = MbAdminUrl + "service/registration/ping",
                CancellationToken = cancellationToken,

                // Seeing block length errors
                EnableHttpCompression = false,

                LogRequest    = false,
                LogErrors     = logErrors,
                BufferContent = false
            };

            options.SetPostData(data);

            using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
            {
            }
        }