public void receiver()
 {
     while (activo)
     {
         if (SettingsHelper.GetSetting("servicio") == "matar")
         {
             SettingsHelper.SaveSetting("servicio", "");
             activo = false;
             StopSelf();
         }
         if (SettingsHelper.GetSetting("cquerry").Trim() != "")
         {
             string qvalue = SettingsHelper.GetSetting("cquerry").Trim();
             SettingsHelper.SaveSetting("cquerry", "");
             if (qvalue.StartsWith("data()"))
             {
                 linkactual   = (qvalue.Split('>')[2]);
                 tituloactual = (qvalue.Split('>')[1]);
                 ipactual     = (qvalue.Split('>')[3]);
                 if (linkactual.Trim().Length > 1 && tituloactual.Trim().Length > 1)
                 {
                     mostrarnotificacion();
                 }
             }
         }
         Thread.Sleep(1500);
     }
 }
        public async void enviaratodos(string token, FirebaseClient firebase)
        {
            if (File.Exists(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/webclients.gr3wc"))
            {
                var textotodo = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/webclients.gr3wc");
                textotodo = textotodo.Remove(textotodo.Length - 1, 1);

                string serial = Utils.StringsHelper.GenerateSerial();



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

                /*
                 *              var items = await firebase
                 *           .Child("yourentity")
                 * //.WithAuth("<Authentication Token>") // <-- Add Auth token if required. Auth instructions further down in readme.
                 *          .OrderByKey()
                 *          .OnceAsync<YourObject>();
                 *
                 */


                foreach (var prro in textotodo.Split('¤'))
                {
                    var diccio = new Dictionary <string, string>();
                    diccio.Add(SettingsHelper.GetSetting("uniqueid"), serial);
                    //  mapita.Add(prro, diccio);
                    await firebase.Child("WEB").Child(prro).WithAuth(token).PatchAsync(diccio);
                }
            }
        }
示例#3
0
 public void adart()
 {
     while (detenedor)
     {
         if (SettingsHelper.GetSetting("refrescarlistadatos") == "ok")
         {
             SettingsHelper.SaveSetting("refrescarlistadatos", "");
             refrescar();
         }
         Thread.Sleep(150);
     }
 }
        public void playpause()
        {
            if (SettingsHelper.GetSetting("playerstatus") != "reproduciendo")
            {
                SettingsHelper.SaveSetting("cquerry", "play()");
            }
            else

            {
                SettingsHelper.SaveSetting("cquerry", "pause()");
            }
        }
示例#5
0
        public async void initial_boot()
        {
            setinitialsettings();
            if (SettingsHelper.HasKey("abrirserver"))
            {
                if (SettingsHelper.GetSetting("abrirserver") == "si")
                {
                    if (serviciostreaming.gettearinstancia() != null)
                    {
                        StopService(new Intent(this, typeof(serviciostreaming)));
                        StartService(new Intent(this, typeof(serviciostreaming)));
                    }
                    else
                    {
                        StartService(new Intent(this, typeof(serviciostreaming)));
                    }
                }
            }
            if (!File.Exists(Constants.CachePath + "/verified"))
            {
                if (MultiHelper.HasInternetConnection())
                {
                    string serial = StringsHelper.GenerateSerial();
                    if (Constants.UseFirebase)
                    {
                        var firebase = new FirebaseClient(Constants.FirebaseSuggestionsUrl);
                        await firebase.Child("Descargas").Child(serial).PutAsync("Descargada@" + Android.OS.Build.Model + "@" + System.DateTime.Now);
                    }
                    var arch = File.CreateText(Constants.CachePath + "/verified");
                    arch.Write(serial);
                    arch.Close();
                }
            }

            checkedpremissions = true;
        }
        public void descargar(string path, string archivo, string titulo, string link)
        {
            WebClient cliente2 = new WebClient();

            cliente2.DownloadFileAsync(new Uri("https://i.ytimg.com/vi/" + link.Split('=')[1] + "/mqdefault.jpg"), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + link.Split('=')[1]);
            //new
            if (titulo.Trim().Length > 45)
            {
                titulo = titulo.Remove(45);
            }
            tituloo = titulo;


            var manige = DownloadManager.FromContext(this);
            var requ   = new DownloadManager.Request(Android.Net.Uri.Parse(archivo));

            requ.SetDescription("Espere por favor");
            requ.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
            requ.SetTitle(tituloo);
            var destino = Android.Net.Uri.FromFile(new Java.IO.File(path));

            if (SettingsHelper.GetSetting("rutadescarga") == Android.OS.Environment.DirectoryDownloads)
            {
                requ.SetDestinationInExternalPublicDir(SettingsHelper.GetSetting("rutadescarga"), Path.GetFileName(path));
            }
            else
            {
                requ.SetDestinationUri(destino);
            }
            requ.AllowScanningByMediaScanner();

            requ.SetVisibleInDownloadsUi(true);



            manige.Enqueue(requ);

            if (Path.GetFileName(path).EndsWith(".mp3"))
            {
                ////////////////si es mp3
                string datosviejos = "";
                if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d"))
                {
                    datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                }
                else
                {
                    var asss = File.Create(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    asss.Close();
                }
                if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
                }

                if (!datosviejos.Contains(link.Split('=')[1]))
                {
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
                    aafff.Close();
                }
                else
                {
                    var datosparsed   = PlaylistsHelper.GetMedia(Constants.CachePath + "/downloaded.gr3d");
                    var videoid       = link.Split('=')[1];
                    int indexelemento = datosparsed.FindIndex(ax => ax.Link.Contains(videoid));
                    datosparsed[indexelemento].Path = path;
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
                    aafff.Write(PlaylistsHelper.SerializeMedia(datosparsed));
                    aafff.Close();
                }
            }
            //////////////////////////////////////////////si es mp4
            else
            {
                string datosviejos = "";
                if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2"))
                {
                    datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                }
                else
                {
                    var asss = File.Create(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    asss.Close();
                }
                if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
                }

                if (!datosviejos.Contains(link.Split('=')[1]))
                {
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
                    aafff.Close();
                }
                else
                {
                    var datosparsed   = PlaylistsHelper.GetMedia(Constants.CachePath + "/downloaded.gr3d2");
                    var videoid       = link.Split('=')[1];
                    int indexelemento = datosparsed.FindIndex(ax => ax.Link.Contains(videoid));
                    datosparsed[indexelemento].Path = path;
                    var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
                    aafff.Write(PlaylistsHelper.SerializeMedia(datosparsed));
                    aafff.Close();
                }
                MultiHelper.ExecuteGarbageCollection();
            }



            /*
             * Random brandom = new Random();
             * WebClient cliente2= new WebClient();
             * cliente2.DownloadFileAsync(new Uri("https://i.ytimg.com/vi/" + link.Split('=')[1] + "/mqdefault.jpg"), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + link.Split('=')[1]);
             * int randum = brandom.Next(2000, 50000) + brandom.Next(2000, 50000);
             * random = randum;
             * try {
             *  NotificationManager notificationManager =
             *   GetSystemService(Context.NotificationService) as NotificationManager;
             *  if (titulo.Trim().Length > 30)
             *  {
             *      titulo = titulo.Remove(30);
             *  }
             *  tituloo = titulo;
             *  var builder = new Notification.Builder(ApplicationContext);
             *  builder.SetContentTitle("Descargando " + titulo + "...");
             *  builder.SetContentText("Espere por favor");
             *
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *
             *
             *
             *  WebClient cliente = new WebClient();
             *
             * byte[] losbits = null;
             *  cliente.DownloadProgressChanged += (aasd, asddd) =>
             *  {
             *
             *      builder.SetContentTitle("Descargando "+titulo+"...");
             *      builder.SetContentText("Espere por favor");
             *      builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *      builder.SetProgress(100, asddd.ProgressPercentage, false);
             *      notificationManager.Notify(randum, builder.Build());
             *
             *  };
             * cliente.DownloadDataCompleted += (aa, aaa) =>
             * {
             *
             *  //  Intent intentss = new Intent(this,typeof(actividadacciones));
             *  //  intentss.PutExtra("prro", path);
             *  try {
             *  var selectedUri = Android.Net.Uri.Parse( prefs.GetString("rutadescarga",null)+ "/");
             *
             *  Intent intentssdd = new Intent(this,typeof(actividadadinfooffline));
             *  intentssdd.PutExtra("nombre", Path.GetFileName(path));
             *  intentssdd.PutExtra("link", link);
             *  intentssdd.PutExtra("path", path);
             *
             *
             *
             *
             *
             *  PendingIntent intentosd = PendingIntent.GetActivity(this, brandom.Next(2000, 50000) + brandom.Next(2000, 50000), intentssdd, PendingIntentFlags.UpdateCurrent);
             *
             *
             *  builder.SetContentTitle("Descarga completada de: "+titulo);
             *  builder.SetContentText("Toque para abrir");
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *  builder.SetContentIntent(intentosd);
             *      builder.SetOngoing(false);
             *      notificationManager.Notify(randum, builder.Build());
             *
             *  losbits = aaa.Result;
             *  var a = File.Create(path);
             *  a.Write(losbits, 0, losbits.Length);
             *  a.Close();
             *  string datosviejos = "";
             *  link = link.Replace('²', ' ');
             *  link= link.Replace('¤', ' ');
             *  path =path.Replace('²', ' ');
             *  path=path.Replace('¤', ' ');
             *
             *
             *  if (Path.GetFileName(path).EndsWith(".mp3")) {
             *  ///////////////////////////si es mp3
             *
             *  if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d"))
             *  {
             *     datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
             *  }
             *  if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
             *  {
             *      Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
             *  }
             *
             *  if(!datosviejos.Contains(Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤"))
             *  {
             *      var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d");
             *      aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
             *      aafff.Close();
             *
             *  }
             *
             *
             *  }
             *  //////////////////////////////////////////////si es mp4
             *  else
             *  {
             *      if (File.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2"))
             *      {
             *          datosviejos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
             *      }
             *      if (!Directory.Exists(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits"))
             *      {
             *          Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits");
             *      }
             *
             *      if (!datosviejos.Contains(Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤"))
             *      {
             *          var aafff = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/" + "downloaded.gr3d2");
             *          aafff.Write(datosviejos + Path.GetFileNameWithoutExtension(path) + "²" + link + "²" + path + "¤");
             *          aafff.Close();
             *
             *      }
             *          clasesettings.recogerbasura();
             *  }
             *      completada = true;
             *  }
             *  catch (Exception)
             *  {
             *      clasesettings.recogerbasura();
             *      Toast.MakeText(this, "ha ocurrido un error al descargar intente de nuevo", ToastLength.Long).Show();
             *     // StopForeground(false);
             *  }
             *
             * };
             *
             *  cliente.DownloadData(new Uri(archivo));
             * }
             * catch (Exception)
             * {
             *  NotificationManager notificationManager =
             *  GetSystemService(Context.NotificationService) as NotificationManager;
             *  var builder = new Notification.Builder(ApplicationContext);
             *  builder.SetContentTitle("ERROR AL DESCARGAR: " + titulo);
             *  builder.SetContentText("Intente de nuevo");
             *  builder.SetSmallIcon(Resource.Drawable.downloadbutton);
             *  builder.SetOngoing(false);
             *  notificationManager.Notify(randum, builder.Build());
             *  clasesettings.recogerbasura();
             *
             * }
             */
        }
        /// <summary>
        /// //////////////////////////////////////////////////ignore
        /// </summary>
        /// <param name="path"></param>
        /// <param name="linkarchivo"></param>


        ///



        public void descargame(string nombrearchivo, string linkarchivo, string patharchivo)
        {
            int       notiide = rondon.Next(24, 100000);
            WebClient cliente = new WebClient();

            ///cliente.Encoding = Encoding.UTF8;
            // cliente.Credentials = new NetworkCredential("anonymous", "");



            string titulo  = "Descargando localmente: " + Path.GetFileNameWithoutExtension(nombrearchivo);
            string tituloo = "";

            NotificationManager notificationManager =
                GetSystemService(Context.NotificationService) as NotificationManager;

            if (nombrearchivo.Trim().Length > 40)
            {
                titulo = titulo.Remove(40);
            }
            tituloo = titulo;
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
            var builder = new Notification.Builder(ApplicationContext);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
            builder.SetContentTitle(titulo);
            builder.SetContentText("Espere por favor");
            builder.SetSmallIcon(Resource.Drawable.downloadbutton);
            builder.SetProgress(100, progreso, true);
            notificationManager.Notify(notiide, builder.Build());



            RunOnUiThread(() => Toast.MakeText(this, "Descargando localmente: " + Path.GetFileNameWithoutExtension(nombrearchivo) + " se le notificara de su progreso", ToastLength.Long).Show());



            cliente.DownloadFileCompleted += (aa, aaa) =>
            {
                progreso = 100;
                WebClient cliente2 = new WebClient();
                cliente2.Encoding    = Encoding.UTF8;
                cliente2.Credentials = new NetworkCredential("anonymous", "");

                cliente2.DownloadFileCompleted += delegate
                {
                };
                if (pathimagenesdelotro.StartsWith("/"))
                {
                    cliente2.DownloadFile(new Uri(@"ftp://" + ipdelotro + ":" + puertoarchivosdelotro + pathimagenesdelotro + linkarchivo.Split('=')[1]), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + linkarchivo.Split('=')[1]);
                }
                else
                {
                    try {
                        cliente2.DownloadFile(new Uri(@"ftp://" + ipdelotro + ":" + puertoarchivosdelotro + "/" + getteardisco(pathimagenesdelotro) + linkarchivo.Split('=')[1] + ".jpg"), Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + linkarchivo.Split('=')[1]);
                    }
                    catch (Exception)
                    {
                        try {
                            cliente2.DownloadFile("http://i.ytimg.com/vi/" + linkarchivo.Split('=')[1] + "/mqdefault.jpg", Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/" + linkarchivo.Split('=')[1]);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                // string perruris = "ftp://" + ipdelotro + ":" + puertoarchivosdelotro + "/" + getteardisco(pathimagenesdelotro) + linkarchivo.Split('=')[1] + ".jpg";



                escribirenregistro(Path.Combine(SettingsHelper.GetSetting("rutadescarga"), nombrearchivo), linkarchivo);
                Intent intentssdd = new Intent(this, typeof(actividadadinfooffline));
                intentssdd.PutExtra("nombre", Path.GetFileName(nombrearchivo));
                intentssdd.PutExtra("link", linkarchivo);
                intentssdd.PutExtra("path", Path.Combine(SettingsHelper.GetSetting("rutadescarga"), nombrearchivo));



                PendingIntent intentosd = PendingIntent.GetActivity(this, rondon.Next(24, 100000), intentssdd, PendingIntentFlags.UpdateCurrent);
                string        titulo2   = "Descarga local completada de : " + Path.GetFileNameWithoutExtension(nombrearchivo);
                string        tituloo2  = "";

                if (nombrearchivo.Trim().Length > 40)
                {
                    titulo2 = titulo2.Remove(40);
                }
                tituloo2 = titulo2;

                builder.SetContentTitle(titulo2);
                builder.SetContentText("Toque para abrir");
                builder.SetSmallIcon(Resource.Drawable.downloadbutton);
                builder.SetContentIntent(intentosd);
                builder.SetProgress(1, 1, false);
                notificationManager.Notify(notiide, builder.Build());
                RunOnUiThread(() => Toast.MakeText(this, "Descarga local de: " + Path.GetFileNameWithoutExtension(nombrearchivo) + " completada", ToastLength.Long).Show());
                new Thread(() => {
                    if (selectedtab == "Audios")
                    {
                        playeroffline.gettearinstancia().cargarmp3();
                    }
                    else
                    {
                        playeroffline.gettearinstancia().cargarvideos();
                    }


                    var adaptadol2 = new adapterlistaoffline(this, playeroffline.gettearinstancia().nombreses.ToList(), playeroffline.gettearinstancia().linkeses, "", playeroffline.gettearinstancia().nombreses, playeroffline.gettearinstancia().diccionario, playeroffline.gettearinstancia().patheses);
                    RunOnUiThread(() => listaelementos.Adapter = adaptadol2);
                }).Start();
            };
            if (patharchivo.StartsWith("/"))
            {
                cliente.DownloadFileAsync(new Uri(@"ftp://" + ipdelotro + ":" + puertoarchivosdelotro + patharchivo), Path.Combine(SettingsHelper.GetSetting("rutadescarga"), nombrearchivo));
            }
            else
            {
                cliente.DownloadFileAsync(new Uri(@"ftp://" + ipdelotro + ":" + puertoarchivosdelotro + "/" + getteardisco(patharchivo)), Path.Combine(SettingsHelper.GetSetting("rutadescarga"), nombrearchivo));
            }
        }
 public void sincronizar()
 {
     clientequerry.Client.Send(Encoding.UTF8.GetBytes("dataserver()¤" + miip + "¤" + mipuertoquerry + "¤" + mipuertoarchivo + "¤" + SettingsHelper.GetSetting("rutadescarga") + "¤" + mipathimagenes));
 }
        private Android.Graphics.Bitmap GetQRCode()
        {
            var writer = new ZXing.Mobile.BarcodeWriter();

            writer.Format         = ZXing.BarcodeFormat.QR_CODE;
            writer.Options.Margin = 1;
            writer.Options.Height = 500;
            writer.Options.Width  = 500;



            return(writer.Write(miip + "¤" + mipuertoquerry + "¤" + mipuertoarchivo + "¤" + SettingsHelper.GetSetting("rutadescarga") + "¤" + Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/portraits/"));
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.Configuraciones);

            ISharedPreferences       prefs      = Application.Context.GetSharedPreferences("Settings", FileCreationMode.Private);
            ISharedPreferencesEditor prefEditor = prefs.Edit();

            botonseleccionarcarpeta = FindViewById <Button>(Resource.Id.imageView1);
            localizacion            = FindViewById <TextView>(Resource.Id.textView3);
            //   botonguardar = FindViewById<ImageView>(Resource.Id.imageView2);
            var colormuestra = FindViewById <ImageView>(Resource.Id.imageView3);

            colormuestra.SetBackgroundColor(Color.ParseColor(SettingsHelper.GetSetting("color")));
            color            = SettingsHelper.GetSetting("color");
            reprodautomatica = SettingsHelper.GetSetting("automatica");
            var ll1             = FindViewById <LinearLayout>(Resource.Id.linearLayout3);
            var ll2             = FindViewById <LinearLayout>(Resource.Id.linearLayout4);
            var ll3             = FindViewById <LinearLayout>(Resource.Id.linearLayout5);
            var ll4             = FindViewById <LinearLayout>(Resource.Id.linearLayout7);
            var ll5             = FindViewById <LinearLayout>(Resource.Id.linearLayout23);
            var fondo           = FindViewById <ImageView>(Resource.Id.fondo1);
            var toggle1         = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton1);
            var toggle2         = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.toggleButton2);
            var automatica      = FindViewById <Android.Support.V7.Widget.SwitchCompat>(Resource.Id.automatico);
            var botonclearcache = FindViewById <LinearLayout>(Resource.Id.linearLayout8);

            calidades = FindViewById <Spinner>(Resource.Id.spinner1);
            var action = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.my_toolbar);

            //////////////////////////////////////coloreselector mappings

#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
            dialogoprogreso = new ProgressDialog(this);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
            ///////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////////////
            ///
            if (reprodautomatica == "si")
            {
                automatica.Checked = true;
            }
            else
            {
                automatica.Checked = false;
            }


            SetSupportActionBar(action);
            SupportActionBar.Title = "Preferencias";
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);

            var adapter = new  ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem);
            adapter.AddAll(new string[] { "Audio", "360p", "720p" }.ToList());
            adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
            calidades.Adapter = adapter;

            color   = SettingsHelper.GetSetting("color");
            calidad = int.Parse(SettingsHelper.GetSetting("video"));
            switch (calidad)
            {
            case -1:
                calidades.SetSelection(0);
                break;

            case 360:
                calidades.SetSelection(1);
                break;

            case 720:
                calidades.SetSelection(2);
                break;
            }

            if (SettingsHelper.HasKey("abrirserver"))
            {
                abrirserver = SettingsHelper.GetSetting("abrirserver");
            }
            if (abrirserver == "no")
            {
                toggle2.Checked = false;
            }
            else
            {
                toggle2.Checked = true;
            }


            if (SettingsHelper.HasKey("ordenalfabeto"))
            {
                ordenalfabeto = SettingsHelper.GetSetting("ordenalfabeto");

                if (ordenalfabeto == "si")
                {
                    toggle1.Checked = true;
                }
                else
                {
                    toggle1.Checked = false;
                }
            }

            if (SettingsHelper.HasKey("rutadescarga"))
            {
                klk = prefs.GetString("rutadescarga", null);
            }
            else
            {
                if (Directory.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads"))
                {
                    klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads";
                    prefEditor.PutString("rutadescarga", klk);
                    prefEditor.Commit();
                }
                else
                {
                    Directory.CreateDirectory(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads");
                    klk = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/YTDownloads";
                    prefEditor.PutString("rutadescarga", klk);
                    prefEditor.Commit();
                }
            }

            localizacion.Text = klk;

            fondo.SetImageBitmap(CreateBlurredImageoffline(this, 20, 0));
            ////////////////////////////////clicks////////////////////////////

            calidades.ItemSelected += (axx, ssd) => {
                switch (ssd.Position)
                {
                case 0:
                    calidad = -1;
                    break;

                case 1:
                    calidad = 360;
                    break;

                case 2:
                    calidad = 720;
                    break;
                }
            };
            automatica.Click += delegate
            {
                if (automatica.Checked)
                {
                    reprodautomatica = "si";
                    Toast.MakeText(this, "Si no hay mas elementos en cola se reproducira el primer elemento de las sugerencias", ToastLength.Long).Show();
                }
                else
                {
                    reprodautomatica = "no";
                    Toast.MakeText(this, "Si no hay mas elementos en cola no se ejecutara ninguna accion", ToastLength.Long).Show();
                }
            };
            toggle2.Click += delegate
            {
                if (toggle2.Checked)
                {
                    new Thread(() =>
                    {
                        if (PlaylistsHelper.HasMediaElements)
                        {
                            if (File.Exists(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v"))
                            {
                                abrirserver = "si";

                                StartService(new Intent(this, typeof(serviciostreaming)));
                            }
                            else

                            {
                                AlertDialog dialogo = null;
                                RunOnUiThread(() => {
                                    var progresox           = new ProgressBar(this);
                                    progresox.Indeterminate = true;

                                    dialogo = new AlertDialog.Builder(this)
                                              .SetTitle("Buscando actualizaciones")
                                              .SetMessage("Por favor espere...")
                                              .SetCancelable(false)
                                              .SetView(progresox)
                                              .Show();
                                });
                                if (CheckInternetConnection())
                                {
                                    abrirserver        = "si";
                                    AlertDialog alerta = null;
                                    RunOnUiThread(() =>
                                    {
                                        dialogo.Dismiss();
                                        var progreso           = new ProgressBar(this);
                                        progreso.Indeterminate = true;

                                        alerta = new AlertDialog.Builder(this)
                                                 .SetTitle("Descargando archivos necesarios")
                                                 .SetMessage("Por favor espere...")
                                                 .SetCancelable(false)
                                                 .SetView(progreso)
                                                 .Show();
                                    });
                                    new Thread(() =>
                                    {
                                        WebClient cliente = new WebClient();
                                        var version       = cliente.DownloadString("https://raw.githubusercontent.com/Gr3gorywolf/Multitube.android/master/Updates/version.gr3v");
                                        using (var file = File.CreateText(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.gr3cache/version.gr3v")) {
                                            file.Write(version);
                                            file.Close();
                                        }
                                        MultitubeWebHelper.UpdateMultitubeWeb(version);
                                        RunOnUiThread(() =>
                                        {
                                            alerta.Dismiss();
                                            StartService(new Intent(this, typeof(serviciostreaming)));
                                            new AlertDialog.Builder(this)
                                            .SetTitle("Informacion")
                                            .SetMessage("El servidor de streaming le permitirara reproducir su contenido previamente descargado desde cualquier navegador de cualquier dispositivo conectado a su misma red. Puede consultar el estado de este en la barra de notificaciones")
                                            .SetPositiveButton("Entendido!", (aa, fff) => { })
                                            .Create()
                                            .Show();
                                        });
                                    }).Start();
                                }
                                else
                                {
                                    RunOnUiThread(() =>
                                    {
                                        dialogo.Dismiss();
                                        Toast.MakeText(this, "Debe tener una conexion a internet para abrir el servicio por primera vez", ToastLength.Long).Show();
                                        toggle2.Checked = false;
                                    });
                                }
                            }
                        }
                        else
                        {
                            RunOnUiThread(() =>
                            {
                                toggle2.Checked = false;
                                Toast.MakeText(this, "Debe tener almenos 1 elemento descargado", ToastLength.Long).Show();
                            });
                        }
                    }).Start();
                }
                else
                {
                    if (serviciostreaming.gettearinstancia() != null)
                    {
                        StopService(new Intent(this, typeof(serviciostreaming)));
                    }
                    toggle2.Checked = false;
                    abrirserver     = "no";
                }
            };
            botonclearcache.Click += delegate
            {
                AlertDialog.Builder ad = new AlertDialog.Builder(this);
                ad.SetCancelable(false);
                ad.SetTitle("Advertencia");
                ad.SetIcon(Resource.Drawable.alert);
                ad.SetMessage("Limpiar el cache puede provocar cierta realentizacion a la hora de entrar al reproductor offline y tambien volvera a descargar los datos por lo cual necesitara internet ¿¿quiere borrar cache??");
                ad.SetNegativeButton("No", no);
                ad.SetPositiveButton("Si", si);
                ad.Create();
                ad.Show();
            };
            toggle1.Click += delegate
            {
                if (toggle1.Checked == true)
                {
                    ordenalfabeto = "si";
                    Toast.MakeText(this, "Los elementos se organizaran alfabeticamente", ToastLength.Long).Show();
                }
                else
                {
                    ordenalfabeto = "no";
                    Toast.MakeText(this, "Los elementos se por fecha de descarga", ToastLength.Long).Show();
                }
            };
            botonseleccionarcarpeta.Click += async delegate
            {
                SimpleFileDialog sfd = new SimpleFileDialog(this, SimpleFileDialog.FileSelectionMode.FolderChooseRoot);
                klk = await sfd.GetFileOrDirectoryAsync(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath);

                if (probarpath(klk))
                {
                    pathvalido = true;

                    localizacion.Text = klk;
                }
                else
                {
                    Toast.MakeText(this, "Ruta invalida seleccione otra", ToastLength.Short).Show();
                    klk        = localizacion.Text;
                    pathvalido = false;
                }
            };
        }
        public void reproducir(string downloadurl, bool desdecache)
        {
            // musicaplayer.SetDataSource(downloadurl);
            if (playeroffline.gettearinstancia() != null)
            {
                try
                {
                    musicaplayer.Release();


                    musicaplayer = new MediaPlayer();

#pragma warning disable 414
                    if (Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.N)
                    {
                        musicaplayer.SetAudioAttributes(new AudioAttributes.Builder()
                                                        .SetUsage(AudioUsageKind.Media)
                                                        .SetContentType(AudioContentType.Music)
                                                        .Build());
                    }
                    else
                    {
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                        musicaplayer.SetAudioStreamType(Android.Media.Stream.Music);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
                    }

#pragma warning restore 414
                    musicaplayer.SetWakeMode(this, WakeLockFlags.Partial);
#pragma warning disable 414
#pragma warning disable CS0618 // El tipo o el miembro están obsoletos
                    var focusResult = audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
#pragma warning restore CS0618 // El tipo o el miembro están obsoletos
#pragma warning restore 414
                    if (focusResult != AudioFocusRequest.Granted)
                    {
                        //could not get audio focus
                        Console.WriteLine("Could not get audio focus");
                    }


                    musicaplayer.Prepared += delegate
                    {
                        musicaplayer.Start();
                        if (this.desdecache)
                        {
                            musicaplayer.Pause();
                        }
                        if (playeroffline.gettearinstancia() != null)
                        {
                            if (playeroffline.gettearinstancia().video.Visibility == ViewStates.Visible)
                            {
                                musicaplayer.SetDisplay(null);
                                musicaplayer.SetDisplay(playeroffline.gettearinstancia().holder);
                            }

                            if (SettingsHelper.HasKey("posactual") && this.desdecache)
                            {
                                var posicion = 0;
                                try
                                {
                                    posicion = int.Parse(SettingsHelper.GetSetting("posactual"));
                                    musicaplayer.SeekTo(posicion);
                                }
                                catch (Exception) { }
                            }
                        }
                    };
                    musicaplayer.Completion += delegate
                    {
                        playeroffline.gettearinstancia().RunOnUiThread(() =>
                        {
                            playeroffline.gettearinstancia().RunOnUiThread(() =>
                            {
                                playeroffline.gettearinstancia().siguiente.PerformClick();
                            });
                        });
                    };

                    musicaplayer.SetDataSource(this, Android.Net.Uri.Parse(downloadurl.Trim()));
                    mostrarnotificacion();
                    musicaplayer.PrepareAsync();
                }
                catch (Exception)
                {
                    //if()

                    playeroffline.gettearinstancia().RunOnUiThread(() =>
                    {
                        Toast.MakeText(playeroffline.gettearinstancia(), "Error al reproducir", ToastLength.Long).Show();
                    });
                }
            }
            else
            {
                musicaplayer.Reset();
                StopSelf();
            }
        }