public async void PushBulletPushNoteTest()
        {
            try
            {
                var devices = await Client.CurrentUsersDevices();

                Assert.IsNotNull(devices);

                var device = devices.Devices.FirstOrDefault(o => o.Nickname == TestHelper.GetConfig("Device"));
                Assert.IsNotNull(device, "Could not find the device specified.");

                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    DeviceIden = device.Iden,
                    Title      = "hello world",
                    Body       = "This is a test from my C# wrapper."
                };

                var response = await Client.PushNote(reqeust);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        public void SendNotification(Sites sites)
        {
            PushbulletClient client = new PushbulletClient("o.gPbFYLv0VHGepKmD77nJElg9FWSbGQca");

            //If you don't know your device_iden, you can always query your devices
            var devices = client.CurrentUsersDevices();

            var device = devices.Devices.Where(o => o.Iden == "ujuXuA1sqOqsjAnjr1gpPw");

            String message = "";

            for (int x = 0; x < sites.siteCount(); x++)
            {
                message = message + "Site " + sites.getSite(x).id + " has a value of: " + sites.getSite(x).price + "\n";
            }

            if (device != null)
            {
                PushNoteRequest request = new PushNoteRequest()
                {
                    DeviceIden = "ujuXuA1sqOqsjAnjr1gpPw",
                    Title      = "Value has changed",
                    Body       = message
                };
                PushResponse response = client.PushNote(request);
            }
        }
Exemple #3
0
        protected override void OnSendNotification(string title, string message, string testing)
        {
            if (!MainControl.PushBulletCheckbox.Checked)
            {
                Logger.Write("UI: Pushbullet notifications are disabled", LogLevel.Debug);
                return;
            }

            if (string.IsNullOrWhiteSpace(MainControl.PushBulletTokenTextBox.Text))
            {
                Logger.Write("UI: Pushbullet Token is missing", LogLevel.Error);
                return;
            }

            try
            {
                var client  = new PushbulletClient(MainControl.PushBulletTokenTextBox.Text);
                var request = new PushNoteRequest {
                    Body = message, Title = title
                };
                if (!string.IsNullOrWhiteSpace(MainControl.PushBulletDeviceIdTextBox.Text))
                {
                    request.DeviceIden = MainControl.PushBulletDeviceIdTextBox.Text;
                }

                var response = client.PushNote(request);

                Logger.Write($"UI: Message pushed to Pushbullet with Id {response.ReceiverIden}", LogLevel.Info);
            }
            catch (Exception ex)
            {
                Logger.Write(ex, "UI: Unable to push Pushbullet notification", LogLevel.Error);
            }
        }
        public void Send(string title, string message)
        {
            Console.WriteLine();
            Console.WriteLine("--- " + title);
            Console.WriteLine("> " + message);
            Console.WriteLine("---");

            if (!string.IsNullOrWhiteSpace(_apiKey))
            {
                var client = new PushbulletClient(_apiKey);
                var currentUserInformation = client.CurrentUsersInformation();

                if (currentUserInformation != null)
                {
                    PushNoteRequest reqeust = new PushNoteRequest()
                    {
                        Email = currentUserInformation.Email,
                        Title = title,
                        Body  = message
                    };

                    client.PushNote(reqeust);
                }
            }
        }
Exemple #5
0
        public static void SendPushbulletMessage(string title, string message)
        {
            try
            {
                PushbulletClient client;

                User currentUserInformation;

                client = new PushbulletClient("o.7DsY57f3IS7FXOejdR8ncoIXvU3n2yF0");

                currentUserInformation = client.CurrentUsersInformation();

                if (currentUserInformation != null)
                {
                    PushNoteRequest request = new PushNoteRequest()
                    {
                        Email = currentUserInformation.Email,
                        Title = title,
                        Body  = message
                    };

                    PushResponse response = client.PushNote(request);
                }
            }
            catch (Exception)
            {
                // we ignore any pushbullet problems
            }
        }
        public void PushNote(string title, string body)
        {
            PushNoteRequest request = new PushNoteRequest();

            request.Title = title;
            request.Body  = body;
            Client.PushNote(request);
        }
Exemple #7
0
        private static void ReportBack(string message)
        {
            var client = CFG.Configuration.Default.PBClient;

            var pushNote = new PushNoteRequest()
            {
                DeviceIden = CFG.Configuration.Default.PBTargetDeviceId,
                Body       = message,
                Title      = "Torrent added successfully"
            };

            client.PushNote(pushNote);
        }
Exemple #8
0
        private void Envianotificação(string texto)
        {
            PushbulletClient client = new PushbulletClient("o.ijhfmbKRI8JAAAjaorTvs3n1I1oHo4qH");
            //var devices = client.CurrentUsersDevices();
            //var device = devices.Devices.Where(o => o.Manufacturer == "Apple").FirstOrDefault();
            PushNoteRequest request1 = new PushNoteRequest
            {
                DeviceIden = "ujy7mvFtukmsjE5NB4jvkO",
                Title      = texto,
                Body       = texto
            };

            PushResponse response1 = client.PushNote(request1);
        }
Exemple #9
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);
        }
        public void Notify(Notification notification, IEnumerable <string> deviceIds)
        {
            if (deviceIds == null)
            {
                return;
            }
            if (!deviceIds.Any())
            {
                return;
            }
            if (!IsPusbulletApiKeyValid())
            {
                return;
            }

            PushbulletClient client = new PushbulletClient(ApiKey);
            var response            = client.CurrentUsersDevices();

            List <Device> devices = new List <Device>();

            foreach (var device in response.Devices)
            {
                if (deviceIds.Any(_ => _ == device.Iden))
                {
                    devices.Add(device);
                }
            }

            foreach (var device in devices)
            {
                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    DeviceIden = device.Iden,
                    Title      = notification.Title,
                    Body       = notification.Body
                };

                try {
                    client.PushNote(reqeust);
                }
                catch (Exception e) {
                    if (Debugger.IsAttached)
                    {
                        throw e;
                    }
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Pushes the note.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="ignoreEmptyFields">if set to <c>true</c> [ignore empty fields].</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">note request</exception>
        /// <exception cref="System.Exception">
        /// </exception>
        public PushResponse PushNote(PushNoteRequest request, bool ignoreEmptyFields = false)
        {
            try
            {
                #region pre-processing

                if (request == null)
                {
                    throw new ArgumentNullException("note request");
                }

                if (string.IsNullOrWhiteSpace(request.DeviceIden) && string.IsNullOrWhiteSpace(request.Email))
                {
                    throw new Exception(PushbulletConstants.PushRequestErrorMessages.EmptyEmailProperty);
                }

                if (string.IsNullOrWhiteSpace(request.Type))
                {
                    throw new Exception(PushbulletConstants.PushRequestErrorMessages.EmptyTypeProperty);
                }

                if (!ignoreEmptyFields)
                {
                    if (string.IsNullOrWhiteSpace(request.Title))
                    {
                        throw new Exception(PushbulletConstants.PushNoteRequestErrorMessages.EmptyTitleProperty);
                    }

                    if (string.IsNullOrWhiteSpace(request.Body))
                    {
                        throw new Exception(PushbulletConstants.PushNoteRequestErrorMessages.EmptyBodyProperty);
                    }
                }

                #endregion pre-processing


                #region processing

                return(PostPushRequest <PushNoteRequest>(request));

                #endregion processing
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #12
0
        public void Push(string title, string message)
        {
            var device = GetDevice();

            if (device != null)
            {
                var request = new PushNoteRequest
                {
                    DeviceIden = device.Iden,
                    Title      = title,
                    Body       = message
                };

                var response = _client.PushNote(request);
            }
        }
        public async void GetPushesSinceLastPush()
        {
            try
            {
                // Push a first note
                PushNoteRequest request = new PushNoteRequest()
                {
                    Title = "Push one",
                    Body  = "This is the first message."
                };
                var response = await Client.PushNote(request);

                // Get modified date of last push
                var results = await Client.GetPushes(new PushResponseFilter()
                {
                    Limit = 1
                });

                var lastModified = results.Pushes[0].Modified;

                Thread.Sleep(1000);

                // Push a second note
                var secondBody = "This is the second message.";
                request = new PushNoteRequest()
                {
                    Title = "Push two",
                    Body  = secondBody
                };
                response = await Client.PushNote(request);

                // Get pushes since first one, + one millisecond because otherwise we can get back our previous received push...
                results = await Client.GetPushes(new PushResponseFilter()
                {
                    ModifiedDate = lastModified.AddMilliseconds(1)
                });

                //should have only the second push
                Assert.AreEqual(1, results.Pushes.Count);
                Assert.AreEqual(secondBody, results.Pushes[0].Body);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #14
0
        public void pushNotification(string message, string pbKey)
        {
            if (pbClient == null)
            {
                pbClient = new PushbulletClient(pbKey);
            }
            if (pbClient.CurrentUsersInformation() == null)
            {
                showBalloon("Your Pushbullet key is invalid", SystemIcons.Error);
                return;
            }
            PushNoteRequest note = new PushNoteRequest {
                Title = "ALC",
                Body  = message,
            };

            pbClient.PushNote(note);
        }
        public override bool OnExecution()
        {
            PushBulletConnectorNode pushBulletConnector = this.InParameters["pushBullet"].GetValue() as PushBulletConnectorNode;
            var title   = this.InParameters["title"].GetValue().ToString();
            var message = this.InParameters["message"].GetValue().ToString();
            var devices = pushBulletConnector.Client.CurrentUsersDevices();

            foreach (var device in devices.Devices)
            {
                var request = new PushNoteRequest
                {
                    DeviceIden = device.Iden,
                    Title      = title,
                    Body       = message
                };
                pushBulletConnector.Client.PushNote(request);
            }
            return(true);
        }
Exemple #16
0
        private void Envianotificação(string texto)
        {
            PushbulletClient client   = new PushbulletClient("o.ijhfmbKRI8JAAAjaorTvs3n1I1oHo4qH");
            PushNoteRequest  request1 = new PushNoteRequest
            {
                DeviceIden = "ujy7mvFtukmsjE5NB4jvkO",
                Title      = texto,
                Body       = texto
            };

            PushResponse    response1 = client.PushNote(request1);
            PushNoteRequest request2  = new PushNoteRequest
            {
                DeviceIden = "ujy7mvFtukmsjBmQj6ywIS",
                Title      = texto,
                Body       = texto
            };

            PushResponse response2 = client.PushNote(request2);
        }
Exemple #17
0
        public void PushbulletPushNoteByEmailTest()
        {
            try
            {
                var currentUserInformation = Client.CurrentUsersInformation();
                Assert.IsNotNull(currentUserInformation);

                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    Email = currentUserInformation.Email,
                    Title = "hello world via email",
                    Body  = "This is a test from my C# wrapper."
                };

                var response = Client.PushNote(reqeust);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #18
0
        private void sendAlert(String title, String text)
        {
            PushbulletClient client = new PushbulletClient(txt_APIKey.Text);

            var currentUserInformation = client.CurrentUsersInformation();

            if (currentUserInformation != null)
            {
                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    Email = currentUserInformation.Email,
                    Title = title,
                    Body  = text
                };

                txt_Log.AppendText(DateTime.Now.ToString("HH:mm:ss") + " - " + text + "\r\n");
                if (!DEBUG)
                {
                    PushResponse response = client.PushNote(reqeust);
                }
            }
        }
Exemple #19
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);
        }
Exemple #20
0
        private void SendPushBullet(string Message, string _Title, string API, int UserNotifyId)
        {
            ///TODO: Add Client API Keys in DB
            ///TODO: Retreive Client API Key

            // v1Tftuzx00PyhMzoOdJMMbvnrDwUCvz2ZQujvKinowKOW
            PushbulletClient client = new PushbulletClient(API);

            var currentUserInformation = client.CurrentUsersInformation();

            if (currentUserInformation != null)
            {
                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    Email = currentUserInformation.Email,
                    Title = _Title,
                    Body  = Message
                };

                PushResponse response = client.PushNote(reqeust);

                LogNotification(UserNotifyId, Message);
            }
        }
        public static NotifycationMessages Notify(string token)
        {
            PushbulletClient client = new PushbulletClient(token);
            var devices             = client.CurrentUsersDevices();
            var device = devices.Devices.Where(o => o.Active == true).FirstOrDefault();

            if (device != null)
            {
                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    DeviceIden = device.Iden,
                    Title      = "Auto Accepter for Dota 2",
                    Body       = "YOUR GAME IS READY!!!"
                };

                PushResponse response = client.PushNote(reqeust, false);

                return(NotifycationMessages.OK);
            }
            else
            {
                return(NotifycationMessages.Has_no_device);
            }
        }
        public static void SendNotification(String notification)
        {
            DrySafe.Logger.Info($"Send notification : {notification}");

            PushbulletClient client = new PushbulletClient(_apiKey);

            //If you don't know your device_iden, you can always query your devices
            var devices = client.CurrentUsersDevices();

            foreach (var device in devices.Devices.Where(d => d.Fingerprint != null))
            {
                if (device != null)
                {
                    PushNoteRequest request = new PushNoteRequest
                    {
                        DeviceIden = device.Iden,
                        Title      = "Alerte pluie",
                        Body       = notification
                    };

                    PushResponse response = client.PushNote(request);
                }
            }
        }
Exemple #23
0
        public void PushbulletPushNoteTest()
        {
            try
            {
                var devices = Client.CurrentUsersDevices();
                Assert.IsNotNull(devices);

                var device = devices.Devices.Where(o => o.manufacturer == "Apple").FirstOrDefault();
                Assert.IsNotNull(device, "Could not find the device specified.");

                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    device_iden = device.iden,
                    title       = "hello world",
                    body        = "This is a test from my C# wrapper."
                };

                var response = Client.PushNote(reqeust);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #24
0
        //static int reneScore = 0;

        static void Main(string[] args)
        {
            Console.Title = "Deathlist " + year;
            //dlInit();                               //Befüllen der Link-Liste

            //Befüllen der Deathlists
            emil   = new int[] { 0, 1, 2, 12, 13, 17, 19, 42, 55, 57, 60, 62, 78, 79, 91, 93, 96, 97, 103, 108, 111, 120, 125, 126, 127, 135, 136, 138, 139, 142 };
            fabian = new int[] { 0, 2, 3, 18, 25, 31, 35, 45, 46, 47, 60, 62, 69, 84, 90, 92, 96, 97, 103, 107, 116, 117, 120, 120, 124, 125, 126, 127, 138, 139 };
            jasi   = new int[] { 6, 8, 9, 13, 16, 26, 29, 30, 32, 34, 36, 38, 48, 52, 53, 80, 85, 86, 87, 88, 89, 94, 97, 98, 112, 120, 123, 136, 138, 146 };
            manu   = new int[] { 3, 7, 10, 26, 34, 36, 37, 38, 39, 48, 64, 67, 70, 71, 79, 85, 86, 89, 97, 98, 99, 100, 103, 115, 118, 121, 124, 129, 137, 143 };
            michi  = new int[] { 19, 21, 26, 28, 33, 34, 44, 48, 58, 64, 72, 73, 86, 88, 89, 95, 97, 102, 103, 104, 106, 118, 119, 122, 132, 136, 137, 138, 139, 145 };
            //rene        = new int[] { 4, 13, 21, 23, 28, 36, 44, 49, 52, 55, 57, 58, 59, 63, 65, 72, 78, 87, 87, 96, 103, 105, 109, 118, 119, 120, 121, 133, 139, 146 };
            valentin = new int[] { 6, 13, 14, 19, 24, 27, 29, 43, 50, 59, 66, 67, 77, 83, 85, 87, 88, 98, 101, 105, 38, 111, 112, 128, 131, 134, 141, 144, 147, 148 };
            miri     = new int[] { 11, 16, 22, 23, 26, 33, 36, 48, 49, 52, 54, 54, 56, 63, 67, 74, 76, 81, 82, 85, 89, 107, 109, 110, 112, 113, 123, 144, 146, 148 };
            volker   = new int[] { 4, 5, 13, 15, 20, 33, 35, 40, 41, 46, 51, 60, 61, 65, 68, 75, 88, 97, 103, 107, 114, 117, 126, 127, 130, 133, 136, 138, 140, 148 };


            for (int i = 0; i < d.Length; i++)                                                                          //Jeden Link im Array durchgehen
            {
                string urlAddress = d[i];                                                                               //und die jeweilige URL verwenden
                string data       = "-";

                HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(urlAddress);                               //HTTP Anfrage
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();                                      //HTTP Antwort

                if (response.StatusCode == HttpStatusCode.OK)                                                           //Wenn die Antwort ohne Fehler ankommt (Code: 200) dann weitermachen
                {
                    Stream       receiveStream = response.GetResponseStream();                                          //Stream um den Text der Webseite verwenden zu können
                    StreamReader readStream    = null;

                    if (response.CharacterSet == null)
                    {
                        readStream = new StreamReader(receiveStream);
                        Console.WriteLine("");
                    }
                    else
                    {
                        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
                        //Console.WriteLine("");
                    }

                    data = readStream.ReadToEnd();                                                                      //String data beinhaltet den Quellcode

                    if (data.Contains(year + " deaths"))                                                                //Abfrage ob "2021 deaths" in den Categories vorkommt (engl. Wiki)
                    {
                        dl.Add(i);                                                                                      //In die Todes-Liste hinzufügen
                        string s = d[i].Substring(30).Replace("_", " ");                                                //Vorbereitung für Console-Output
                        Console.WriteLine(i + " - " + s);                                                               //Console-Output
                    }
                    else if (data.Contains("Gestorben " + year))                                                        //Abfrage ob "Gestorben 2021" in den Categories vorkommt (deu. Wiki)
                    {
                        dl.Add(i);                                                                                      //Das gleiche in Deutsch
                        string s = d[i].Substring(30).Replace("_", " ");                                                //
                        Console.WriteLine(i + " - " + s);                                                               //
                    }                                                                                                   //

                    response.Close();                                                                                   //Die Streams müssen geschlossen werden.
                    readStream.Close();
                }
            }

            //Console.WriteLine(data);
            //Console.ReadKey();
            //System.Environment.Exit(0);
            Console.WriteLine();


            //Nachdem alle Einträge der Link-Liste durch sind wird die Liste der Verstorbenen mit den Deathlists der Teilnehmer verglichen.
            //Dazu dient ein Unterprogramm "fastSearch" selbstgeschrieben als Platzhalter. (unten weiter zu finden)
            emilScore   = fastSearch(dl, emil);
            fabianScore = fastSearch(dl, fabian);
            jasiScore   = fastSearch(dl, jasi);
            manuScore   = fastSearch(dl, manu);
            michiScore  = fastSearch(dl, michi);
            //reneScore = fastSearch(dl, rene);
            valentinScore = fastSearch(dl, valentin);
            miriScore     = fastSearch(dl, miri);
            volkerScore   = fastSearch(dl, volker);


            //Console-Output mit allen Teilnehmern und deren Punkten
            Console.WriteLine("Emil: " + emilScore);
            Console.WriteLine("Fabian: " + fabianScore);
            Console.WriteLine("Jasi: " + jasiScore);
            Console.WriteLine("Manu: " + manuScore);
            Console.WriteLine("Michi: " + michiScore);
            //Console.WriteLine("Rene: " + reneScore);
            Console.WriteLine("Valentin: " + valentinScore);
            Console.WriteLine("Miri: " + miriScore);
            Console.WriteLine("Volker: " + volkerScore);


            string[] pD = { };
            try {
                pD = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "pD.txt");                          //Einlesen des Text-Files mit den Verstorbenen, die bereits vor der Abfrage abgedankt haben
            }catch (FileNotFoundException e) {
                File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory + "pD.txt", pD);
            }
            string[] caster = new string[dl.Count];                                                                     //Umwandeln der ArrayList zu String Array
            for (int i = 0; i < dl.Count; i++)                                                                          //
            {
                caster[i] = (dl[i] + "");                                                                               //
                //Console.WriteLine(i+" "+dl[i]);                                                                       //
            }                                                                                                           //


            if (pD.SequenceEqual(caster))                                                                               //Besteht ein Unterschied zwischen der letzten Abfrage und der gerade abgefragten Liste?
            {
                Console.WriteLine("Meh");                                                                               //Nein: Kein weiterer ist verstorben
            }
            else
            {
                string oDiff = "";                                                                                      //Ja:
                foreach (string diff in caster)                                                                         //Wer mit welchem Index
                {
                    if (!pD.Contains(diff))                                                                             //
                    {
                        oDiff = diff;                                                                                   //
                    }                                                                                                   //
                }                                                                                                       //

                Console.WriteLine("Heureka");

                String whoPointed = "";                                                                                 //String wird der Nachricht für Pushbullet angefügt und zeigt, wer gepunktet hat

                whoPointed += pointSearch(Int32.Parse(oDiff), emil, "Emil ");                                           //Ist der Index des neuverstorbenen in der jeweiligen Liste?
                whoPointed += pointSearch(Int32.Parse(oDiff), fabian, "Fabian ");
                whoPointed += pointSearch(Int32.Parse(oDiff), jasi, "Jasi ");
                whoPointed += pointSearch(Int32.Parse(oDiff), manu, "Manu ");
                whoPointed += pointSearch(Int32.Parse(oDiff), michi, "Michi ");
                //whoPointed += pointSearch(Int32.Parse(oDiff), rene, "Rene ");
                whoPointed += pointSearch(Int32.Parse(oDiff), valentin, "Valentin ");
                whoPointed += pointSearch(Int32.Parse(oDiff), miri, "Miri ");
                whoPointed += pointSearch(Int32.Parse(oDiff), volker, "Volker ");


                //Client erstellen
                PushbulletClient client = new PushbulletClient("o.xbEidwElVYGVSDK5F1uX0r1ZyVe5ovSt");

                //Informationen über unseren Account abholen
                var currentUserInformation = client.CurrentUsersInformation();

                //Prüfen, ob Accountinfos geladen wurden
                if (currentUserInformation != null)
                {
                    //Anfrage erzeugen
                    PushNoteRequest request = new PushNoteRequest {
                        Email = currentUserInformation.Email,
                        Title = "Deathlist " + year,
                        Body  = "RIP " + d[Int32.Parse(oDiff)].Substring(30).Replace("_", " ") + "\n" + whoPointed
                    };

                    PushbulletSharp.Models.Responses.PushResponse response = client.PushNote(request);
                }

                Pushover pclient = new Pushover("asf1vbpvec3x6h288p46nu8xj2i6xb");
                PushoverClient.PushResponse responsePO = pclient.Push(
                    "Deathlist " + year,
                    "RIP " + d[Int32.Parse(oDiff)].Substring(30).Replace("_", " ") + "\n" + whoPointed,
                    "g3kf5dfnarwrkemmf35vimf2hxcyyz"
                    );
            }

            File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory + "pD.txt", caster);                               //Neue Liste in die Datei zurückschreiben
        }
