Ejemplo n.º 1
0
        protected override void OnResume()
        {
            base.OnResume();

            nomusuario.Click += delegate
            {
                StopItems();
            };

            tipo.Click += delegate
            {
                StopItems();
            };

            velocidad.Click += delegate
            {
                StopItems();
            };

            activacion.Click += delegate
            {
                StopItems();
            };

            loginService = new LoginService();
            userService  = new UserService();

            try
            {
                client = loginService.Connect();

                if (client.IsUserAuthorized())
                {
                    usuario = client.Session.TLUser;
                }
            }
            catch (Exception ex)
            {
                this.FinishAffinity();
            }

            database         = new SQLiteRepository();
            userRepository   = new UserRepository(database);
            configRepository = new ConfigRepository(database);
            errorText        = new ErrorText();

            configuracion = configRepository.GetConfig();

            speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext);
            speechReco.SetRecognitionListener(this);
            intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es");
            intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch);
            intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1);

            toSpeech        = new TextToSpeech(this, this);
            gestureDetector = new GestureDetector(this);
        }
Ejemplo n.º 2
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);
            this.Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);

            database          = new SQLiteRepository();
            configRepo        = new ConfigRepository(database);
            loginService      = new LoginService();
            errorText         = new ErrorText();
            FakeSessionDelete = new FakeSessionDelete();
            configuracion     = configRepo.GetConfig();

            b      = FindViewById <ImageButton>(Resource.Id.Enviar);
            b2     = FindViewById <ImageButton>(Resource.Id.Leer);
            b3     = FindViewById <ImageButton>(Resource.Id.Contactos);
            b4     = FindViewById <ImageButton>(Resource.Id.Configuracion);
            logout = FindViewById <Button>(Resource.Id.logout);

            try
            {
                client = loginService.Connect();
            }
            catch (Exception ex)
            {
                this.FinishAffinity();
            }

            if (client.IsUserAuthorized())
            {
                usuario = client.Session.TLUser;
            }

            service = new Intent(this, typeof(ReceiveService));
            if (!IsMyServiceRunning(service))
            {
                StartService(service);
            }

            SetVisible(true);
        }
Ejemplo n.º 3
0
        protected override void OnResume()
        {
            base.OnResume();

            database          = new SQLiteRepository();
            contactRepository = new ContactRepository(database);
            configRepository  = new ConfigRepository(database);
            configuracion     = configRepository.GetConfig();
            errorText         = new ErrorText();

            speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext);
            speechReco.SetRecognitionListener(this);
            intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es");
            intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch);
            intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1);

            gestureDetector = new GestureDetector(this);
            toSpeech        = new TextToSpeech(this, this);
        }
Ejemplo n.º 4
0
        protected override void OnResume()
        {
            base.OnResume();

            configRepo    = new ConfigRepository(database);
            configuracion = configRepo.GetConfig();

            service = new Intent(this, typeof(ReceiveService));
            if (!IsMyServiceRunning(service))
            {
                StartService(service);
            }

            speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext);
            speechReco.SetRecognitionListener(this);
            intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es");
            intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch);
            intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1);

            gestureDetector = new GestureDetector(this);
            toSpeech        = new TextToSpeech(this, this);
        }
