Beispiel #1
0
        public void StartDownload()
        {
            MBDownloadManager.RequestDownload(DownloadUri, this);

            this.DownloadStato = DownloadStato.Downloading;             //in download
            SetUIState();
        }
        private static void InstallMbPackage(string uri, string localUri)
        {
            Uri qUri = new Uri(uri);

            localUri = Uri.UnescapeDataString(localUri);
            uri      = Uri.UnescapeDataString(uri);

            string fileName = System.IO.Path.GetFileName(localUri);

            string search = "/pub/";

            //string url = uri.AbsoluteUri;
            uri = uri.Substring(uri.IndexOf(search) + search.Length).Trim('/');

            string outPath = System.IO.Path.Combine(DataManager.Get <ISettingsManager>().Settings.DocPath, uri);

            //outPath = Path.Combine(outPath, parts[1]).Trim('/');
            outPath = System.Web.HttpUtility.UrlDecode(outPath);
            outPath = System.IO.Path.GetDirectoryName(outPath);

            string filePath = new Uri(localUri).LocalPath;

            try
            {
                if (System.IO.Path.GetExtension(localUri) == ".mb")
                {
                    //outPath = Path.Combine(outPath, fileName.Replace(fileExt, ".mbp"));
                    FileSystemManager.UnzipDocument(filePath, outPath);
                    File.Delete(filePath);
                    //ImageLoader.Instance.ClearDiskCache();
                    //ImageLoader.Instance.ClearMemoryCache();
                    MBImageLoader.RemoveFromCache(qUri.ToString());
                }
                else if (System.IO.Path.GetExtension(localUri) == ".pdf")
                {
                    outPath = System.IO.Path.Combine(outPath, fileName);
                    if (File.Exists(outPath))
                    {
                        File.Delete(outPath);
                    }

                    //se la cartella non esiste la creo
                    string dir = System.IO.Path.GetDirectoryName(outPath);

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    File.Move(filePath, outPath);
                }

                MBDownloadManager.FinishDownload(qUri, true);
            }
            catch (Exception value)
            {
                Console.WriteLine(value);
                MBDownloadManager.FinishDownload(qUri, false);
            }
        }
        static void NotifyDownloadListeners()
        {
            lock (requestQueue)
            {
                foreach (var quri in queuedUpdates)
                {
                    var list = pendingRequests[quri];
                    pendingRequests.Remove(quri);

                    DownloadInfo down = MBDownloadManager.DownloadInfo(quri.AbsoluteUri);

                    if (down != null)
                    {
                        Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Application.Context.GetSystemService("download");
                        downloadManager.Remove(down.Id);

                        MBDownloadManager.RegisterDownload(quri.ToString(), down.LocalUri);
                    }

                    foreach (var pr in list)
                    {
                        try
                        {
                            pr.DownloadCompleted(quri.AbsoluteUri, ""); // this is the bit that should be on the UiThread
                        }
                        catch (Exception e)
                        {
                            Log.Error("MWC", e.Message);
                        }
                    }
                }

                queuedUpdates.Clear();
            }
        }
        public static void StopDownload(Uri uri)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                if (pendingRequests.ContainsKey(uri))
                {
                    pendingRequests.Remove(uri);
                }

                if (queuedUpdates.Contains(uri))
                {
                    queuedUpdates.Remove(uri);
                }

                requestQueue = new Stack <Uri>(requestQueue.Where(i => i != uri).Reverse());

                DownloadInfo down = MBDownloadManager.DownloadInfo(uri.AbsoluteUri);

                if (down != null)
                {
                    MBDownloadManager.FinishDownload(uri, false);
                }
                else
                {
                }
            });
        }
        public static void InstallFinishedMB()
        {
            Android.App.DownloadManager.Query query = new Android.App.DownloadManager.Query();

            query.SetFilterByStatus(DownloadStatus.Successful);

            Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Context.GetSystemService("download");

            ICursor cursor = downloadManager.InvokeQuery(query);

            while (cursor.MoveToNext())
            {
                string localUri = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnLocalUri));
                string uri      = cursor.GetString(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnUri));
                long   id       = cursor.GetLong(cursor.GetColumnIndex(Android.App.DownloadManager.ColumnId));
                string filePath = new Uri(localUri).AbsolutePath;

                if (File.Exists(filePath))
                {
                    MBDownloadManager.InstallMbPackage(uri, localUri);
                    downloadManager.Remove(id);
                    //MBDownloadManager.FinishDownload(new Uri(uri), true);
                }
            }

            cursor.Close();
        }
        static void Download(Uri uri)
        {
            string fileName = Path.GetFileName(uri.LocalPath);

            Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Application.Context.GetSystemService("download");

            Android.App.DownloadManager.Request request = new Android.App.DownloadManager.Request(Android.Net.Uri.Parse(uri.AbsoluteUri));

            //Restrict the types of networks over which this download may proceed.
            request.SetAllowedNetworkTypes(Android.App.DownloadNetwork.Wifi | Android.App.DownloadNetwork.Mobile);
            //Set whether this download may proceed over a roaming connection.
            request.SetAllowedOverRoaming(false);
            //Set the title of this download, to be displayed in notifications (if enabled).
            //request.SetTitle(title);
            request.SetVisibleInDownloadsUi(false);

            //request.SetNotificationVisibility(DownloadVisibility.Hidden);
            #if DEBUG
            request.SetNotificationVisibility(DownloadVisibility.Visible);
            #else
            request.SetNotificationVisibility(DownloadVisibility.Hidden);
            #endif

            request.SetDestinationInExternalFilesDir(Application.Context, Android.OS.Environment.DirectoryDownloads, fileName);

            //Enqueue a new download and same the referenceId
            var id = downloadManager.Enqueue(request);

            MBDownloadManager.DownloadMonitor(id);
        }
        private static void FinishDownload(Uri uri, bool result)
        {
            Interlocked.Decrement(ref MBDownloadManager.fileUriers);
            Console.WriteLine("DECREMENT " + MBDownloadManager.fileUriers);

            bool   flag2 = false;
            object obj   = MBDownloadManager.requestQueue;

            lock (obj)
            {
                if (result)
                {
                    MBDownloadManager.queuedUpdates.Add(uri);
                    if (MBDownloadManager.queuedUpdates.Count == 1)
                    {
                        flag2 = true;
                    }
                }
                else
                {
                    MBDownloadManager.pendingRequests.Remove(uri);

                    DownloadInfo down = MBDownloadManager.DownloadInfo(uri.AbsoluteUri);

                    if (down != null)
                    {
                        Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Application.Context.GetSystemService("download");
                        downloadManager.Remove(down.Id);
                    }
                }

                if (MBDownloadManager.requestQueue.Count > 0)
                {
                    uri = MBDownloadManager.requestQueue.Pop();
                    if (uri == null)
                    {
                        Console.Error.WriteLine("Dropping request {0} because url is null", uri);
                        MBDownloadManager.pendingRequests.Remove(uri);
                        uri = null;
                    }
                }
                else
                {
                    uri = null;
                }
            }

            if (flag2)
            {
                //FileDownloader.nsDispatcher.BeginInvokeOnMainThread(new NSAction(FileDownloader.NotifyDownloadListeners));
                NotifyDownloadListeners();
            }

            if (uri != null)
            {
                Interlocked.Increment(ref MBDownloadManager.fileUriers);
                MBDownloadManager.StartFileDownload(uri);
            }
        }
        public void OnItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            if (actionMode != null)
            {
                return;
            }

            var item = _Items[e.Position];

            if (item is Pubblicazione)
            {
                Console.WriteLine("click thumb" + e.Position);

                Pubblicazione doc = item as Pubblicazione;

                //se sta aggiornando non apro il documento
                var down = _downloads.Where(d => d.ID == doc.ID).FirstOrDefault();

                if (down != null)
                {
                    DownloadInfo downInfo = MBDownloadManager.DownloadInfo(down.Uri.AbsoluteUri);

                    if (downInfo != null && downInfo.Id != 0 && downInfo.Uri != "")
                    {
                        return;
                    }
                }

                if (DateTime.Now > doc.DataScadenza && !doc.IsPDF && doc.DataScadenza != DateTime.MinValue)
                {
                    var alert = new AlertDialog.Builder(Activity);
                    alert.SetTitle(GetString(Resource.String.gen_error));
                    alert.SetMessage(GetString(Resource.String.pub_expired));
                    alert.SetPositiveButton("Ok", (EventHandler <DialogClickEventArgs>)null);
                    alert.Show().SetDivider();
                    return;
                }

                Intent i = new Intent();
                i.SetClass(Activity, typeof(ViewerScreen));

                //i.SetFlags(ActivityFlags.NewTask);

                i.SetAction(Intent.ActionView);

                i.PutExtra("pubPath", doc.Path);
                Activity.StartActivityForResult(i, 0);
                //Activity.StartActivity(i);
            }
            else if (item is DirectoryInfo)
            {
                Console.WriteLine("click dir" + e.Position);

                DirectoryInfo dir = item as DirectoryInfo;

                _CurrentDir = dir;
                PopulateTable();
            }
        }
        /*public static long CurrentDownloading
         * {
         *  get
         *  {
         *      Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Application.Context.GetSystemService("download");
         *
         *      Android.App.DownloadManager.Query query = new Android.App.DownloadManager.Query();
         *      //query.SetFilterById(_downloadReference);
         *      //query.SetFilterByStatus(DownloadStatus.Pending | DownloadStatus.Running | DownloadStatus.Paused | DownloadStatus.Successful);
         *
         *      ICursor cursor = downloadManager.InvokeQuery(query);
         *
         *      long num = 0;
         *
         *      while (cursor.MoveToNext())
         *      {
         *          num++;
         *      }
         *
         *      return num;
         *  }
         * }*/

        public static void RequestDownload(Uri uri, IDownloadUpdated2 notify)
        {
            if (MBDownloadManager.DefaultManager == null)
            {
                MBDownloadManager.DefaultManager = new MBDownloadManager();
            }

            MBDownloadManager.DefaultManager.AddDownload(uri, notify);
        }
        protected override void PopulateTable()
        {
            if (IsUpdating)
            {
                return;
            }

            //titolo pulsante back
            //if (!DataManager.Get<IPreferencesManager>().Preferences.AlreadyRun || FileSystemManager.DocumentsToImport > 0 || MBDownloadManager.Context == null)
            {
                //_Thread = new Thread(CaricaDocumentiAsync);
                StartUpdating(true);
                _Thread = new Thread(() =>
                {
                    if (Activity.CanAccessExternal())
                    {
                        if (!Directory.Exists(DataManager.Get <ISettingsManager>().Settings.SharedPath))
                        {
                            Directory.CreateDirectory(DataManager.Get <ISettingsManager>().Settings.SharedPath);
                        }

                        FileSystemManager.ImportDocuments();
                    }

                    if (MBDownloadManager.Context == null)
                    {
                        MBDownloadManager.Context = Activity.BaseContext;
                        MBDownloadManager.InstallFinishedMB();
                    }

                    if (Activity != null)
                    {
                        Activity.RunOnUiThread(() =>
                        {
                            LoadDocuments();
                            StopUpdating();
                        });
                    }
                });

                _Thread.Start();
            }

            /*else
             * {
             *  StartUpdating(true);
             *
             *  LoadDocuments();
             *
             *  StopUpdating();
             * }*/

            CheckUpdates();
        }
 private static void StartFileDownload(Uri uri)
 {
     //Interlocked.Increment(ref MBDownloadManager.fileUriers);
     try
     {
         //FileLoader._StartFileUri(uri);
         MBDownloadManager.Download(uri);
     }
     catch (Exception arg)
     {
         Console.Error.WriteLine("CRITICAL: should have never happened {0}", arg);
     }
 }
        public void AddDownload(Uri uri, IDownloadUpdated2 notify)
        {
            object obj2 = MBDownloadManager.requestQueue;

            lock (obj2)
            {
                if (MBDownloadManager.pendingRequests.ContainsKey(uri))
                {
                    return;
                }
            }

            MBDownloadManager.QueueRequest(uri, notify);
            return;
        }