Exemple #25
0
        private bool Respond(SteamID toID, SteamID userID, string message, bool room)
        {
            CheckIfDBExists(userID);
            Dictionary <ulong, DB> db = Options.NotificationOptions.DB;

            db[userID].userID = userID.ConvertToUInt64();
            db[userID].seen   = DateTime.Now;
            db[userID].name   = Bot.steamFriends.GetFriendPersonaName(userID);

            string[] query = StripCommand(message, Options.NotificationOptions.SeenCommand);
            if (query != null && query.Length == 1)
            {
                SendMessageAfterDelay(toID, "Usage: " + Options.NotificationOptions.SeenCommand + " <steamid64>", room);
                return(true);
            }
            if (query != null && query.Length == 2)
            {
                if (!db.ContainsKey(Convert.ToUInt64(query[1])) || db[Convert.ToUInt64(query[1])] == null)
                {
                    SendMessageAfterDelay(toID, "The user " + query[1] + " was not found.", room);
                    return(true);
                }
                else
                {
                    SendMessageAfterDelay(toID, string.Format("I last saw {0} on {1} at {2}", db[Convert.ToUInt64(query[1])].name, db[Convert.ToUInt64(query[1])].seen.ToShortDateString(), db[Convert.ToUInt64(query[1])].seen.ToShortTimeString()), room);
                    return(true);
                }
            }

            query = StripCommand(message, Options.NotificationOptions.APICommand);
            if (query != null && userID != toID)
            {
                SendMessageAfterDelay(toID, "This command will only work in private to protect privacy.", room);
                return(true);
            }
            else if (query != null && userID == toID && query.Length == 1)
            {
                SendMessageAfterDelay(toID, "Usage: " + Options.NotificationOptions.APICommand + " <apikey>", room);
                return(true);
            }
            else if (query != null && query.Length == 2 && userID == toID)
            {
                CheckIfDBExists(userID);
                string api = query[1];
                db[userID.ConvertToUInt64()].pb.apikey = api;
                PushbulletClient client = new PushbulletClient(api);
                PushNoteRequest  note   = new PushNoteRequest()
                {
                    Title = "Test note",
                    Body  = "This is a test. If you receive this then you have successfully registered an API key with the bot."
                };

                PushResponse response = client.PushNote(note);
                if (response == null)
                {
                    SendMessageAfterDelay(toID, "Your push failed. Most likely your API key is incorrect.", room);
                    return(true);
                }
                else
                {
                    SendMessageAfterDelay(toID, "Your push was a success.", room);
                    return(true);
                }
            }

            query = StripCommand(message, Options.NotificationOptions.FilterCommand);
            if (query != null && query.Length == 1)
            {
                SendMessageAfterDelay(toID, "Usage: " + Options.NotificationOptions.FilterCommand + "<subcommand> [query]\nAvailable sub commands: add, list, clear, delete", room);
                return(true);
            }
            else if (query != null && query.Length >= 2)
            {
                if (query[1] == "add" && query.Length >= 3)
                {
                    List <string> words = new List <string>();
                    words = db[userID].pb.filter;
                    // !filter add banshee test 1 2 3
                    for (int i = 2; i < query.Length; i++)
                    {
                        words.Add(query[i]);
                    }

                    db[userID].pb.filter = words;
                    SendMessageAfterDelay(toID, "Your filter has been successfully modified.", room);
                    return(true);
                }
                else if (query[1] == "list" && query.Length == 2)
                {
                    if (db[userID].pb.filter.Count > 0)
                    {
                        string words = string.Join(", ", db[userID].pb.filter);
                        SendMessageAfterDelay(userID, "Your filter: " + words, false);
                        return(true);
                    }
                    else
                    {
                        SendMessageAfterDelay(userID, "Your filter is empty. Use \"!filter add <words>\" to add to your filter", false);
                        return(true);
                    }
                }
                else if (query[1] == "clear" && query.Length == 2)
                {
                    db[userID].pb.filter.Clear();
                    SendMessageAfterDelay(toID, "Your filter has been cleared", room);
                    return(true);
                }
                else if (query[1] == "delete" && query.Length == 3)
                {
                    db[userID].pb.filter.Remove(query[2]);
                    SendMessageAfterDelay(toID, "The filter \"" + query[2] + "\" has been removed", room);
                    return(true);
                }
            }

            query = StripCommand(message, Options.NotificationOptions.ClearCommand);
            if (query != null)
            {
                db[userID] = null;
                SendMessageAfterDelay(toID, "Your database file has been cleared.", room);
                return(true);
            }


            foreach (DB d in db.Values)
            {
                if (d == null || d.pb == null || d.pb.filter == null || d.pb.filter.Count == 0)
                {
                    return(false);
                }
                foreach (string word in d.pb.filter)
                {
                    if (message.ToLower().Contains(word.ToLower()) && userID.ConvertToUInt64() != d.userID)
                    {
                        if (d.pb.apikey != null && d.pb.apikey != "")
                        {
                            PushbulletClient client = new PushbulletClient(d.pb.apikey);
                            PushNoteRequest  note   = new PushNoteRequest();
                            note.Title = string.Format("Steam message from {0}/{1} in {2}", db[userID.ConvertToUInt64()].name, userID.ConvertToUInt64(), toID.ConvertToUInt64());
                            note.Body  = message;
                            client.PushNote(note);
                            Log.Instance.Verbose("{0}/{1}: Sending pushbullet for {2}/{3}", Bot.username, Name, db[d.userID].name, db[d.userID].userID);
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
        public static void Notify(string messageFormat, params object[] args)
        {
            #if DEBUG
            return;
            #endif
            PushbulletClient client = new PushbulletClient(Settings.PushbulletApiKey);

            //If you don't know your device_iden, you can always query your devices
            var userDevices = client.CurrentUsersDevices();

            //search for specified device, otherwise send to all devices
            var recipientDevices = new List<PushbulletSharp.Models.Responses.Device>();

            bool isUserSpecifiedDeviceFound = false;
            if (!string.IsNullOrWhiteSpace(Settings.PushbulletDeviceName))
            {
                foreach (var device in userDevices.Devices)
                {
                    if (device.Nickname.ToLowerInvariant().Contains(Settings.PushbulletDeviceName.ToLower()))
                    {
                        recipientDevices.Add(device);
                        isUserSpecifiedDeviceFound = true;
                        break;
                    }
                }
            }

            if (!isUserSpecifiedDeviceFound)
            {
                recipientDevices.AddRange(userDevices.Devices);
            }

            foreach (var device in recipientDevices)
            {
                if (device != null)
                {
                    var request = new PushNoteRequest()
                    {
                        DeviceIden = device.Iden,
                        Title = "Notification from dlm",
                        Body = string.Format(messageFormat, args)
                    };
                    var response = client.PushNote(request);
                }
            }
        }
        private bool Respond(SteamID toID, SteamID userID, string message, bool room)
        {
            bool messageSent = false;
            CheckIfDBExists(userID);
            Dictionary<ulong, DB> db = Options.NotificationOptions.DB;

            db[userID].userID = userID.ConvertToUInt64();
            db[userID].seen = DateTime.Now;
            db[userID].name = Bot.steamFriends.GetFriendPersonaName(userID);

            string[] query = StripCommand(message, Options.NotificationOptions.SeenCommand);
            if (query != null && query.Length == 2)
            {
                if (!db.ContainsKey(Convert.ToUInt64(query[1])) || db[Convert.ToUInt64(query[1])] == null)
                {
                    SendMessageAfterDelay(toID, "The user " + query[1] + " was not found.", room);
                    messageSent = true;
                }
                else
                {
                    SendMessageAfterDelay(toID, string.Format("I last saw {0} on {1} at {2}", db[Convert.ToUInt64(query[1])].name, db[Convert.ToUInt64(query[1])].seen.ToShortDateString(), db[Convert.ToUInt64(query[1])].seen.ToShortTimeString()), room);
                    messageSent = true;
                }
            }

            query = StripCommand(message, Options.NotificationOptions.APICommand);
            if(query != null && userID != toID)
            {
                SendMessageAfterDelay(toID, "This command will only work in private to protect privacy.", room);
                messageSent = true;
            }
            else if(query != null && query.Length == 2 && userID == toID)
            {
                CheckIfDBExists(userID);
                string api = query[1];
                db[userID.ConvertToUInt64()].pb.apikey = api;
                PushbulletClient client = new PushbulletClient(api);
                PushNoteRequest note = new PushNoteRequest()
                {
                    Title = "Test note",
                    Body = "This is a test. If you receive this then you have successfully registered an API key with the bot."
                };

                PushResponse response = client.PushNote(note);
                if(response == null)
                {
                    SendMessageAfterDelay(toID, "Your push failed. Most likely your API key is incorrect.", room);
                    messageSent = true;
                }
                else
                {
                    SendMessageAfterDelay(toID, "Your push was a success.", room);
                    messageSent = true;
                }
            }

            query = StripCommand(message, Options.NotificationOptions.FilterCommand);
            if(query != null && query.Length == 1)
            {
                SendMessageAfterDelay(toID, "Available sub commands: add, list, clear, delete", room);
                messageSent = true;
            }
            else if(query != null && query.Length >= 2)
            {
                if(query[1] == "add" && query.Length >= 3)
                {

                    List<string> words = new List<string>();
                    words = db[userID].pb.filter;
                    // !filter add banshee test 1 2 3
                    for (int i = 2; i < query.Length; i++)
                    {
                        words.Add(query[i]);
                    }

                    db[userID].pb.filter = words;
                    SendMessageAfterDelay(toID, "Your filter has been successfully modified.", room);
                    messageSent = true;
                }
                else if(query[1] == "list" && query.Length == 2)
                {
                    if (db[userID].pb.filter.Count > 0)
                    {
                        string words = string.Join(", ", db[userID].pb.filter);
                        SendMessageAfterDelay(userID, "Your filter: " + words, false);
                        messageSent = true;
                    }
                    else
                    {
                        SendMessageAfterDelay(userID, "Your filter is empty. Use \"!filter add <words>\" to add to your filter", false);
                        messageSent = true;
                    }
                }
                else if(query[1] == "clear" && query.Length == 2)
                {
                    db[userID].pb.filter.Clear();
                    SendMessageAfterDelay(toID, "Your filter has been cleared", room);
                    messageSent = true;
                }
                else if(query[1] == "delete" && query.Length == 3)
                {
                    db[userID].pb.filter.Remove(query[2]);
                    SendMessageAfterDelay(toID, "The filter \"" + query[2] + "\" has been removed", room);
                    messageSent = true;
                }
            }

            query = StripCommand(message, Options.NotificationOptions.ClearCommand);
            if(query != null)
            {
                db[userID] = null;
                SendMessageAfterDelay(toID, "Your database file has been cleared.", room);
                messageSent = true;
            }

            foreach (DB d in db.Values)
            {
                if (d == null || d.pb == null || d.pb.filter == null || d.pb.filter.Count == 0)
                {
                    return false;
                }
                foreach (string word in d.pb.filter)
                {
                    if (message.ToLower().Contains(word.ToLower()) && userID.ConvertToUInt64() != d.userID)
                    {
                        if (d.pb.apikey != null && d.pb.apikey != "")
                        {
                            PushbulletClient client = new PushbulletClient(d.pb.apikey);
                            PushNoteRequest note = new PushNoteRequest();
                            note.Title = string.Format("Steam message from {0}/{1} in {2}", db[userID.ConvertToUInt64()].name, userID.ConvertToUInt64(), toID.ConvertToUInt64());
                            note.Body = message;
                            client.PushNote(note);
                            Log.Instance.Verbose("{0}/{1}: Sending pushbullet for {2}/{3}", Bot.username, Name, db[d.userID].name, db[d.userID].userID);
                            return true;
                        }
                    }
                }
            }

            return messageSent;
        }
        public async Task <bool> UpdateRound()
        {
            Form1 mainForm = (Form1)Application.OpenForms[0];


            //Run Updateround

            /*
             *
             *  1   Capture area that is located under the application
             *  2   Save Captured area as JPG to temporary location
             *  3   Run Tesseract OCR on the image
             *  4   Find relevant data
             *  -- Realm is Full <-- Can be used to find out if capture is from right location
             *  -- Position in queue: 12345 <-- Relevant data
             *  -- Estimated time: 123 min <-- Non relevant, inaccurate
             *  -- Change Realm <-- Can be used to find out if capture is from right location
             *  5   Send notification
             *
             ++ Watch for dangerous words
             ++  Disconnected
             ++  Error
             ++  WOW51900319
             ++  BLZ51901016
             ++
             ++ You have been disconnected from the server.
             ++
             */
            try
            {
                //0 Hide text elements from UI (while snipping
                mainForm.btn_autoRefresh.Visible = false;
                mainForm.txt_currPosi.Visible    = false;
                mainForm.txt_loglabel.Visible    = false;
                mainForm.label1.Visible          = false;
                mainForm.txt_speed.Visible       = false;
                mainForm.txt_etrlabel.Visible    = false;
                mainForm.Text = "";

                //1
                Point     bounds       = new Point(mainForm.Bounds.Top, mainForm.Bounds.Left);
                Rectangle canvasBounds = Screen.GetBounds(bounds);
                Graphics  graphics;


                using (Image image = new Bitmap(mainForm.Width, mainForm.Height))
                {
                    using (graphics = Graphics.FromImage(image))
                    {
                        graphics.CopyFromScreen(new Point
                                                    (mainForm.Bounds.Left, mainForm.Bounds.Top), Point.Empty, canvasBounds.Size);
                    }

                    //2
                    var bmresult = image;
                    //File.Delete(Application.StartupPath + "\\ocr.png"); --keep incase things break

                    bmresult.Save(Application.StartupPath + "\\ocr.png", System.Drawing.Imaging.ImageFormat.Png);
                    //bmresult.Dispose(); --keep incase things break
                    //graphics.Dispose(); --keep incase things break
                }


                //2 Manipulate image a bit with MagickImage

                // Read from file
                using (MagickImage image = new MagickImage(Application.StartupPath + "\\ocr.png"))
                {
                    Percentage percentage = new Percentage(ProgHelpers.threshold);

                    image.Threshold(percentage); // 50 is OK, range from 45-60 with various results. TODO: Finetuning.
                    image.Depth = 1;
                    image.Write(Application.StartupPath + "\\ocrMagick.png");
                }

                //3
                var ocrimage = new Bitmap(Application.StartupPath + "\\ocrMagick.png");
                var ocr      = new TesseractEngine(Application.StartupPath + "TessData", "eng");

                //4
                string stringresult = ocr.Process(ocrimage).GetText();



                string positiontxt = "";
                int    position    = 99999;


                ocrimage.Dispose();

                //Return hidden values
                mainForm.btn_autoRefresh.Visible = true;
                mainForm.txt_currPosi.Visible    = true;
                mainForm.txt_loglabel.Visible    = true;
                mainForm.label1.Visible          = true;
                mainForm.txt_speed.Visible       = true;
                mainForm.txt_etrlabel.Visible    = true;
                mainForm.Text = "K8 Gnomish Queuing Device";

                //4a - Assign relevant data


                //Find things that you expect to see to gauge whether data is reliable or not
                //Then check if it contains common "dangerous words
                if (stringresult.Contains("queue") | stringresult.Contains("Realm is Full") | stringresult.Contains("Position") | stringresult.Contains("Estimated"))
                {
                    //Expected input, find position of text, get next 5 letters (queue position)
                    ProgHelpers.pushtype = 1;

                    positiontxt = getBetween(stringresult, "queue:", "\n");

                    //Additional step, replace l and | as 1 (common OCR mistake)
                    //Add more obvious OCR common errors as we go
                    positiontxt = positiontxt.Replace("l", "1");
                    positiontxt = positiontxt.Replace("|", "1");
                    positiontxt = positiontxt.ToUpper().Replace("O", "0");

                    positiontxt = Regex.Replace(positiontxt, "[^0-9]", "");

                    if (Int32.TryParse(positiontxt, out position))
                    {
                        if (ProgHelpers.startingPosition == 99999)
                        {
                            ProgHelpers.startingPosition = position;
                            ProgHelpers.qpositions.Add(position);
                            ProgHelpers.qtimes.Add(DateTime.Now);
                        }

                        if (ProgHelpers.startingPosition < position)
                        {
                            //Handling for the event that the starting position has been assumed wrongly
                            //Replace Max position from the List, let the DateTime be (for now at least), it reduces accuracy a bit but it can't be helped
                            //NOTE: This skips adding to the qpositions list
                            int indexofStartingPosition = ProgHelpers.qpositions.IndexOf(ProgHelpers.startingPosition);
                            ProgHelpers.qpositions[indexofStartingPosition] = position;
                            ProgHelpers.startingPosition = position;
                        }
                        else
                        {
                            ProgHelpers.qpositions.Add(position);
                            ProgHelpers.qtimes.Add(DateTime.Now);
                        }


                        //get index of latest Datetime (we might do some scrutiny later on)
                        int indexOflatest = ProgHelpers.qtimes.IndexOf(ProgHelpers.qtimes.Max());

                        /*
                         * UNDER CONSTRUCTION ZONE: ETA CALCULATOR PART
                         */
                        //Progress
                        if (ProgHelpers.qpositions.Count > 3)
                        {
                            decimal progressed = Convert.ToDecimal(ProgHelpers.startingPosition) - Convert.ToDecimal(ProgHelpers.qpositions[indexOflatest]);
                            decimal progStatus = progressed / Convert.ToDecimal(ProgHelpers.startingPosition);

                            float etaUp = (float)progStatus;

                            //Add to ETACalc
                            ProgHelpers.etaCalc.Update(etaUp);
                            //Update ETA if possible
                            bool etaAvail = ProgHelpers.etaCalc.ETAIsAvailable;
                            if (etaAvail == true)
                            {
                                //ETA Available, get time Remaining and time of arrival

                                TimeSpan etaSpan = ProgHelpers.etaCalc.ETR;
                                ProgHelpers.etaString      = "Estimated time remaining: " + etaSpan.Hours + " Hours, " + etaSpan.Minutes + " Minutes.";
                                mainForm.txt_etrlabel.Text = ProgHelpers.etaString;
                            }
                        }

                        /*
                         * UNDER CONSTRUCTION ZONE ENDS
                         */

                        //Update label
                        DateTime nowtime = DateTime.Now;
                        TimeSpan span    = nowtime.Subtract(ProgHelpers.startingTime);

                        mainForm.txt_currPosi.Text = ProgHelpers.qpositions[indexOflatest].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " / " + span.Hours + " H " + span.Minutes + " M " + span.Seconds + " S";

                        //Update speed to form
                        var    hoursform  = (DateTime.Now - ProgHelpers.startingTime).TotalHours;
                        double passedform = Convert.ToDouble(ProgHelpers.startingPosition) - Convert.ToDouble(ProgHelpers.qpositions[indexOflatest]);
                        double speedform  = passedform / hoursform;
                        mainForm.txt_speed.Text = "Speed: " + (int)speedform + " / Hour";
                        LogWriter.LogWrite(mainForm.txt_etrlabel.Text + " | " + mainForm.txt_currPosi.Text + " | " + mainForm.txt_speed.Text + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes.");
                    }
                }
                else if (stringresult.Contains("Error") | stringresult.Contains("Disconnected") | stringresult.Contains("WOW51900319") | stringresult.Contains("BLZ51901016") | stringresult.Contains("disconnected") | stringresult.Contains("You have been disconnected from the server.") | stringresult.Contains("Account Name"))
                {
                    //Expected error input, no need to parse though
                    ProgHelpers.pushtype = 2;
                }
                else
                {
                    //Unexpected input, dont parse.
                    ProgHelpers.pushtype = 3;
                }

                //5

                //
                if (ProgHelpers.pushMode == 1 | ProgHelpers.pushMode == 0)
                {
                    //Using Pushbullet, Default
                    PushbulletClient client    = new PushbulletClient(ProgHelpers.pushApi);
                    var currentUserInformation = client.CurrentUsersInformation();

                    //If error, send immediately (check warning count towards)
                    if (ProgHelpers.pushtype == 2 | ProgHelpers.pushtype == 3)
                    {
                        string bodymsg = "WARNING! Unexpected error occured! No queue status available!";

                        if (ProgHelpers.pushtype == 2)
                        {
                            bodymsg = "WARNING! You have been disconnected from the queue!!!";
                        }
                        else
                        {
                            bodymsg = "WARNING! Unexpected error occured! No queue status available!";
                        }

                        if (ProgHelpers.errorCount >= ProgHelpers.concurErrors)
                        {
                            //More than threshhold -> Run

                            if (ProgHelpers.sentErrors < ProgHelpers.maxErrors)
                            {
                                //Send only a limited amount of errors
                                if (currentUserInformation != null)
                                {
                                    PushNoteRequest request = new PushNoteRequest
                                    {
                                        Email = currentUserInformation.Email,
                                        Title = "WARN! Gnomish Queuing Device",
                                        Body  = bodymsg
                                    };

                                    PushbulletSharp.Models.Responses.PushResponse response = client.PushNote(request);
                                    ProgHelpers.sentErrors++;
                                    mainForm.txt_loglabel.Text = (DateTime.Now.ToLongTimeString() + " Error message sent.");

                                    return(false);
                                }
                            }
                        }
                        else
                        {
                            //Add errorcount
                            ProgHelpers.errorCount++;
                        }
                    }
                    else
                    {
                        //Normal message

                        if (ProgHelpers.qpositions.Count > 0)
                        {
                            if (ProgHelpers.startingMsgsent == false)
                            {
                                string bodymsg = "Queue Watcher started, no position information yet.";

                                if (currentUserInformation != null)
                                {
                                    PushNoteRequest request = new PushNoteRequest
                                    {
                                        Email = currentUserInformation.Email,
                                        Title = "Gnomish Queuing Device",
                                        Body  = bodymsg
                                    };

                                    PushbulletSharp.Models.Responses.PushResponse response = client.PushNote(request);
                                }

                                //Starting message done
                                ProgHelpers.startingMsgsent = true;
                                LogWriter.LogWrite("Push message sent.");
                            }
                            else
                            {
                                //Elapsed time
                                DateTime nowtime = DateTime.Now;
                                TimeSpan span    = nowtime.Subtract(ProgHelpers.startingTime);

                                //Sent recently? Send every 3 minutes when under 1000 in queue
                                TimeSpan sincelastsend = nowtime.Subtract(ProgHelpers.pushTime);

                                int indexOflatest = ProgHelpers.qtimes.IndexOf(ProgHelpers.qtimes.Max());

                                if (ProgHelpers.qpositions[indexOflatest] < 1000)
                                {
                                    if (sincelastsend.TotalMinutes > ProgHelpers.sendIntervalSoon)
                                    {
                                        var    hours  = (DateTime.Now - ProgHelpers.startingTime).TotalHours;
                                        double passed = Convert.ToDouble(ProgHelpers.startingPosition) - Convert.ToDouble(ProgHelpers.qpositions[indexOflatest]);
                                        double speed  = passed / hours;

                                        string bodymsg = "";

                                        if (ProgHelpers.qpositions.Count < 5)
                                        {
                                            //Too little data to measure speed
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes.";
                                        }
                                        else
                                        {
                                            //Give speed info
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes. | Speed: " + (int)speed + " / Hour. | " + ProgHelpers.etaString;
                                        }


                                        if (currentUserInformation != null)
                                        {
                                            PushNoteRequest request = new PushNoteRequest
                                            {
                                                Email = currentUserInformation.Email,
                                                Title = "SOON! Gnomish Queuing Device",
                                                Body  = bodymsg
                                            };

                                            PushbulletSharp.Models.Responses.PushResponse response = client.PushNote(request);

                                            //Update Pushtime
                                            ProgHelpers.pushTime   = DateTime.Now;
                                            ProgHelpers.errorCount = 0; //Reset errors
                                            ProgHelpers.sentErrors = 0;

                                            LogWriter.LogWrite("Push message sent.");
                                        }
                                    }
                                }
                                else
                                {
                                    //Send status update every 15 mins
                                    if (sincelastsend.TotalMinutes > ProgHelpers.sendInterval)
                                    {
                                        var    hours  = (DateTime.Now - ProgHelpers.startingTime).TotalHours;
                                        double passed = Convert.ToDouble(ProgHelpers.startingPosition) - Convert.ToDouble(ProgHelpers.qpositions[indexOflatest]);
                                        double speed  = passed / hours;

                                        string bodymsg = "";

                                        if (ProgHelpers.qpositions.Count < 5)
                                        {
                                            //Too little data to measure speed
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes.";
                                        }
                                        else
                                        {
                                            //Give speed info
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes. | Speed: " + (int)speed + " / Hour. | " + ProgHelpers.etaString;
                                        }

                                        if (currentUserInformation != null)
                                        {
                                            PushNoteRequest request = new PushNoteRequest
                                            {
                                                Email = currentUserInformation.Email,
                                                Title = "Gnomish Queuing Device",
                                                Body  = bodymsg
                                            };

                                            PushbulletSharp.Models.Responses.PushResponse response = client.PushNote(request);

                                            //Update Pushtime
                                            ProgHelpers.pushTime   = DateTime.Now;
                                            ProgHelpers.errorCount = 0; //Reset errors
                                            ProgHelpers.sentErrors = 0;

                                            LogWriter.LogWrite("Push message sent.");
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (ProgHelpers.startingMsgsent == false)
                            {
                                string bodymsg = "Queue Watcher started, no position information yet.";

                                if (currentUserInformation != null)
                                {
                                    PushNoteRequest request = new PushNoteRequest
                                    {
                                        Email = currentUserInformation.Email,
                                        Title = "Gnomish Queuing Device",
                                        Body  = bodymsg
                                    };

                                    PushbulletSharp.Models.Responses.PushResponse response = client.PushNote(request);
                                }

                                //Starting message done
                                ProgHelpers.startingMsgsent = true;
                                LogWriter.LogWrite("Push message sent.");
                            }
                        }

                        mainForm.txt_loglabel.Text = (DateTime.Now.ToLongTimeString() + " Refresh complete.");
                        return(true);
                    }
                }
                if (ProgHelpers.pushMode == 2)
                {
                    //Using Pushover
                    Pushover pclient = new Pushover(ProgHelpers.pushApi);

                    //If error, send immediately (check warning count towards)
                    if (ProgHelpers.pushtype == 2 | ProgHelpers.pushtype == 3)
                    {
                        string bodymsg = "WARNING! Unexpected error occured! No queue status available!";

                        if (ProgHelpers.pushtype == 2)
                        {
                            bodymsg = "WARNING! You have been disconnected from the queue!!!";
                        }
                        else
                        {
                            bodymsg = "WARNING! Unexpected error occured! No queue status available!";
                        }

                        if (ProgHelpers.errorCount >= ProgHelpers.concurErrors)
                        {
                            if (ProgHelpers.sentErrors < ProgHelpers.maxErrors)
                            {
                                PushoverClient.PushResponse response = pclient.Push(
                                    "WARN! Gnomish Queuing Device",
                                    bodymsg,
                                    ProgHelpers.pushoverTargetkey,
                                    priority: Priority.Emergency,
                                    notificationSound: NotificationSound.Alien
                                    );

                                ProgHelpers.sentErrors++;
                                mainForm.txt_loglabel.Text = (DateTime.Now.ToLongTimeString() + " Error message sent.");
                                //Send only a limited amount of errors
                                LogWriter.LogWrite("Push message sent.");
                            }
                            return(false);
                        }
                        else
                        {
                            //Add errorcount
                            ProgHelpers.errorCount++;
                        }
                    }
                    else
                    {
                        //Normal message

                        if (ProgHelpers.qpositions.Count > 0)
                        {
                            if (ProgHelpers.startingMsgsent == false)
                            {
                                string bodymsg = "Queue Watcher started, no position information yet.";

                                PushoverClient.PushResponse response = pclient.Push(
                                    "Gnomish Queuing Device",
                                    bodymsg,
                                    ProgHelpers.pushoverTargetkey
                                    );

                                //Starting message done
                                ProgHelpers.startingMsgsent = true;
                                mainForm.txt_loglabel.Text  = (DateTime.Now.ToLongTimeString() + " Starting message sent.");
                                LogWriter.LogWrite("Push message sent.");
                                return(true);
                            }
                            else
                            {
                                //Elapsed time
                                DateTime nowtime = DateTime.Now;
                                TimeSpan span    = nowtime.Subtract(ProgHelpers.startingTime);

                                //Sent recently? Send every 3 minutes when under 1000 in queue
                                TimeSpan sincelastsend = nowtime.Subtract(ProgHelpers.pushTime);

                                int indexOflatest2 = ProgHelpers.qtimes.IndexOf(ProgHelpers.qtimes.Max());

                                if (ProgHelpers.qpositions[indexOflatest2] < ProgHelpers.whenPriorityMsg)
                                {
                                    if (sincelastsend.TotalMinutes > ProgHelpers.sendIntervalSoon)
                                    {
                                        var    hours  = (DateTime.Now - ProgHelpers.startingTime).TotalHours;
                                        double passed = Convert.ToDouble(ProgHelpers.startingPosition) - Convert.ToDouble(ProgHelpers.qpositions[indexOflatest2]);
                                        double speed  = passed / hours;

                                        string bodymsg = "";

                                        if (ProgHelpers.qpositions.Count < 5)
                                        {
                                            //Too little data to measure speed
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest2].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes.";
                                        }
                                        else
                                        {
                                            //Give speed info
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest2].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes. | Speed: " + (int)speed + " / Hour. | " + ProgHelpers.etaString;
                                        }


                                        PushoverClient.PushResponse response = pclient.Push(
                                            "SOON! Gnomish Queuing Device",
                                            bodymsg,
                                            ProgHelpers.pushoverTargetkey,
                                            priority: Priority.High,
                                            notificationSound: NotificationSound.Tugboat
                                            );

                                        //Update Pushtime
                                        ProgHelpers.pushTime = DateTime.Now;
                                        //Reset errors
                                        ProgHelpers.errorCount = 0;
                                        ProgHelpers.sentErrors = 0;

                                        mainForm.txt_loglabel.Text = (DateTime.Now.ToLongTimeString() + " Position updated");
                                        LogWriter.LogWrite("Push message sent.");
                                        return(true);
                                    }
                                    return(true);
                                }
                                else
                                {
                                    //Send status update every 15 mins
                                    if (sincelastsend.TotalMinutes > ProgHelpers.sendInterval)
                                    {
                                        var    hours  = (DateTime.Now - ProgHelpers.startingTime).TotalHours;
                                        double passed = Convert.ToDouble(ProgHelpers.startingPosition) - Convert.ToDouble(ProgHelpers.qpositions[indexOflatest2]);
                                        double speed  = passed / hours;

                                        string bodymsg = "";

                                        if (ProgHelpers.qpositions.Count < 5)
                                        {
                                            //Too little data to measure speed
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest2].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes.";
                                        }
                                        else
                                        {
                                            //Give speed info
                                            bodymsg = "Current position: " + ProgHelpers.qpositions[indexOflatest2].ToString() + " / " + ProgHelpers.startingPosition.ToString() + " | Time elapsed: " + span.Hours + " Hours " + span.Minutes + " Minutes. | Speed: " + (int)speed + " / Hour. | " + ProgHelpers.etaString;
                                        }



                                        PushoverClient.PushResponse response = pclient.Push(
                                            "Gnomish Queuing Device",
                                            bodymsg,
                                            ProgHelpers.pushoverTargetkey
                                            );

                                        //Update Pushtime
                                        ProgHelpers.pushTime = DateTime.Now;
                                        //Reset errors
                                        ProgHelpers.errorCount = 0;
                                        ProgHelpers.sentErrors = 0;

                                        mainForm.txt_loglabel.Text = (DateTime.Now.ToLongTimeString() + " Position updated");
                                        LogWriter.LogWrite("Push message sent.");
                                        return(true);
                                    }
                                    return(true);
                                }
                            }
                        }
                        else
                        {
                            if (ProgHelpers.startingMsgsent == false)
                            {
                                string bodymsg = "Queue Watcher started, no position information yet.";

                                PushoverClient.PushResponse response = pclient.Push(
                                    "Gnomish Queuing Device",
                                    bodymsg,
                                    ProgHelpers.pushoverTargetkey
                                    );

                                //Starting message done
                                ProgHelpers.startingMsgsent = true;
                                LogWriter.LogWrite("Push message sent.");
                            }
                        }

                        //Update speed to form
                        int    indexOflatest = ProgHelpers.qtimes.IndexOf(ProgHelpers.qtimes.Max());
                        var    hoursform     = (DateTime.Now - ProgHelpers.startingTime).TotalHours;
                        double passedform    = Convert.ToDouble(ProgHelpers.startingPosition) - Convert.ToDouble(ProgHelpers.qpositions[indexOflatest]);
                        double speedform     = passedform / hoursform;
                        mainForm.txt_speed.Text = "Speed: " + (int)speedform + " / Hour";

                        mainForm.txt_loglabel.Text = (DateTime.Now.ToLongTimeString() + " Refresh complete.");
                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
                //Disable autorefresh while updating API

                mainForm.txt_loglabel.Text = (DateTime.Now.ToLongTimeString() + " Something went wrong...");
                LogWriter.LogWrite("Something went wrong...");

                //ConsoleLog.AppendText(DateTime.Now.ToLongTimeString() + " Something went wrong...");
                //logform.ConsoleLog.AppendText(Environment.NewLine);

                return(false);
            }
            return(true);
        }
Exemple #29
0
        private void SendPushBullet(string Message, string _Title, string API, int UserNotifyId)
        {
            ///TODO: Add Client API Keys in DB
            ///TODO: Retreive Client API Key

            // v1Tftuzx00PyhMzoOdJMMbvnrDwUCvz2ZQujvKinowKOW
            PushbulletClient client = new PushbulletClient(API);

            var currentUserInformation = client.CurrentUsersInformation();

            if (currentUserInformation != null)
            {
                PushNoteRequest reqeust = new PushNoteRequest()
                {
                    Email = currentUserInformation.Email,
                    Title = _Title,
                    Body = Message
                };

                PushResponse response = client.PushNote(reqeust);

                LogNotification(UserNotifyId, Message);
            }
        }