Ejemplo n.º 5
0
        protected override void OnResume()
        {
            base.OnResume();

            configuracion = configRepository.GetConfig();

            loginService   = new LoginService();
            messageService = new MessageService();
            errorText      = new ErrorText();

            try
            {
                client = loginService.Connect();

                if (client.IsUserAuthorized())
                {
                    usuario = client.Session.TLUser;
                }
            }
            catch (Exception ex)
            {
                this.FinishAffinity();
            }

            try
            {
                var ch = messageRepository.GetMessages();

                if (ch.Count > 0)
                {
                    _chatsNotReaded = messageRepository.CountMessagesNotReaded();
                    var total = _chatsNotReaded.Sum(x => x.Counter);

                    if (_chatsNotReaded.Count > 0 && _chatsNotReaded.Count <= 5)
                    {
                        if (total != 1)
                        {
                            textToSpeak = $"Tiene {total} mensajes nuevos de ";
                        }
                        else
                        {
                            textToSpeak = $"Tiene ún mensaje nuevo de ";
                        }

                        for (var i = 0; i < _chatsNotReaded.Count; i++)
                        {
                            var contact = contactRepository.GetContactByPhone(_chatsNotReaded[i].FromTo);
                            if (_chatsNotReaded.Count > 1 && i == _chatsNotReaded.Count - 1)
                            {
                                if (contact != null)
                                {
                                    textToSpeak += $"y {contact.FirstName} {contact.LastName}. ";
                                }
                                else
                                {
                                    textToSpeak += $"y {_chatsNotReaded[i].FromTo}. ";
                                }
                            }
                            else
                            {
                                if (contact != null)
                                {
                                    textToSpeak += $"{contact.FirstName} {contact.LastName}, ";
                                }
                                else
                                {
                                    textToSpeak += $"{_chatsNotReaded[i].FromTo}, ";
                                }
                            }
                        }
                        if (_chatsNotReaded.Count != 1)
                        {
                            textToSpeak += "¿Quiere leerlos, entrar a una conversación, borrarla, no hacer nada o volver atrás?";
                        }
                        else
                        {
                            textToSpeak += "¿Quiere leerlo, entrar a una conversación, borrarla, no hacer nada o volver atrás?";
                        }
                    }
                    else if (_chatsNotReaded.Count > 5)
                    {
                        textToSpeak = $"Tiene {total} mensajes nuevos de más de 5 contactos. ¿Quiere leerlos, entrar a una conversación, borrarla, no hacer nada o volver atrás?";
                    }
                    else if (_chatsNotReaded.Count == 0)
                    {
                        textToSpeak = $"No tiene mensajes nuevos. ¿Quiere entrar a una conversación, borrarla, no hacer nada o volver atrás?";
                    }
                }
                else
                {
                    record      = false;
                    textToSpeak = "No tiene ninguna conversación.";
                }
            }
            catch (Exception ex)
            {
                textToSpeak = $"Ha ocurrido un error al obtener sus mensajes nuevos. ¿Quiere entrar a una conversación, borrarla, no hacer nada o volver atrás?";
            }

            speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext);
            speechReco.SetRecognitionListener(this);
            intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es");
            intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch);
            intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1);

            gestureDetector = new GestureDetector(this);
            toSpeech        = new TextToSpeech(this, this);
        }
Ejemplo n.º 6
0
        protected override void OnResume()
        {
            base.OnResume();

            configRepository = new ConfigRepository(database);
            configuracion    = configRepository.GetConfig();

            loginService   = new LoginService();
            messageService = new MessageService();
            errorText      = new ErrorText();

            try
            {
                client = loginService.Connect();

                if (client.IsUserAuthorized())
                {
                    usuario = client.Session.TLUser;
                }
            }
            catch (Exception ex)
            {
                this.FinishAffinity();
            }

            try
            {
                _chats  = messageRepository.GetMessagesByPhoneWithoutSeen(extra);
                contact = contactRepository.GetContactByPhone(extra);
                messageRepository.MarkMessagesAsRead(extra);
                var total = _chats.Sum(x => x.Mensaje.Length);
                if (_chats.Count > 0)
                {
                    textToSpeak = $"Los mensajes nuevos de {contact.FirstName} {contact.LastName} son: ";
                    if (total < 3900)
                    {
                        for (int i = 0; i < _chats.Count; i++)
                        {
                            int j = i + 1;
                            if (i == _chats.Count - 1)
                            {
                                textToSpeak += $" y {j.ToString()} {_chats[i].Mensaje}";
                            }
                            else
                            {
                                textToSpeak += $"{j.ToString()} {_chats[i].Mensaje}, ";
                            }
                        }
                        textToSpeak += ". ¿Quiere responder?";
                        accion       = "responder";
                    }
                    else
                    {
                        LeerMensajesSinLeer();
                    }
                }
                else
                {
                    textToSpeak = "¿Quiere leer desde una fecha, buscar por un mensaje, no hacer nada o volver atrás?";
                    accion      = "leer";
                }
            }
            catch (Exception ex)
            {
                textToSpeak = "Ha ocurrido un error al acceder a la base de datos. ¿Quiere leer desde una fecha, buscar por un mensaje, no hacer nada o volver atrás?";
                accion      = "leer";
            }

            speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext);
            speechReco.SetRecognitionListener(this);
            intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es");
            intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch);
            intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1);

            gestureDetector = new GestureDetector(this);
            toSpeech        = new TextToSpeech(this, this);
        }