Beispiel #13
0
        public void Initialize()
        {
            if (DownloadUri != null && DownloadUri.AbsolutePath != "")
            {
                DownloadInfo down = MBDownloadManager.DownloadInfo(DownloadUri.AbsoluteUri);

                if (down != null && down.Id != 0 && down.Uri != "")
                {
                    MBDownloadManager.UpdateNotify(DownloadUri, this);

                    this.DownloadStato = DownloadStato.Downloading;
                }
            }
            else
            {
                this.DownloadStato = DownloadStato.NoUpdate;
            }

            SetUIState();
        }
        static void QueueRequest(Uri uri, IDownloadUpdated2 notify)
        {
            if (notify == null)
            {
                throw new ArgumentNullException("notify");
            }
            object obj = MBDownloadManager.requestQueue;

            lock (obj)
            {
                if (MBDownloadManager.pendingRequests.ContainsKey(uri))
                {
                    MBDownloadManager.pendingRequests[uri].Add(notify);
                }
                else
                {
                    List <IDownloadUpdated2> list = new List <IDownloadUpdated2>(4);
                    list.Add(notify);
                    MBDownloadManager.pendingRequests[uri] = list;
                    if (MBDownloadManager.fileUriers >= MaxRequests)
                    {
                        MBDownloadManager.requestQueue.Push(uri);
                    }
                    else
                    {
                        Interlocked.Increment(ref MBDownloadManager.fileUriers);
                        ThreadPool.QueueUserWorkItem(delegate
                        {
                            try
                            {
                                MBDownloadManager.StartFileDownload(uri);
                            }
                            catch (Exception value)
                            {
                                Console.WriteLine(value);
                            }
                        });
                    }
                }
            }
        }
        private void ShowDownloadDialog()
        {
            var dialog = new AlertDialog.Builder(Activity);

            dialog.SetTitle(GetString(Resource.String.down_title));
            dialog.SetMessage(GetString(Resource.String.down_downAll));
            dialog.SetNegativeButton(GetString(Resource.String.gen_cancel), delegate { return; });
            dialog.SetPositiveButton(GetString(Resource.String.gen_download), delegate(object sender, DialogClickEventArgs e)
            {
                if (_Items == null)
                {
                    return;
                }

                foreach (var item in _Items)
                {
                    if (item == null)
                    {
                        continue;
                    }

                    if (item.GetType() == typeof(Download))
                    {
                        Download down = (item as Download);

                        if (down.Stato == DownloadStato.Download || down.Stato == DownloadStato.Update)
                        {
                            MBDownloadManager.RequestDownload(down.Uri, new VoidNotify());
                        }
                    }
                }

                PopulateTable();
            });

            dialog.Create();
            dialog.Show().SetDivider();
        }
        private void ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            var item = _Downloads[e.Position];

            MBDownloadManager.RequestDownload(item.Uri, new VoidNotify());

            item.Stato = DownloadStato.Downloading;

            //_ListView.Adapter = new SearchDownAdapter(this, _Downloads);

            var adapter = new SearchDownAdapter(this, _Downloads);

            adapter.OpenAction += (string p) => {
                Intent i = new Intent();
                i.SetClass(this, typeof(ViewerScreen));

                i.SetAction(Intent.ActionView);

                i.PutExtra("pubPath", p);
                this.StartActivityForResult(i, 0);
            };

            _ListView.Adapter = adapter;
        }
