Beispiel #1
0
        public async Task <IActionResult> SendPushBulletFromAppVeyor(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequest req)
        {
            try
            {
                var pushBulletApiKey        = Environment.GetEnvironmentVariable("PUSHBULLET_API_KEY", EnvironmentVariableTarget.Process);
                var pushBulletEncryptionKey = Environment.GetEnvironmentVariable("PUSHBULLET_ENCRYPTION_KEY", EnvironmentVariableTarget.Process);

                if (pushBulletApiKey.IsNullOrEmpty())
                {
                    return(new BadRequestErrorMessageResult("PushBelletApiKey cannot be found"));
                }

                if (pushBulletEncryptionKey.IsNullOrEmpty())
                {
                    return(new BadRequestErrorMessageResult("PushBulletEncryptionKey cannot be found"));
                }

                var requestBody = await req.GetRawBodyStringAsync();

                var appVeyor = JsonConvert.DeserializeObject <AppVeyor>(requestBody);

                Log.Logger.Information("AppVeyor Request Built: {@AppVeyor}", appVeyor);
                //_logger.LogInformation("AppVeyor Request Built: {@AppVeyor}", appVeyor);

                var client = new PushBulletClient(pushBulletApiKey, pushBulletEncryptionKey, TimeZoneInfo.Local);

                var channel = req.Headers["Channel"].ToString();
                var title   = $"{appVeyor.EventData.ProjectName} Release";
                var body    = $"There's a new version of {appVeyor.EventData.ProjectName}! Update: {appVeyor.EventData.CommitMessage}";
                var url     = $"https://www.nuget.org/packages/{appVeyor.EventData.ProjectName}/{appVeyor.EventData.BuildVersion}";

                if (channel.IsNullOrEmpty())
                {
                    return(new BadRequestErrorMessageResult($"Unknown channel from project {appVeyor.EventData.ProjectName}"));
                }

                var pushLinkRequest = new PushLinkRequest
                {
                    ChannelTag = channel,
                    Title      = title,
                    Url        = url,
                    Body       = body
                };

                var pushLinkResponse = await client.PushLink(pushLinkRequest);

                _logger.LogInformation("PushBullet Sent Link Message. {@PushLinkRequest} {@PushLinkResponse}", pushLinkRequest, pushLinkResponse);

                return(new OkObjectResult(pushLinkResponse));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending PushBullet message");
                return(new BadRequestErrorMessageResult(ex.Message));
            }
        }
        public void Send(Reminder reminder)
        {
            var message = $"Reminder: {reminder.Url}";

            var apiKey = reminder.User.UserNotificationType.Value;

            var client = new PushBulletClient(apiKey);

            client.PushAsync("Url Reminder", message, string.Empty).Wait();
        }
Beispiel #3
0
        public void TestInit()
        {
            ApiKey = "--YOURKEYGOESHERE--";
            Client = new PushBulletClient(ApiKey, "--YOUR-ENCRYPTION-PASSWORD--", TimeZoneInfo.Local);

            //Optional pass in your timezone
            //Client = new PushBulletClient(ApiKey, TimeZoneInfo.Local);

            //Or pass in a specific timezone
            //Client = new PushBulletClient(ApiKey, "password", TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
        }
Beispiel #4
0
        public async Task SendNotificationAsync(string subject, string body)
        {
            var configuration = _Configuration.Value();

            if (!configuration.IsEnabled())
            {
                _Logger.Log(LogLevel.Debug, "Pushbullet notification channel is not enabled");
                return;
            }

            var client = new PushBulletClient(configuration.AccessToken);
            await client.PushAsync(subject, body, null).NotNull();
        }
Beispiel #5
0
        public void TestInit()
        {
            var config = TestHelper.InitConfiguration();

            ApiKey = TestHelper.GetConfig("ApiKey");
            Client = new PushBulletClient(ApiKey);

            //Optional pass in your timezone
            //Client = new PushBulletClient(ApiKey, TimeZoneInfo.Local);

            //Or pass in a specific timezone
            //Client = new PushBulletClient(ApiKey, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
        }
Beispiel #6
0
        private async Task <List <PushResponse> > SendToDevices(PushBulletClient client, PushBullet pushBulletModel, string userId)
        {
            var devices = await client.CurrentUsersDevices();

            var deviceToSend = devices.Devices.Where(x => pushBulletModel.DeviceNickNames.Contains(x.Nickname)).ToList();

            if (!deviceToSend.Any())
            {
                throw new NullReferenceException($"No device nicknames matched {string.Join(", ", pushBulletModel.DeviceNickNames)}");
            }

            var responses = new List <PushResponse>();

            deviceToSend.ForEach(async device =>
            {
                if (string.IsNullOrEmpty(pushBulletModel.Url))
                {
                    var pushNoteRequest = new PushNoteRequest
                    {
                        DeviceIden = device.Iden,
                        Title      = pushBulletModel.Title,
                        Body       = pushBulletModel.Body
                    };

                    var pushNoteResponse = await client.PushNote(pushNoteRequest);

                    _logger.LogInformation("PushBullet Sent Message by {UserId}.", userId);

                    responses.Add(pushNoteResponse);
                }
                else
                {
                    var pushLinkRequest = new PushLinkRequest
                    {
                        DeviceIden = device.Iden,
                        Title      = pushBulletModel.Title,
                        Url        = pushBulletModel.Url,
                        Body       = pushBulletModel.Body
                    };

                    var pushLinkResponse = await client.PushLink(pushLinkRequest);

                    _logger.LogInformation("PushBullet Sent Link Message by {UserId}.", userId);

                    responses.Add(pushLinkResponse);
                }
            });

            return(responses);
        }