Ejemplo n.º 7
0
        public void OnResults(Bundle results)
        {
            Log.Info(LOG_TAG, "onResults");
            IEnumerable <string> matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
            int count = 0;

            countSpeech++;
            configuracion = configRepository.GetConfig();

            foreach (string result in matches)
            {
                count++;
                try
                {
                    if (count == 1)
                    {
                        if (countSpeech == 1)
                        {
                            if (result.ToLower().Contains("usuario"))
                            {
                                accion = "usuario";
                                try
                                {
                                    user         = userRepository.GetUser();
                                    textToSpeak  = user.Username != null ? $"Su nombre de usuario es {user.Username}" : "No tiene nombre de usuario";
                                    textToSpeak += ". ¿Quiere modificarlo?";
                                }
                                catch (Exception ex)
                                {
                                    countSpeech = 0;
                                    textToSpeak = "Ha ocurrido un error al acceder a la base de datos. Por favor, inténtelo más tarde. " +
                                                  "¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura o " +
                                                  "la activación de la voz, no hacer nada o volver atrás?";
                                }
                                toSpeech = new TextToSpeech(this, this);
                            }
                            else if (result.ToLower().Contains("tipo"))
                            {
                                accion = "tipo";
                                string voz = toSpeech.Voice != null ? toSpeech.Voice.Name : "la voz por defecto";
                                textToSpeak = $"La voz actual es: {voz}. ";
                                listVoice   = toSpeech.Voices;
                                if (listVoice != null && listVoice.Count > 1)
                                {
                                    textToSpeak += "Las voces actualmente instaladas son: ";
                                    int contador = 0;
                                    foreach (var item in listVoice)
                                    {
                                        contador++;
                                        if (contador == listVoice.Count)
                                        {
                                            textToSpeak += $"y {item.Name}. ";
                                        }
                                        else
                                        {
                                            textToSpeak += $"{item.Name}, ";
                                        }
                                    }
                                    textToSpeak += "Diga el nombre de la voz a cambiar o diga cancelar";
                                }
                                else
                                {
                                    countSpeech  = 0;
                                    textToSpeak += "No tiene más voces instaladas. ¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura o " +
                                                   "la activación de la voz, no hacer nada o volver atrás?";
                                }
                                toSpeech = new TextToSpeech(this, this);
                            }
                            else if (result.ToLower().Contains("velocidad"))
                            {
                                accion = "velocidad";
                                string velocidad = configuracion.Velocidad == 1.0 ? "normal" : configuracion.Velocidad == 0.5 ? "lenta" :
                                                   configuracion.Velocidad == 0.0 ? "muy lenta" : configuracion.Velocidad == 1.5 ? "rápida" : configuracion.Velocidad == 2 ?
                                                   "muy rápida" : "super rápida";
                                textToSpeak = $"La velocidad de lectura es {velocidad}. ¿Quiere aumentar la velocidad de lectura, reducirla o cancelar?";
                                toSpeech    = new TextToSpeech(this, this);
                            }
                            else if (result.ToLower().Contains("activación") || result.ToLower().Contains("activacion"))
                            {
                                accion = "activar";
                                string voz = configuracion.Voz ? "activada" : "desactivada";
                                string act = configuracion.Voz ? "desactivarla" : "activarla";
                                textToSpeak = $"La voz está {voz} .¿Quiere {act}?";
                                toSpeech    = new TextToSpeech(this, this);
                            }
                            else if (result.ToLower().Contains("atras") || result.ToLower().Contains("atrás") || result.ToLower().Contains("volver"))
                            {
                                StopItems();
                                StartActivity(typeof(MainActivity));
                            }
                            else if (result.ToLower().Contains("nada"))
                            {
                            }
                            else
                            {
                                countSpeech = 0;
                                textToSpeak = "Lo siento, no ha dicho una opción válida. ¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                              "o la activación de la voz, no hacer nada o volver atrás?";
                                toSpeech = new TextToSpeech(this, this);
                            }
                        }
                        else if (countSpeech == 2)
                        {
                            if (accion == "usuario" && (result.ToLower().Contains("si") || result.ToLower().Contains("sí")))
                            {
                                textToSpeak = "¿Qué nombre de usuario quiere?";
                                toSpeech    = new TextToSpeech(this, this);
                            }
                            else if ((accion == "usuario" || accion == "activar") && result.ToLower().Contains("no"))
                            {
                                countSpeech = 0;
                                textToSpeak = "¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura o " +
                                              "la activación de la voz, no hacer nada o volver atrás?";
                                toSpeech = new TextToSpeech(this, this);
                            }
                            else if (accion == "velocidad")
                            {
                                countSpeech = 0;
                                if (result.ToLower().Contains("cancelar"))
                                {
                                }
                                else if (result.ToLower().Contains("aumentar"))
                                {
                                    if (configuracion.Velocidad == 2.5)
                                    {
                                        textToSpeak = "No se puede aumentar más la velocidad de lectura.";
                                    }
                                    else
                                    {
                                        try
                                        {
                                            configuracion.Velocidad = configuracion.Velocidad + (float)0.5;
                                            configRepository.UpdateConfig(configuracion);
                                            textToSpeak = "Velocidad de lectura aumentada.";
                                        }
                                        catch (Exception ex)
                                        {
                                            countSpeech = 0;
                                            textToSpeak = "Ha ocurrido un error al acceder a la base de datos. Por favor, inténtelo más tarde.";
                                        }
                                    }
                                }
                                else if (result.ToLower().Contains("reducir"))
                                {
                                    if (configuracion.Velocidad == 0.0)
                                    {
                                        countSpeech = 0;
                                        textToSpeak = "No se puede reducir más la velocidad de lectura.";
                                    }
                                    else
                                    {
                                        try
                                        {
                                            configuracion.Velocidad = configuracion.Velocidad - (float)0.5;
                                            configRepository.UpdateConfig(configuracion);
                                            textToSpeak = "Velocidad de lectura reducida.";
                                        }
                                        catch (Exception ex)
                                        {
                                            countSpeech = 0;
                                            textToSpeak = "Ha ocurrido un error al acceder a la base de datos. Por favor, inténtelo más tarde.";
                                        }
                                    }
                                }
                                configuracion = configRepository.GetConfig();
                                textToSpeak  += " ¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                "o la activación de la voz, no hacer nada o volver atrás?";
                                toSpeech = new TextToSpeech(this, this);
                            }
                            else if (accion == "tipo")
                            {
                                if (result.ToLower().Contains("cancelar"))
                                {
                                    countSpeech  = 0;
                                    textToSpeak += "¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                   "o la activación de la voz, no hacer nada o volver atrás?";
                                    toSpeech = new TextToSpeech(this, this);
                                }
                                else
                                {
                                    bool exist = false;
                                    foreach (var item in listVoice)
                                    {
                                        if (item.Name == result)
                                        {
                                            v     = item;
                                            exist = true;
                                            break;
                                        }
                                    }
                                    if (exist)
                                    {
                                        try
                                        {
                                            countSpeech           = 0;
                                            configuracion.TipoVoz = result;
                                            configRepository.UpdateConfig(configuracion);
                                            toSpeech.SetVoice(v);
                                            textToSpeak = "Voz modificada. ¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                          "o la activación de la voz, no hacer nada o volver atrás?";
                                        }
                                        catch (Exception ex)
                                        {
                                            countSpeech = 0;
                                            textToSpeak = "Ha ocurrido un error al acceder a la base de datos. Por favor, inténtelo más tarde. ¿Quiere modificar" +
                                                          " su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                          "o la activación de la voz, no hacer nada o volver atrás?";
                                        }
                                    }
                                    else
                                    {
                                        countSpeech = 1;
                                        textToSpeak = "No existe ese tipo de voz. Por favor, diga otro nombre de voz o cancelar";
                                    }
                                    toSpeech = new TextToSpeech(this, this);
                                }
                            }
                            else if (accion == "activar" && (result.ToLower().Contains("si") || result.ToLower().Contains("sí")))
                            {
                                try
                                {
                                    countSpeech       = 0;
                                    configuracion.Voz = !configuracion.Voz;
                                    string texto = configuracion.Voz ? "activada" : "desactivada";
                                    configRepository.UpdateConfig(configuracion);
                                    textToSpeak = $"Voz {texto}. ¿Quiere modificar su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                  "o la activación de la voz, no hacer nada o volver atrás?";
                                }
                                catch (Exception ex)
                                {
                                    countSpeech = 0;
                                    textToSpeak = "Ha ocurrido un error al acceder a la base de datos. Por favor, inténtelo más tarde. ¿Quiere modificar" +
                                                  " su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                  "o la activación de la voz, no hacer nada o volver atrás?";
                                }
                                toSpeech = new TextToSpeech(this, this);
                            }
                        }
                        else if (countSpeech == 3)
                        {
                            if (accion == "usuario")
                            {
                                if (result.ToLower().Contains("cancelar"))
                                {
                                    countSpeech = 0;
                                    textToSpeak = "¿Quiere modificar tu nombre de usuario, el tipo de voz, la velocidad de lectura o " +
                                                  "la activación de la voz, no hacer nada o volver atrás?";
                                    toSpeech = new TextToSpeech(this, this);
                                }
                                else
                                {
                                    try
                                    {
                                        bool valido = userService.CheckUsername(client, result);
                                        if (valido)
                                        {
                                            try
                                            {
                                                userService.UpdateUsername(client, result, userRepository);
                                                Vibrator vibrator = (Vibrator)this.GetSystemService(Context.VibratorService);
                                                vibrator.Vibrate(500);
                                                countSpeech = 0;
                                                textToSpeak = $"Su nombre de usuario ha sido modificado correctamente a {result}. ¿Quiere modificar tu nombre de usuario, " +
                                                              "el tipo de voz, la velocidad de lectura o la activación de la voz, no hacer nada o volver atrás?";
                                            }
                                            catch (Exception ex)
                                            {
                                                countSpeech = 0;
                                                textToSpeak = "Ha ocurrido un error al modificar su nombre de usuario. Por favor, inténtelo más tarde. ¿Quiere modificar" +
                                                              " su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                              "o la activación de la voz, no hacer nada o volver atrás?";
                                            }
                                            toSpeech = new TextToSpeech(this, this);
                                        }
                                        else
                                        {
                                            countSpeech = 2;
                                            textToSpeak = "El nombre de usuario no es válido. Por favor, diga otro nombre de usuario o cancelar";
                                            toSpeech    = new TextToSpeech(this, this);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        countSpeech = 0;
                                        textToSpeak = "Ha ocurrido un error al modificar su nombre de usuario. Por favor, inténtelo más tarde. ¿Quiere modificar" +
                                                      " su nombre de usuario, el tipo de voz, la velocidad de lectura " +
                                                      "o la activación de la voz, no hacer nada o volver atrás?";
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Ejemplo n.º 8
0
        protected override void OnResume()
        {
            base.OnResume();

            configRepo    = new ConfigRepository(database);
            configuracion = configRepo.GetConfig();

            if (listaContactos.Count > 0)
            {
                textToSpeak = "Sus contactos bloqueados son: ";
                for (int i = 0; i < listaContactos.Count; i++)
                {
                    if (listaContactos.Count == 1)
                    {
                        textToSpeak += $"{listaContactos[i]}. ";
                    }
                    else
                    {
                        if (i == (listaContactos.Count - 1))
                        {
                            textToSpeak += $"y {listaContactos[i]}. ";
                        }
                        else
                        {
                            textToSpeak += $"{listaContactos[i]}, ";
                        }
                    }
                }
            }
            else
            {
                textToSpeak = "No tienes contactos bloqueados. ";
            }

            textToSpeak += "¿Quiere bloquear un contacto, desbloquear un contacto, no hacer nada o volver atrás?";

            try
            {
                client = loginService.Connect();

                if (client.IsUserAuthorized())
                {
                    usuario = client.Session.TLUser;
                }
            }
            catch (Exception ex)
            {
                this.FinishAffinity();
            }

            speechReco = SpeechRecognizer.CreateSpeechRecognizer(this.ApplicationContext);
            speechReco.SetRecognitionListener(this);
            intentReco = new Intent(RecognizerIntent.ActionRecognizeSpeech);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguagePreference, "es");
            intentReco.PutExtra(RecognizerIntent.ExtraCallingPackage, this.PackageName);
            intentReco.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelWebSearch);
            intentReco.PutExtra(RecognizerIntent.ExtraMaxResults, 1);

            gestureDetector = new GestureDetector(this);
            toSpeech        = new TextToSpeech(this, this);
        }
Ejemplo n.º 9
0
        public void OnResults(Bundle results)
        {
            int countOnResults = 0;
            IEnumerable <string> matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
            string   text = "", codigo = "", hash = "";
            bool     isRegistered = true;
            TLUser   user;
            DateTime ahora = DateTime.UtcNow;

            Android.Net.Uri inboxURI = Android.Net.Uri.Parse("content://sms/inbox");

            foreach (string result in matches)
            {
                countOnResults++;
                try
                {
                    if (countOnResults == 1)
                    {
                        record = true;
                        if (int.TryParse(result[0].ToString(), out int num))
                        {
                            text = result.Replace(" ", string.Empty);
                            if (text.Length == 9)
                            {
                                telephone  = "34" + text;
                                phone.Text = telephone;

                                client = loginService.Connect();

                                isRegistered = loginService.IsPhoneRegistered(client, telephone);
                                if (!isRegistered)
                                {
                                    textToSpeak = "No tiene una cuenta registrada. ¿Cuál quiere que sea su nombre de usuario?";
                                    toSpeech    = new TextToSpeech(this, this);
                                }
                                else
                                {
                                    if (!client.IsUserAuthorized())
                                    {
                                        hash   = loginService.SendCodeRequest(client, telephone);
                                        codigo = LookForSms(ahora);
                                        if (codigo == "Ha habido un error")
                                        {
                                            record      = false;
                                            textToSpeak = "Ha habido un error en la recepción del SMS. Por favor, inténtelo en aproximadamente media hora";
                                            toSpeech    = new TextToSpeech(this, this);
                                        }
                                        else
                                        {
                                            code.Text = codigo;
                                            user      = loginService.MakeAuth(client, telephone, hash, codigo);

                                            try
                                            {
                                                User u = new User
                                                {
                                                    Phone          = telephone,
                                                    Username       = user.Username,
                                                    Hash           = hash,
                                                    Code           = codigo,
                                                    SessionExpires = (new DateTime(1970, 1, 1)).AddMilliseconds(client.Session.SessionExpires).AddHours(1),
                                                    AccessHash     = user.AccessHash
                                                };
                                                userRepo.InsertUser(u);

                                                configuracion = new Models.Config()
                                                {
                                                    Phone     = telephone,
                                                    Voz       = true,
                                                    Velocidad = (float)1.0,
                                                    TipoVoz   = toSpeech.Voice != null ? toSpeech.Voice.Name : ""
                                                };
                                                configRepo.InsertConfig(configuracion);
                                                bool contactos           = contactService.GetContacts(client, contactRepo);
                                                bool contactosBloqueados = contactService.GetBlockedContacts(client, contactRepo);
                                            }
                                            catch (Exception ex) { }

                                            Vibrator vibrator = (Vibrator)this.GetSystemService(Context.VibratorService);
                                            vibrator.Vibrate(1000);
                                            record = false;
                                            // Creación sesión
                                            InitSession(telephone);

                                            textToSpeak = "Login correcto";
                                            toSpeech    = new TextToSpeech(this, this);
                                        }
                                    }
                                    else
                                    {
                                        user = client.Session.TLUser;

                                        try
                                        {
                                            User u = new User
                                            {
                                                Phone          = telephone,
                                                Username       = user.Username,
                                                Hash           = hash,
                                                Code           = codigo,
                                                SessionExpires = (new DateTime(1970, 1, 1)).AddMilliseconds(client.Session.SessionExpires).AddHours(1),
                                                AccessHash     = user.AccessHash
                                            };
                                            userRepo.InsertUser(u);
                                            configuracion = new Models.Config()
                                            {
                                                Phone     = telephone,
                                                Voz       = true,
                                                Velocidad = (float)1.0,
                                                TipoVoz   = toSpeech.Voice != null ? toSpeech.Voice.Name : ""
                                            };
                                            configRepo.InsertConfig(configuracion);
                                        }
                                        catch (Exception ex) { }
                                        // Creación sesión
                                        InitSession(telephone);
                                        Vibrator vibrator = (Vibrator)this.GetSystemService(Context.VibratorService);
                                        vibrator.Vibrate(1000);
                                        record      = false;
                                        textToSpeak = "Login correcto";
                                        toSpeech    = new TextToSpeech(this, this);
                                    }
                                }
                            }
                            else
                            {
                                record      = true;
                                textToSpeak = "El número de teléfono no tiene un formato correcto. Por favor, diga un número de teléfono válido";
                                toSpeech    = new TextToSpeech(this, this);
                            }
                        }
                        else
                        {
                            client = loginService.Connect();
                            hash   = loginService.SendCodeRequest(client, telephone);

                            codigo = LookForSms(ahora);

                            if (int.TryParse(codigo, out int num2))
                            {
                                record      = false;
                                textToSpeak = "Ha habido un error esperando el código de verificación. Por favor, inténtelo en 30 minutos";
                                toSpeech    = new TextToSpeech(this, this);
                            }
                            else
                            {
                                user = loginService.SignUp(client, telephone, hash, codigo, result, "");
                                user = loginService.MakeAuth(client, telephone, hash, codigo);

                                try
                                {
                                    User u = new User
                                    {
                                        Phone          = telephone,
                                        Username       = user.Username,
                                        Hash           = hash,
                                        Code           = codigo,
                                        SessionExpires = (new DateTime(1970, 1, 1)).AddMilliseconds(client.Session.SessionExpires).AddHours(1),
                                        AccessHash     = user.AccessHash
                                    };
                                    userRepo.InsertUser(u);

                                    configuracion = new Models.Config()
                                    {
                                        Phone     = telephone,
                                        Voz       = true,
                                        Velocidad = (float)1.0,
                                        TipoVoz   = toSpeech.Voice != null ? toSpeech.Voice.Name : ""
                                    };
                                    configRepo.InsertConfig(configuracion);

                                    bool contactos           = contactService.GetContacts(client, contactRepo);
                                    bool contactosBloqueados = contactService.GetBlockedContacts(client, contactRepo);
                                }
                                catch (Exception ex) { }
                                Vibrator vibrator = (Vibrator)this.GetSystemService(Context.VibratorService);
                                vibrator.Vibrate(1000);
                                record = false;

                                // Creación sesión
                                InitSession(telephone);

                                textToSpeak = "Registro y login correctos";
                                toSpeech    = new TextToSpeech(this, this);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // TODO: cerrar la aplicación
                    record = false;
                    database.DeleteDataDatabase();
                    FakeSessionDelete.DeleteSession();
                    textToSpeak = "Ha ocurrido un error. Por favor, inténtelo más tarde";
                    toSpeech    = new TextToSpeech(this, this);
                }
            }
        }