Beispiel #17
0
        public void ConfigureForDownload()
        {
            //pulsante download
            EventHandler onDownClick = (object sender, EventArgs e) =>
            {
                this.Stato = DownloadStato.Downloading;

                //_downloadReference = MBDownloadManager2.Download(_download.Uri, System.IO.Path.GetFileName(_download.Uri.LocalPath), _download.Titolo, this);
                //_downloadReference = MBDownloadManager2.RequestDownload(DownloadUri, System.IO.Path.GetFileName(DownloadUri.LocalPath), this.Title, this);

                MBDownloadManager.RequestDownload(DownloadUri, this);
                SetUIState();

                Log.Info(this.Title, "Inizio download");
            };

            _btnDownload.Click -= onDownClick;
            _btnDownload.Click += onDownClick;

            //pulsante ferma
            EventHandler onStopClick = (object sender, EventArgs e) =>
            {
                //if(_downloadReference != 0)
                {
                    MBDownloadManager.StopDownload(DownloadUri);
                    //_downloadReference = 0;

                    this.Stato = InitStato;
                    SetUIState();
                }
            };

            _btnStop.Click -= onStopClick;
            _btnStop.Click += onStopClick;

            DownloadInfo down = MBDownloadManager.DownloadInfo(DownloadUri.AbsoluteUri);

            if (down != null && down.Id != 0 && down.Uri != "")
            {
                //_downloadReference = down.Id;
                MBDownloadManager.UpdateNotify(DownloadUri, this);

                if (down.Status == DownloadStatus.Running || down.Status == DownloadStatus.Pending)
                {
                    _prgDownload.Progress = 0;
                }
                else if (down.Status == DownloadStatus.Successful)
                {
                    string filePath = new Uri(down.LocalUri).AbsolutePath;
                    if (File.Exists(filePath))
                    {
                        _prgDownload.Progress = 100;
                    }
                }

                this.Stato = DownloadStato.Downloading;
            }
            else if (MBDownloadManager.IsWaiting(DownloadUri))
            {
                _prgDownload.Progress = 0;
                this.Stato            = DownloadStato.Downloading;

                MBDownloadManager.UpdateNotify(DownloadUri, this);
            }

            _btnBuy.SetText(this.Prezzo, TextView.BufferType.Normal);

            SetUIState();
        }