Beispiel #7
0
        static async Task Main(string[] args)
        {
            using var pbClient = new PushBulletClient();
            var       histories          = new Dictionary <Uri, State>();
            const int loopDelayInSeconds = 10;

            await _fileLogger.LogAsync("Starting");

            while (true)
            {
                var config   = Configuration.Default.WithDefaultLoader();
                var context  = BrowsingContext.New(config);
                var document = await context.OpenAsync("https://www.newegg.ca/p/pl?d=3080&N=100007708&isdeptsrh=1");

                var itemContainers = document.QuerySelectorAll("div.item-cell div.item-container");

                foreach (var itemContainer in itemContainers)
                {
                    try
                    {
                        var itemInfo  = itemContainer.Children.First(x => x.ClassName == "item-info");
                        var itemPromo = (IHtmlParagraphElement)itemInfo.Children.First(x => x.ClassName == "item-promo");
                        var itemTitle = (IHtmlAnchorElement)itemInfo.Children.First(x => x.ClassName == "item-title");

                        var newState = string.Equals(itemPromo.TextContent, "OUT OF STOCK", StringComparison.InvariantCultureIgnoreCase) ? State.OutOfStock : State.InStock;
                        var uri      = new UriBuilder(itemTitle.HostName, itemTitle.PathName).Uri;

                        if (histories.ContainsKey(uri) && histories[uri] != newState && newState != State.OutOfStock)
                        {
                            await _fileLogger.LogAsync($"New state for {itemTitle.InnerHtml} : {newState}");

                            await pbClient.NotifyAsync(uri.ToString());
                        }

                        histories[uri] = newState;
                    }
                    catch (Exception e)
                    {
                        await _fileLogger.LogAsync(e);
                    }
                }

                await Task.Delay(loopDelayInSeconds * 1000);

                var outOfStock = histories.Count(x => x.Value == State.OutOfStock);
                await _fileLogger.LogAsync($"{DateTime.Now} - Out of stock : {outOfStock} - In stock {histories.Count - outOfStock}");
            }
        }
Beispiel #8
0
        public async Task <IActionResult> Post([FromBody] PushBullet pushBulletModel)
        {
            var userAuthKey = Request.Headers["AuthKey"].ToString();

            var user = _userManager.FindByApiAuthKeyAsync(userAuthKey);

            try
            {
                var pushBulletUserSettings = await _pushBulletAppService.RetrieveDecryptedPushBulletSettingsByUserId(user.Id);

                var pushBulletApiKey        = pushBulletUserSettings.ApiKey;
                var pushBulletEncryptionKey = pushBulletUserSettings.EncryptionKey;

                if (pushBulletApiKey.IsNullOrEmpty())
                {
                    return(new BadRequestObjectResult("PushBullet Api Key cannot be found"));
                }

                if (pushBulletEncryptionKey.IsNullOrEmpty())
                {
                    return(new BadRequestObjectResult("PushBullet Encryption Key cannot be found"));
                }

                var client = new PushBulletClient(pushBulletApiKey, pushBulletEncryptionKey, TimeZoneInfo.Local);

                if (!string.IsNullOrEmpty(pushBulletModel.Channel) && (pushBulletModel.DeviceNickNames == null || !pushBulletModel.DeviceNickNames.Any()))
                {
                    var sendToChannel = await SendToChannel(client, pushBulletModel, user.Id);

                    return(new OkObjectResult(sendToChannel));
                }

                if (string.IsNullOrEmpty(pushBulletModel.Channel) && pushBulletModel.DeviceNickNames != null && pushBulletModel.DeviceNickNames.Any())
                {
                    var sendToDevices = await SendToDevices(client, pushBulletModel, user.Id);

                    return(new OkObjectResult(sendToDevices));
                }

                return(new ConflictObjectResult("Sending messages to devices and channels on the same request is not supported."));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unable to send PushBullet messages for {UserId} using the PushBullet model {@PushBullet}", user.Id, pushBulletModel);
                return(new BadRequestObjectResult(ex));
            }
        }
Beispiel #9
0
        private async Task <List <PushResponse> > SendToChannel(PushBulletClient client, PushBullet pushBulletModel, string userId)
        {
            var responses = new List <PushResponse>();

            if (string.IsNullOrEmpty(pushBulletModel.Url))
            {
                var pushNoteRequest = new PushNoteRequest
                {
                    ChannelTag = pushBulletModel.Channel,
                    Title      = pushBulletModel.Title,
                    Body       = pushBulletModel.Body
                };

                var pushNoteResponse = await client.PushNote(pushNoteRequest);

                _logger.LogInformation("PushBullet Sent Message by {UserId}.", userId);

                responses.Add(pushNoteResponse);
            }
            else
            {
                var pushLinkRequest = new PushLinkRequest
                {
                    ChannelTag = pushBulletModel.Channel,
                    Title      = pushBulletModel.Title,
                    Url        = pushBulletModel.Url,
                    Body       = pushBulletModel.Body
                };

                var pushLinkResponse = await client.PushLink(pushLinkRequest);

                _logger.LogInformation("PushBullet Sent Link Message by {UserId}.", userId);

                responses.Add(pushLinkResponse);
            }

            return(responses);
        }
Beispiel #10
0
 internal Chat(Model model, PushBulletClient client)
 {
     _model  = model;
     _client = client;
 }
Beispiel #11
0
 internal Device(Model model, PushBulletClient client)
 {
     _model  = model;
     _client = client;
 }
Beispiel #12
0
 internal Subscription(Model model, PushBulletClient client)
 {
     _client = client;
     _model  = model;
 }