Beispiel #18
0
        private void Initialize()
        {
            //Xamarin.Insights.Initialize(global::InPublishing.XamarinInsights.ApiKey, this);
            AppCenter.Start("cab73ad7-da5e-4ce1-a472-6d48df685f2f", typeof(Analytics), typeof(Crashes));

            //image loader
            var config = new ImageLoaderConfiguration.Builder(ApplicationContext);

            config.ThreadPriority(Java.Lang.Thread.NormPriority - 2);
            config.DenyCacheImageMultipleSizesInMemory();
            config.DiskCacheFileNameGenerator(new Md5FileNameGenerator());
            config.DiskCacheSize(50 * 1024 * 1024); // 50 MiB
            config.TasksProcessingOrder(QueueProcessingType.Lifo);
            config.WriteDebugLogs();                // Remove for release app

            // Initialize ImageLoader with configuration.
            ImageLoader.Instance.Init(config.Build());



            if (!DataManager.AlreadyRegistered <ISettingsManager>())
            {
                DataManager.RegisterReference <ISettingsManager, SettingsManager>();
            }

            DataManager.Get <ISettingsManager>().AndroidGetSettings = p =>
            {
                string content;
                using (StreamReader sr = new StreamReader(Assets.Open("AppSettings.xml")))
                {
                    content = sr.ReadToEnd();
                    return(content);
                }
            };

            DataManager.Get <ISettingsManager>().Load();

            //se è attiva la condivisione setto la cartella nella root
            string sharedPath = "";

            if (DataManager.Get <ISettingsManager>().Settings.ShareDir)
            {
                string appName = ApplicationInfo.LoadLabel(PackageManager);
                sharedPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, appName);
            }
            else
            {
                sharedPath = GetExternalFilesDir("shared").AbsolutePath;
            }

            if (this.CanAccessExternal())
            {
                if (!Directory.Exists(sharedPath))
                {
                    Directory.CreateDirectory(sharedPath);
                }
            }

            //cartella per le pubblicazioni nascosta

/*#if DEBUG
 *                      string docPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.Inpublishing/Publications";
 *                      string notePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/.Inpublishing/Notes";*/
//#else
            string docPath  = GetExternalFilesDir("publications").AbsolutePath;
            string notePath = GetExternalFilesDir("notes").AbsolutePath;

//#endif

            //Se non esiste la creo
            if (!Directory.Exists(docPath))
            {
                Directory.CreateDirectory(docPath);
            }

            DataManager.Get <ISettingsManager>().Settings.Debug      = true;
            DataManager.Get <ISettingsManager>().Settings.DocPath    = docPath;
            DataManager.Get <ISettingsManager>().Settings.SharedPath = sharedPath;
            DataManager.Get <ISettingsManager>().Settings.NotePath   = notePath;

            DataManager.Get <ISettingsManager>().Settings.AndroidContext = this;

            /*WifiManager manager = Application.Context.GetSystemService (Context.WifiService) as WifiManager;
             * WifiInfo info = manager.ConnectionInfo;
             * string address = info.MacAddress;*///uuid

            ISharedPreferences prefs = GetSharedPreferences(this.PackageName, FileCreationMode.Private);

            string deviceId = prefs.GetString("UniqueDeviceIdentifier", "");

            if (deviceId == "")
            {
                //Guid guid = Guid.NewGuid();
                //deviceId = guid.ToString ();
                deviceId = Android.Provider.Settings.Secure.GetString(ApplicationContext.ContentResolver, Android.Provider.Settings.Secure.AndroidId);
                ISharedPreferencesEditor editor = prefs.Edit();
                editor.PutString("UniqueDeviceIdentifier", deviceId);
                editor.Apply();
            }

            DataManager.Get <ISettingsManager>().Settings.DeviceUID  = deviceId;
            DataManager.Get <ISettingsManager>().Settings.DeviceOS   = DocumentOS.Android;
            DataManager.Get <ISettingsManager>().Settings.DeviceType = Utility.IsTablet(this) ? DocumentDevice.Tablet : DocumentDevice.Phone;

            //statistiche
            DataManager.Get <ISettingsManager>().Settings.StatsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            FileSystemManager.AndroidCopyFunc = delegate()
            {
                //se è singola e devo importare i documenti elimino quelli presenti
                if (DataManager.Get <ISettingsManager>().Settings.SingolaApp&& Directory.Exists(DataManager.Get <ISettingsManager>().Settings.DocPath))
                {
                    System.IO.DirectoryInfo di = new DirectoryInfo(DataManager.Get <ISettingsManager>().Settings.DocPath);

                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }
                    foreach (DirectoryInfo dir in di.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                }

                string       dPath = DataManager.Get <ISettingsManager>().Settings.SharedPath;
                AssetManager am    = Resources.Assets;
                var          files = am.List("pub");
                foreach (string file in files)
                {
                    using (Stream source = Assets.Open("pub/" + file))
                    {
                        if (!File.Exists(Path.Combine(dPath, file)))
                        {
                            using (var dest = System.IO.File.Create(Path.Combine(dPath, file)))
                            {
                                source.CopyTo(dest);
                            }
                        }
                    }
                }
            };

            FileSystemManager.AndroidCountFunc = p =>
            {
                AssetManager am = Resources.Assets;
                return(am.List("pub").Length);
            };

            //preferenze
            if (!DataManager.AlreadyRegistered <IPreferencesManager>())
            {
                DataManager.RegisterReference <IPreferencesManager, PreferencesManager>();
            }

            DataManager.Get <ISettingsManager>().Load();

            //ordinamento
            if (!DataManager.Get <IPreferencesManager>().Preferences.AlreadyRun)
            {
                var order = DataManager.Get <ISettingsManager>().Settings.EdicolaOrder;

                DataManager.Get <IPreferencesManager>().Preferences.EdicolaOrder = order;
                DataManager.Get <IPreferencesManager>().Save();
            }

            //notifiche
            if (CheckPlayServices())
            {
                gcm   = GoogleCloudMessaging.GetInstance(this);
                regid = GetRegistrationId(ApplicationContext);
                //regid = "";
                if (regid == "")
                {
                    //ConnectivityManager connectivityManager = (ConnectivityManager) GetSystemService(ConnectivityService);
                    NetworkStatus internetStatus = Reachability.InternetConnectionStatus();
                    if (internetStatus == NetworkStatus.ReachableViaCarrierDataNetwork || internetStatus == NetworkStatus.ReachableViaWiFiNetwork)
                    {
                        RegisterInBackground();
                    }
                }
                else                 //anche se ho già il token registro comunque il dispositivo sull'edicola, saltando la richiesta del token però
                {
                    Thread _Thread = new Thread(() =>
                    {
                        try
                        {
                            SendRegistrationIdToBackend();
                        }
                        catch (Java.IO.IOException ex)
                        {
                            Log.Info(TAG, ex.Message);
                        }
                    });
                    _Thread.Start();
                }
            }
            else
            {
                Log.Info(TAG, "No valid Google Play Services APK found.");
            }

            //se la versione è diversa setto come se fosse la prima volta che l'app parte
            string version = PackageManager.GetPackageInfo(PackageName, 0).VersionCode.ToString();

            if (DataManager.Get <IPreferencesManager>().Preferences.AppVersion == "" || DataManager.Get <IPreferencesManager>().Preferences.AppVersion != version)
            {
                DataManager.Get <IPreferencesManager>().Preferences.DocImported = false;
            }

            DataManager.Get <IPreferencesManager>().Preferences.AppVersion = version;
            DataManager.Get <IPreferencesManager>().Save();

            if (DataManager.Get <ISettingsManager>().Settings.EdicolaEnabled&& !DataManager.Get <ISettingsManager>().Settings.SingolaApp)
            {
                //var intent = new Intent(this, typeof(EdicolaScreen));
                var intent = new Intent(this, typeof(HomeScreen));
                intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop);
                StartActivity(intent);
            }
            else
            {
                var intent = new Intent(this, typeof(DownloaderScreen));
                intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop);
                StartActivity(intent);
            }

            StatisticheManager.SendStats();

            MBDownloadManager.RemoveAll();

            //google analytics
            AnalyticsService.Initialize(this);
            AnalyticsService.SendEvent("App", AnalyticsEventAction.AppStart);

            DataManager.Get <IPreferencesManager>().Preferences.AlreadyRun = true;
            DataManager.Get <IPreferencesManager>().Save();
        }
Beispiel #19
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            this.Window.RequestFeature(WindowFeatures.NoTitle);

            SetContentView(Resource.Layout.DownloadDetails);

            this.SetTitle(_download.Titolo);

            TextView  txtTitolo     = FindViewById <TextView>(Resource.Id.txtTitolo);
            TextView  txtAutore     = FindViewById <TextView>(Resource.Id.txtAutore);
            TextView  txtPubblicato = FindViewById <TextView>(Resource.Id.txtPubblicato);
            TextView  txtScadenza   = FindViewById <TextView>(Resource.Id.txtScadenza);
            TextView  txtDimensione = FindViewById <TextView>(Resource.Id.txtDimensione);
            ImageView imgCover      = FindViewById <ImageView>(Resource.Id.imgCover);
            Button    btnOpen       = FindViewById <Button>(Resource.Id.btnOpen);
            Button    btnDownload   = FindViewById <Button>(Resource.Id.btnDownload);
            Button    btnBuy        = FindViewById <Button>(Resource.Id.btnBuy);
            TextView  txtPrezzo     = FindViewById <TextView>(Resource.Id.txtPrezzo);

            txtTitolo.Text = _download.Titolo;
            txtAutore.Text = _download.Autore.Trim();
            txtPrezzo.Text = "";

            if (_download.Tipo == "pdf")
            {
                imgCover.SetImageResource(Resource.Drawable.pdf_icon);
            }
            else
            {
                string key = _download.ImageKey;
                var    uri = new Uri(DataManager.Get <ISettingsManager>().Settings.DownloadUrl +
                                     "services/edicola_services.php?action=pubCover&zip=" + _download.RelativePath +
                                     "&img=copertina.jpg&key=" + key +
                                     "&app=" + DataManager.Get <ISettingsManager>().Settings.AppId);

                imgCover.Tag = uri.ToString();

                //Koush.UrlImageViewHelper.SetUrlDrawable (imgCover, uri.AbsoluteUri);

                MBImageLoader.DisplayNetworkImage(uri, imgCover, new PointF(360, 360));
            }

            if (_download.DataPubblicazione != DateTime.MinValue)
            {
                txtPubblicato.Text = string.Format(Context.GetString(Resource.String.pub_publishedOn), _download.DataPubblicazione.ToString("dd-MM-yyyy"));
            }
            else
            {
                txtPubblicato.Visibility = ViewStates.Gone;
            }

            if (_download.DataScadenza != DateTime.MinValue)
            {
                txtScadenza.Text = string.Format(Context.GetString(Resource.String.pub_expireOn), _download.DataScadenza.ToString("dd-MM-yyyy"));
            }
            else
            {
                txtScadenza.Visibility = ViewStates.Gone;
            }

            txtDimensione.Text = Utils.FormatBytes(_download.Dimensione);

            if (DataManager.Get <ISettingsManager>().Settings.InAppPurchase&& _download.IapID != "")
            {
                if (_download.IapAcquistato)
                {
                    txtPrezzo.Text = string.Format(Context.GetString(Resource.String.iap_purchaseDate), _download.IapDataAcquisto.ToString("dd-MM-yyyy"));
                }
            }

            //pulsante apri
            btnOpen.SetTextColor(Color.Transparent.FromHex(DataManager.Get <ISettingsManager>().Settings.ButtonColor));
            btnOpen.Text   = Context.GetString(Resource.String.pub_open);
            btnOpen.Click += delegate
            {
                if (OpenAction != null)
                {
                    OpenAction();
                }
            };

            //pulsante download
            btnDownload.SetTextColor(Color.Transparent.FromHex(DataManager.Get <ISettingsManager>().Settings.ButtonColor));
            btnDownload.Text   = Context.GetString(Resource.String.pub_download);
            btnDownload.Click += delegate
            {
                if (DownloadAction != null)
                {
                    DownloadAction();
                }
            };

            //pulsante buy
            btnBuy.SetTextColor(Color.Transparent.FromHex(DataManager.Get <ISettingsManager>().Settings.ButtonColor));

            btnBuy.Text   = _download.IapPrezzo;
            btnBuy.Click += delegate
            {
                if (BuyAction != null)
                {
                    BuyAction();
                }
            };

            GradientDrawable gd = new GradientDrawable();

            gd.SetColor(Color.Transparent.FromHex("ffffff"));
            gd.SetCornerRadius(5);
            gd.SetStroke(1, Color.Transparent.FromHex(DataManager.Get <ISettingsManager>().Settings.ButtonColor));
            btnBuy.Background = gd;

            /*if(FileDownloader.IsWaiting(_download.Uri))
             * {
             *      _download.Stato = DownloadStato.Downloading;
             * }*/
            DownloadInfo down = MBDownloadManager.DownloadInfo(_download.Uri.AbsoluteUri);

            if (down != null && (down.Status == DownloadStatus.Running || down.Status == DownloadStatus.Pending))
            {
                _download.Stato = DownloadStato.Downloading;
            }

            //in base allo stato del download configuro i pulsanti
            switch (_download.Stato)
            {
            case DownloadStato.Download:
                btnDownload.Text   = Context.GetString(Resource.String.pub_download);
                btnOpen.Visibility = ViewStates.Invisible;
                btnBuy.Visibility  = ViewStates.Gone;
                btnBuy.Enabled     = false;
                break;

            case DownloadStato.NoUpdate:
                btnDownload.Visibility = ViewStates.Invisible;
                btnOpen.Visibility     = ViewStates.Visible;
                btnBuy.Visibility      = ViewStates.Gone;
                btnBuy.Enabled         = false;
                break;

            case DownloadStato.Update:
                btnDownload.Text   = Context.GetString(Resource.String.down_update);
                btnOpen.Visibility = ViewStates.Visible;
                btnBuy.Visibility  = ViewStates.Gone;
                btnBuy.Enabled     = false;
                break;

            case DownloadStato.Downloading:
                btnDownload.Text    = Context.GetString(Resource.String.down_wait);
                btnDownload.Enabled = false;
                btnOpen.Visibility  = ViewStates.Invisible;
                btnBuy.Visibility   = ViewStates.Gone;
                btnBuy.Enabled      = false;
                break;

            case DownloadStato.Expired:
                btnDownload.Text    = Context.GetString(Resource.String.pub_expired);
                btnDownload.Enabled = false;
                btnOpen.Visibility  = ViewStates.Invisible;
                btnBuy.Visibility   = ViewStates.Gone;
                btnBuy.Enabled      = false;
                break;

            case DownloadStato.Buy:
                btnDownload.Visibility = ViewStates.Gone;
                btnDownload.Enabled    = false;
                btnOpen.Visibility     = ViewStates.Invisible;
                btnBuy.Visibility      = ViewStates.Visible;
                btnBuy.Enabled         = true;
                break;

            default:
                break;
            }
        }
        private async Task BillProcess(Product prod)
        {
            var result = await _billingHandler.BuyProduct(prod);

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

            if (result.Result == BillingResult.OK)
            {
                if (result.Purchase != null && result.Data != null)
                {
                    string orderID = "";
                    if (result.Purchase.OrderId == null || result.Purchase.OrderId == "")
                    {
                        orderID = result.Purchase.PurchaseToken;
                    }

                    var data = new Dictionary <string, string>();
                    data.Add("packageName", Activity.PackageName);
                    data.Add("orderId", orderID);
                    data.Add("productId", result.Purchase.ProductId);
                    data.Add("developerPayload", result.Purchase.DeveloperPayload);
                    data.Add("purchaseTime", result.Purchase.PurchaseTime.ToString());
                    data.Add("purchaseToken", result.Purchase.PurchaseToken);
                    data.Add("purchaseState", result.Purchase.PurchaseState.ToString());

                    returnData = Notification.CheckRegisterPurchase(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data))));
                }
            }
            else if (result.Result == BillingResult.ItemAlreadyOwned)
            {
                var purch = await _billingHandler.GetPurchases(ItemType.Product);

                foreach (var p in purch)
                {
                    if (p.ProductId == prod.ProductId)
                    {
                        string orderID = "";
                        if (p.OrderId == null || p.OrderId == "")
                        {
                            orderID = p.PurchaseToken;
                        }

                        var data = new Dictionary <string, string>();
                        data.Add("packageName", Activity.PackageName);
                        data.Add("orderId", orderID);
                        data.Add("productId", p.ProductId);
                        data.Add("developerPayload", p.DeveloperPayload);
                        data.Add("purchaseTime", p.PurchaseTime.ToString());
                        data.Add("purchaseToken", p.PurchaseToken);
                        data.Add("purchaseState", p.PurchaseState.ToString());

                        returnData = Notification.CheckRegisterPurchase(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data))));

                        break;
                    }
                }
            }
            else if (result.Result == BillingResult.UserCancelled)
            {
            }
            else
            {
                returnData["success"]   = "false";
                returnData["errorCode"] = result.Result.ToString();
            }

            if (returnData["success"].ToLower() == "true")
            {
                var sub = _Abbonamenti.Where(d => d.IapID == prod.ProductId).FirstOrDefault();

                if (sub != null && sub.IapID != "") //abbonamento
                {
                    this.PopulateTable();
                }
                else //prodotto
                {
                    Activity.RunOnUiThread(() =>
                    {
                        var uri = new Uri(DataManager.Get <ISettingsManager>().Settings.DownloadUrl + "data/accounts/" + returnData["account"] + "/pub/" + returnData["path"]);
                        MBDownloadManager.RequestDownload(uri, new VoidNotify());

                        this.PopulateTable();
                    });
                }
            }
            else
            {
                string msgError = "";
                switch (returnData["errorCode"])
                {
                case "401":
                    msgError = Activity.GetString(Resource.String.iap_authenticationError);
                    break;

                case "403":
                    msgError = Activity.GetString(Resource.String.iap_unauthorizedUser);
                    break;

                case "402":
                    msgError = Activity.GetString(Resource.String.iap_transactionError);
                    break;

                case "503":
                    msgError = Activity.GetString(Resource.String.gen_tryLater);
                    break;

                case "505":
                    msgError = Activity.GetString(Resource.String.gen_tryLater);
                    break;
                }

                Activity.RunOnUiThread(() =>
                {
                    var alert = new AlertDialog.Builder(Activity);
                    alert.SetTitle(GetString(Resource.String.gen_error));

                    if (msgError != "")
                    {
                        alert.SetMessage(msgError + " [" + returnData["errorCode"] + "]");
                    }
                    else
                    {
                        alert.SetMessage("code: " + returnData["errorCode"]);
                    }

                    alert.SetPositiveButton("Ok", (EventHandler <DialogClickEventArgs>)null);
                    alert.Show().SetDivider();
                });
            }
        }
        public void OnItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            if (actionMode != null)
            {
                return;
            }

            var item = _Items[e.Position];

            if (item.GetType() == typeof(Download))
            {
                DownloadDetails dialog = new DownloadDetails(this.Activity, item as Download);

                dialog.OpenAction += () =>
                {
                    Intent i = new Intent();
                    i.SetClass(Activity, typeof(ViewerScreen));

                    i.SetAction(Intent.ActionView);

                    i.PutExtra("pubPath", (item as Download).GetLocalPath());
                    Activity.StartActivityForResult(i, 0);

                    dialog.Dismiss();
                };

                dialog.DownloadAction += () =>
                {
                    //var cell = ;
                    //var cell = _GridView.Adapter.get(e.Position);

                    //FileDownloader.DefaultRequestDownload((item as Download).Uri, new DownloadGridItem(Activity, (item as Download)));

                    Download down = (item as Download);
                    //MBDownloadManager.Download(down.Uri.AbsoluteUri, System.IO.Path.GetFileName(down.Uri.LocalPath), down.Titolo);
                    MBDownloadManager.RequestDownload(down.Uri, new VoidNotify());

                    this.PopulateTable();
                    dialog.Dismiss();
                };

                dialog.BuyAction += () =>
                {
                    Task.Run(
                        async() =>
                    {
                        if (!DownloadManager.IsLogged())
                        {
                            Action action = delegate {
                                PopulateTable();
                            };

                            ActivitiesBringe.SetObject("loginSuccess", action);

                            var logActivity = new Intent(Activity, typeof(LoginActivity));
                            StartActivity(logActivity);
                        }
                        else
                        {
                            Download down    = (item as Download);
                            List <string> id = new List <string>()
                            {
                                down.IapID
                            };
                            IReadOnlyList <Product> billProducts = await _billingHandler.QueryInventory(id, ItemType.Product);

                            if (billProducts != null)
                            {
                                var prod = billProducts.FirstOrDefault();
                                if (prod != null && prod.ProductId != null)
                                {
                                    Task billTask = BillProcess(prod);
                                }
                            }
                        }
                    }
                        );

                    dialog.Dismiss();
                };

                dialog.Show();
            }
            else if (item.GetType() == typeof(DownDir))
            {
                Console.WriteLine("click dir" + e.Position);

                DownDir dir = item as DownDir;

                _CurrentDir = dir.Path;
                PopulateTable();
            }
        }
 public void Download(Uri uri)
 {
     MBDownloadManager.RequestDownload(uri, this);
 }
        private static void DownloadMonitor(long downId)
        {
            //bool downloading = true;
            //Android.App.DownloadManager downloadManager = (Android.App.DownloadManager)Application.Context.GetSystemService("download");

            DownloadInfo down = MBDownloadManager.DownloadInfo(downId);

            while (down != null)
            {
                down = MBDownloadManager.DownloadInfo(downId);

                if (down == null)
                {
                    break;
                }

                Uri uri = new Uri(down.Uri);

                if (!MBDownloadManager.pendingRequests.ContainsKey(uri))
                {
                    break;
                }

                switch (down.Status)
                {
                case DownloadStatus.Running:
                case DownloadStatus.Pending:
                    if (MBDownloadManager.pendingRequests.ContainsKey(uri))
                    {
                        List <IDownloadUpdated2> list = MBDownloadManager.pendingRequests[uri];
                        var perc = (int)((down.ByteDownloaded * 100L) / down.ByteTotal);
                        try
                        {
                            foreach (IDownloadUpdated2 current2 in list)
                            {
                                current2.ProgressChanged(perc);
                            }
                        }
                        catch (Exception value)
                        {
                            Console.WriteLine(value);
                        }
                    }
                    break;

                case DownloadStatus.Successful:
                    try
                    {
                        MBDownloadManager.InstallMbPackage(down.Uri, down.LocalUri);
                        //downloadManager.Remove(down.Id);

                        //downloading = false;

                        //MBDownloadManager.RegisterDownload(uri.ToString(), down.LocalUri);

                        //MBDownloadManager.FinishDownload(uri, true);
                    }
                    catch (Exception value)
                    {
                        Console.WriteLine(value);
                        MBDownloadManager.FinishDownload(uri, false);
                    }
                    break;

                default:
                    break;
                }
            }
        }