Ejemplo n.º 1
0
        public MainViewModel(IDialogs dialogs, IVpnManager?vpnManager = null)
        {
            this.vpnManager = vpnManager;

            this.ToggleConnection = ReactiveCommand.CreateFromTask(async() =>
            {
                if (this.vpnManager == null)
                {
                    await dialogs.Alert("VPN Management is not supported on this platform");
                    return;
                }
                if (this.vpnManager.Status != VpnConnectionState.Disconnected)
                {
                    await this.vpnManager.Disconnect();
                }
                else
                {
                    await this.vpnManager.Connect(new VpnConnectionOptions(this.ServerAddress)
                    {
                        UserName = this.UserName,
                        Password = this.Password
                    });
                }
            });
        }
Ejemplo n.º 2
0
        IReactiveCommand CreateOneReading(IDialogs dialogs, LocationRetrieve retrieve)
        {
            IReactiveCommand command = ReactiveCommand.CreateFromTask(async ct =>
            {
                var observable = retrieve switch
                {
                    LocationRetrieve.Last => this.manager.GetLastReading(),
                    LocationRetrieve.Current => this.manager.GetCurrentPosition(),
                    _ => this.manager.GetLastReadingOrCurrentPosition()
                };
                var reading = await observable.ToTask(ct);

                if (reading == null)
                {
                    await dialogs.Alert("Could not getting GPS coordinates");
                }
                else
                {
                    this.SetValues(reading);
                }
            });

            this.BindBusyCommand(command);
            return(command);
        }
Ejemplo n.º 3
0
        public AdvertiserViewModel(IDialogs dialogs, IBeaconAdvertiser?advertiser = null)
        {
            this.Toggle = ReactiveCommand.CreateFromTask(
                async() =>
            {
                if (advertiser == null)
                {
                    await dialogs.Alert("Beacon advertising not supported on this platform");
                    return;
                }
                if (advertiser.Uuid != null)
                {
                    this.ToggleText = StartText;
                    await advertiser.Stop();
                }
                else
                {
                    var uuid  = Guid.Parse(this.Uuid);
                    var major = UInt16.Parse(this.Major);
                    var minor = UInt16.Parse(this.Minor);
                    Byte.Parse(this.TxPower);

                    await advertiser.Start(uuid, major, minor);
                    this.ToggleText = StopText;
                }
            },
                this.WhenAny(
                    x => x.Uuid,
                    x => x.Major,
                    x => x.Minor,
                    x => x.TxPower,
                    (uuid, major, minor, tx) =>
            {
                if (!Guid.TryParse(uuid.GetValue(), out var _))
                {
                    return(false);
                }

                if (!UInt16.TryParse(major.GetValue(), out var M) || M == 0)
                {
                    return(false);
                }

                if (!UInt16.TryParse(minor.GetValue(), out var m) || m == 0)
                {
                    return(false);
                }

                if (!Byte.TryParse(tx.GetValue(), out var _))
                {
                    return(false);
                }

                return(true);
            }
                    )
                );
        }
Ejemplo n.º 4
0
        public static async Task <bool> AlertAccess(this IDialogs dialogs, AccessState access)
        {
            switch (access)
            {
            case AccessState.Available:
                return(true);

            case AccessState.Restricted:
                await dialogs.Alert("WARNING: Access is restricted");

                return(true);

            default:
                await dialogs.Alert("Invalid Access State: " + access);

                return(false);
            }
        }
Ejemplo n.º 5
0
        public MediaScannerViewModel(IDialogs dialogs, IMediaGalleryScanner?scanner = null)
        {
            this.RunQuery = ReactiveCommand.CreateFromTask(async() =>
            {
                this.IsSearchExpanded = false;
                this.IsBusy           = true;
                if (scanner == null)
                {
                    await dialogs.Alert("Media scanner not supported");
                    return;
                }
                var result = await scanner.RequestAccess();
                if (result != AccessState.Available)
                {
                    await dialogs.Alert("Invalid Status - " + result);
                    return;
                }
                var mediaTypes = MediaTypes.None;
                if (this.IncludeAudio)
                {
                    mediaTypes |= MediaTypes.Audio;
                }
                if (this.IncludeImages)
                {
                    mediaTypes |= MediaTypes.Image;
                }
                if (this.IncludeVideos)
                {
                    mediaTypes |= MediaTypes.Video;
                }

                var list = await scanner.Query(mediaTypes, this.SyncFrom);
                this.List.ReplaceAll(list.Select(x => new CommandItem
                {
                    Text     = $"{x.Type} - {x.FilePath}",
                    ImageUri = x.Type == MediaTypes.Audio ? null : x.FilePath
                }));
                this.IsBusy = false;
            });
            this.BindBusyCommand(this.RunQuery);
        }
Ejemplo n.º 6
0
        public ListViewModel(IDialogs dialogs, IMotionActivityManager?activityManager = null)
        {
            this.activityManager = activityManager;

            this.Load = ReactiveCommand.CreateFromTask(async() =>
            {
                if (this.activityManager == null)
                {
                    await dialogs.Alert("MotionActivity is not supported on this platform");
                    return;
                }

                var result = await this.activityManager.RequestAccess();
                if (result != Shiny.AccessState.Available)
                {
                    await dialogs.Alert("Motion Activity is not available - " + result);
                    return;
                }

                var activities = await this.activityManager.QueryByDate(this.Date);
                this.Events    = activities
                                 .OrderByDescending(x => x.Timestamp)
                                 .Select(x => new CommandItem
                {
                    Text   = $"({x.Confidence}) {x.Types}",
                    Detail = $"{x.Timestamp.LocalDateTime}"
                })
                                 .ToList();

                this.EventCount = this.Events.Count;
            });
            this.BindBusyCommand(this.Load);

            this.WhenAnyValue(x => x.Date)
            .DistinctUntilChanged()
            .Select(_ => Unit.Default)
            .InvokeCommand((ICommand)this.Load)
            .DisposeWith(this.DestroyWith);
        }
Ejemplo n.º 7
0
        public DictationViewModel(ISpeechRecognizer speech, IDialogs dialogs)
        {
            speech
            .WhenListeningStatusChanged()
            .SubOnMainThread(x => this.IsListening = x);


            this.ToggleListen = ReactiveCommand.Create(() =>
            {
                if (this.IsListening)
                {
                    this.Deactivate();
                }
                else
                {
                    if (this.UseContinuous)
                    {
                        speech
                        .ContinuousDictation()
                        .SubOnMainThread(
                            x => this.Text += " " + x,
                            ex => dialogs.Alert(ex.ToString())
                            )
                        .DisposedBy(this.DeactivateWith);
                    }
                    else
                    {
                        speech
                        .ListenUntilPause()
                        .SubOnMainThread(
                            x => this.Text = x,
                            ex => dialogs.Alert(ex.ToString())
                            )
                        .DisposedBy(this.DeactivateWith);
                    }
                }
            });
        }
Ejemplo n.º 8
0
 public BasicViewModel(IAppSettings appSettings,
                       ISettings settings,
                       IDialogs dialogs)
 {
     this.appSettings     = appSettings;
     this.OpenAppSettings = ReactiveCommand.CreateFromTask(async() =>
     {
         var result = await settings.OpenAppSettings();
         if (!result)
         {
             await dialogs.Alert("Could not open appsettings");
         }
     });
 }
Ejemplo n.º 9
0
        public SettingsViewModel(ITripTrackerManager manager, IDialogs dialogs)
        {
            this.IsEnabled     = manager.TrackingType == null;
            this.UseAutomotive = manager.TrackingType == TripTrackingType.Automotive;
            this.UseCycling    = manager.TrackingType == TripTrackingType.Cycling;
            this.UseRunning    = manager.TrackingType == TripTrackingType.Running;
            this.UseWalking    = manager.TrackingType == TripTrackingType.Walking;
            this.UseOnFoot     = manager.TrackingType == TripTrackingType.OnFoot;
            this.UseExercise   = manager.TrackingType == TripTrackingType.Exercise;
            this.UseStationary = manager.TrackingType == TripTrackingType.Stationary;

            this.ToggleMonitoring = ReactiveCommand.CreateFromTask
                                    (
                async() =>
            {
                var access = await manager.RequestAccess();
                if (access != AccessState.Available)
                {
                    await dialogs.Alert("Invalid Access - " + access);
                }
                else
                {
                    if (!this.IsEnabled)
                    {
                        await manager.StopTracking();
                    }
                    else
                    {
                        var type = this.GetTrackingType().Value;
                        await manager.StartTracking(type);
                    }
                    this.IsEnabled = !this.IsEnabled;
                    this.RaisePropertyChanged(nameof(this.MonitoringText));
                }
            },
                this.WhenAny(
                    x => x.UseAutomotive,
                    x => x.UseRunning,
                    x => x.UseWalking,
                    x => x.UseCycling,
                    x => x.UseOnFoot,
                    x => x.UseExercise,
                    x => x.UseStationary,
                    (auto, run, walk, cycle, foot, ex, st) => this.GetTrackingType() != null
                    )
                                    );
        }
Ejemplo n.º 10
0
        public MonitoringViewModel(INavigationService navigator,
                                   IDialogs dialogs,
                                   IBeaconMonitoringManager?beaconManager = null)
        {
            this.Add  = navigator.NavigateCommand("CreateBeacon");
            this.Load = ReactiveCommand.CreateFromTask(async() =>
            {
                if (beaconManager == null)
                {
                    await dialogs.Alert("Beacon monitoring is not supported on this platform");
                    return;
                }
                var regions = await beaconManager.GetMonitoredRegions();

                this.Regions = regions
                               .Select(x => new CommandItem
                {
                    Text           = $"{x.Identifier}",
                    Detail         = $"{x.Uuid}/{x.Major ?? 0}/{x.Minor ?? 0}",
                    PrimaryCommand = ReactiveCommand.CreateFromTask(async() =>
                    {
                        await beaconManager.StopMonitoring(x.Identifier);
                        this.Load.Execute(null);
                    })
                })
                               .ToList();
            });

            this.StopAllMonitoring = ReactiveCommand.CreateFromTask(
                async() =>
            {
                var result = await dialogs.Confirm("Are you sure you wish to stop all monitoring");
                if (result)
                {
                    await beaconManager.StopAllMonitoring();
                    this.Load.Execute(null);
                }
            },
                Observable.Return(beaconManager != null)
                );
        }
Ejemplo n.º 11
0
        public PeripheralViewModel(IDialogs dialogs)
        {
            this.dialogs = dialogs;

            this.SelectCharacteristic = ReactiveCommand.Create <GattCharacteristicViewModel>(x => x.Select());

            this.ConnectionToggle = ReactiveCommand.Create(() =>
            {
                // don't cleanup connection - force user to d/c
                if (this.peripheral.Status == ConnectionState.Connected || this.peripheral.Status == ConnectionState.Connecting)
                {
                    this.peripheral.CancelConnection();
                }
                else
                {
                    this.peripheral.Connect();
                }
            });

            this.PairToDevice = ReactiveCommand.CreateFromTask(async() =>
            {
                var pair = this.peripheral as ICanPairPeripherals;

                if (pair == null)
                {
                    await dialogs.Alert("Pairing is not supported on this platform");
                }
                else if (pair.PairingStatus == PairingState.Paired)
                {
                    await dialogs.Snackbar("Peripheral is already paired");
                }
                else
                {
                    var pin    = await this.dialogs.Input("Use PIN?  Cancel to not use one");
                    var result = await pair.PairingRequest(pin);
                    await dialogs.Snackbar(result ? "Peripheral Paired Successfully" : "Peripheral Pairing Failed");
                    this.RaisePropertyChanged(nameof(this.PairingText));
                }
            });

            this.RequestMtu = ReactiveCommand.CreateFromTask(
                async x =>
            {
                var mtu = this.peripheral as ICanRequestMtu;
                if (mtu == null)
                {
                    await dialogs.Alert("MTU requests are not supported on this platform");
                }
                else
                {
                    var result = await dialogs.Input("MTU Request", "Range 20-512");
                    if (!result.IsEmpty())
                    {
                        var actual = await mtu.RequestMtu(Int32.Parse(result));
                        await dialogs.Snackbar("MTU Changed to " + actual);
                    }
                }
            },
                this.WhenAny(
                    x => x.ConnectText,
                    x => x.GetValue().Equals("Disconnect")
                    )
                );
        }
Ejemplo n.º 12
0
        public CreateViewModel(INotificationManager notificationManager, IDialogs dialogs)
        {
            this.notificationManager = notificationManager;

            this.WhenAnyValue
            (
                x => x.SelectedDate,
                x => x.SelectedTime
            )
            .Select(x => new DateTime(
                        x.Item1.Year,
                        x.Item1.Month,
                        x.Item1.Day,
                        x.Item2.Hours,
                        x.Item2.Minutes,
                        x.Item2.Seconds)
                    )
            .Subscribe(x => this.ScheduledTime = x)
            .DisposeWith(this.DestroyWith);

            //.ToPropertyEx(this, x => x.ScheduledTime);

            this.SelectedDate = DateTime.Now;
            this.SelectedTime = DateTime.Now.TimeOfDay.Add(TimeSpan.FromMinutes(10));

            this.SendNow = ReactiveCommand.CreateFromTask(() => this.BuildAndSend(
                                                              "Test Now",
                                                              "This is a test of the sendnow stuff",
                                                              null
                                                              ));
            this.Send = ReactiveCommand.CreateFromTask(
                async() =>
            {
                await this.BuildAndSend(
                    this.NotificationTitle,
                    this.NotificationMessage,
                    this.ScheduledTime
                    );
                await dialogs.Alert("Notification Sent Successfully");
            },
                this.WhenAny(
                    x => x.NotificationTitle,
                    x => x.NotificationMessage,
                    x => x.ScheduledTime,
                    (title, msg, sch) =>
                    !title.GetValue().IsEmpty() &&
                    !msg.GetValue().IsEmpty() &&
                    sch.GetValue() > DateTime.Now
                    )
                );
            this.PermissionCheck = ReactiveCommand.CreateFromTask(async() =>
            {
                var result = await notificationManager.RequestAccess();
                await dialogs.Snackbar("Permission Check Result: " + result);
            });

            this.StartChat = ReactiveCommand.CreateFromTask(() =>
                                                            notificationManager.Send(
                                                                "Shiny Chat",
                                                                "Hi, What's your name?",
                                                                "ChatName",
                                                                DateTime.Now.AddSeconds(10)
                                                                )
                                                            );
        }
Ejemplo n.º 13
0
        public AdapterViewModel(INavigationService navigator,
                                IDialogs dialogs,
                                IBleManager?bleManager = null)
        {
            this.IsScanning             = bleManager?.IsScanning ?? false;
            this.CanControlAdapterState = bleManager?.CanControlAdapterState() ?? false;

            this.WhenAnyValue(x => x.SelectedPeripheral)
            .Skip(1)
            .Where(x => x != null)
            .Subscribe(async x => await navigator.Navigate("Peripheral", ("Peripheral", x.Peripheral)));

            this.ToggleAdapterState = ReactiveCommand.CreateFromTask(
                async() =>
            {
                if (bleManager == null)
                {
                    await dialogs.Alert("Platform Not Supported");
                }
                else
                {
                    var poweredOn = bleManager.Status == AccessState.Available;
                    if (!bleManager.TrySetAdapterState(!poweredOn))
                    {
                        await dialogs.Alert("Cannot change bluetooth adapter state");
                    }
                }
            }
                );

            this.ScanToggle = ReactiveCommand.CreateFromTask(
                async() =>
            {
                if (bleManager == null)
                {
                    await dialogs.Alert("Platform Not Supported");
                    return;
                }
                if (this.IsScanning)
                {
                    this.Deactivate();
                }
                else
                {
                    this.IsScanning = true;
                    this.Peripherals.Clear();

                    bleManager
                    .Scan()
                    .Buffer(TimeSpan.FromSeconds(1))
                    .SubOnMainThread(
                        results =>
                    {
                        var list = new List <PeripheralItemViewModel>();
                        foreach (var result in results)
                        {
                            var peripheral = this.Peripherals.FirstOrDefault(x => x.Equals(result.Peripheral));
                            if (peripheral == null)
                            {
                                peripheral = list.FirstOrDefault(x => x.Equals(result.Peripheral));
                            }

                            if (peripheral != null)
                            {
                                peripheral.Update(result);
                            }
                            else
                            {
                                peripheral = new PeripheralItemViewModel(result.Peripheral);
                                peripheral.Update(result);
                                list.Add(peripheral);
                            }
                        }
                        if (list.Any())
                        {
                            // XF is not able to deal with an observablelist/addrange properly
                            foreach (var item in list)
                            {
                                this.Peripherals.Add(item);
                            }
                        }
                    },
                        ex => dialogs.Alert(ex.ToString(), "ERROR")
                        )
                    .DisposeWith(this.DeactivateWith);
                }
            }
                );
        }
Ejemplo n.º 14
0
        public GpsViewModel(IGpsManager manager, IDialogs dialogs)
        {
            this.manager    = manager;
            this.IsUpdating = this.manager.IsListening;

            this.WhenAnyValue(x => x.UseBackground)
            .Subscribe(x => this.Access = this.manager.GetCurrentStatus(
                           new GpsRequest {
                UseBackground = this.UseBackground
            }).ToString()
                       );

            this.WhenAnyValue(x => x.IsUpdating)
            .Select(x => x ? "Stop Listening" : "Start Updating")
            .ToPropertyEx(this, x => x.ListenerText);

            this.GetCurrentPosition = ReactiveCommand.CreateFromTask(async _ =>
            {
                var result = await dialogs.RequestAccess(() => this.manager.RequestAccess(new GpsRequest()));
                if (!result)
                {
                    return;
                }

                var reading = await this.manager.GetLastReading();
                if (reading == null)
                {
                    await dialogs.Alert("Could not getting GPS coordinates");
                }
                else
                {
                    this.SetValues(reading);
                }
            });
            this.BindBusyCommand(this.GetCurrentPosition);

            ReactiveCommand.Create(() => dialogs.ActionSheet(
                                       "Select Priority",
                                       false,
                                       ("Highest", () => this.Priority = GpsPriority.Highest),
                                       ("Normal", () => this.Priority = GpsPriority.Normal),
                                       ("Low", () => this.Priority = GpsPriority.Low)
                                       ));

            this.ToggleUpdates = ReactiveCommand.CreateFromTask(
                async() =>
            {
                if (this.manager.IsListening)
                {
                    await this.manager.StopListener();
                    this.gpsListener?.Dispose();
                }
                else
                {
                    var result = await dialogs.RequestAccess(() => this.manager.RequestAccess(new GpsRequest {
                        UseBackground = this.UseBackground
                    }));
                    if (!result)
                    {
                        await dialogs.Alert("Insufficient permissions");
                        return;
                    }

                    var request = new GpsRequest
                    {
                        UseBackground = this.UseBackground,
                        Priority      = this.Priority,
                    };
                    if (IsInterval(this.DesiredInterval))
                    {
                        request.Interval = ToInterval(this.DesiredInterval);
                    }

                    if (IsInterval(this.ThrottledInterval))
                    {
                        request.ThrottledInterval = ToInterval(this.ThrottledInterval);
                    }

                    await this.manager.StartListener(request);
                }
                this.IsUpdating = this.manager.IsListening;
            },
                this.WhenAny(
                    x => x.IsUpdating,
                    x => x.DesiredInterval,
                    x => x.ThrottledInterval,
                    (u, i, t) =>
            {
                if (u.GetValue())
                {
                    return(true);
                }

                var isdesired   = IsInterval(i.GetValue());
                var isthrottled = IsInterval(t.GetValue());

                if (isdesired && isthrottled)
                {
                    var desired  = ToInterval(i.GetValue());
                    var throttle = ToInterval(t.GetValue());
                    if (throttle.TotalSeconds >= desired.TotalSeconds)
                    {
                        return(false);
                    }
                }
                return(true);
            }
                    )
                );

            this.UseRealtime = ReactiveCommand.Create(() =>
            {
                var rt = GpsRequest.Realtime(false);
                this.ThrottledInterval = String.Empty;
                this.DesiredInterval   = rt.Interval.TotalSeconds.ToString();
                this.Priority          = rt.Priority;
            });

            this.RequestAccess = ReactiveCommand.CreateFromTask(async() =>
            {
                var access = await this.manager.RequestAccess(new GpsRequest {
                    UseBackground = this.UseBackground
                });
                this.Access = access.ToString();
            });
            this.BindBusyCommand(this.RequestAccess);
        }
Ejemplo n.º 15
0
        public AdapterViewModel(IBleManager central,
                                INavigationService navigator,
                                IDialogs dialogs)
        {
            this.CanControlAdapterState = central.CanControlAdapterState();

            this.WhenAnyValue(x => x.SelectedPeripheral)
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(x => navigator.Navigate("Peripheral", ("Peripheral", x.Peripheral)));

            this.ToggleAdapterState = ReactiveCommand.CreateFromTask(
                async() =>
            {
                var poweredOn = central.Status == AccessState.Available;
                if (!central.TrySetAdapterState(!poweredOn))
                {
                    await dialogs.Alert("Cannot change bluetooth adapter state");
                }
            }
                );

            this.ScanToggle = ReactiveCommand.Create(
                () =>
            {
                if (this.IsScanning)
                {
                    this.IsScanning = false;
                    this.scan?.Dispose();
                }
                else
                {
                    this.Peripherals.Clear();

                    this.scan = central
                                .Scan()
                                .Buffer(TimeSpan.FromSeconds(1))
                                .Synchronize()
                                .SubOnMainThread(
                        results =>
                    {
                        var list = new List <PeripheralItemViewModel>();
                        foreach (var result in results)
                        {
                            var peripheral = this.Peripherals.FirstOrDefault(x => x.Equals(result.Peripheral));
                            if (peripheral == null)
                            {
                                peripheral = list.FirstOrDefault(x => x.Equals(result.Peripheral));
                            }

                            if (peripheral != null)
                            {
                                peripheral.Update(result);
                            }
                            else
                            {
                                peripheral = new PeripheralItemViewModel(result.Peripheral);
                                peripheral.Update(result);
                                list.Add(peripheral);
                            }
                        }
                        if (list.Any())
                        {
                            this.Peripherals.AddRange(list);
                        }
                    },
                        ex => dialogs.Alert(ex.ToString(), "ERROR")
                        )
                                .DisposeWith(this.DeactivateWith);

                    this.IsScanning = true;
                }
            }
                );
        }
Ejemplo n.º 16
0
        public ListViewModel(IJobManager jobManager,
                             INavigationService navigator,
                             IDialogs dialogs)
        {
            this.jobManager = jobManager;
            this.dialogs    = dialogs;

            this.Create = navigator.NavigateCommand("CreateJob");

            this.LoadJobs = ReactiveCommand.CreateFromTask(async() =>
            {
                var jobs = await jobManager.GetJobs();

                this.Jobs = jobs
                            .Select(x => new CommandItem
                {
                    Text             = x.Identifier,
                    Detail           = x.LastRunUtc?.ToLocalTime().ToString("G") ?? "Never Run",
                    PrimaryCommand   = ReactiveCommand.CreateFromTask(() => jobManager.Run(x.Identifier)),
                    SecondaryCommand = ReactiveCommand.CreateFromTask(async() =>
                    {
                        await jobManager.Cancel(x.Identifier);
                        this.LoadJobs.Execute(null);
                    })
                })
                            .ToList();
            });
            this.BindBusyCommand(this.LoadJobs);

            this.RunAllJobs = ReactiveCommand.CreateFromTask(async() =>
            {
                if (!await this.AssertJobs())
                {
                    return;
                }

                if (this.jobManager.IsRunning)
                {
                    await dialogs.Alert("Job Manager is already running");
                }
                else
                {
                    await this.jobManager.RunAll();
                    await dialogs.Snackbar("Job Batch Started");
                }
            });

            this.CancelAllJobs = ReactiveCommand.CreateFromTask(async _ =>
            {
                if (!await this.AssertJobs())
                {
                    return;
                }

                var confirm = await dialogs.Confirm("Are you sure you wish to cancel all jobs?");
                if (confirm)
                {
                    await this.jobManager.CancelAll();
                    this.LoadJobs.Execute(null);
                }
            });
        }
Ejemplo n.º 17
0
        public CreateViewModel(INavigationService navigationService,
                               IHttpTransferManager httpTransfers,
                               IDialogs dialogs,
                               IPlatform platform,
                               AppSettings appSettings)
        {
            this.platform = platform;
            this.Url      = appSettings.LastTransferUrl;

            this.WhenAnyValue(x => x.IsUpload)
            .Subscribe(upload =>
            {
                if (!upload && this.FileName.IsEmpty())
                {
                    this.FileName = Guid.NewGuid().ToString();
                }

                this.Title = upload ? "New Upload" : "New Download";
            });

            this.ManageUploads = navigationService.NavigateCommand("ManageUploads");

            this.ResetUrl = ReactiveCommand.Create(() =>
            {
                appSettings.LastTransferUrl = null;
                this.Url = appSettings.LastTransferUrl;
            });

            this.SelectUpload = ReactiveCommand.CreateFromTask(async() =>
            {
                var files = platform.AppData.GetFiles("upload.*", SearchOption.TopDirectoryOnly);
                if (!files.Any())
                {
                    await dialogs.Alert("There are not files to upload.  Use 'Manage Uploads' below to create them");
                }
                else
                {
                    var cfg = new Dictionary <string, Action>();
                    foreach (var file in files)
                    {
                        cfg.Add(file.Name, () => this.FileName = file.Name);
                    }

                    await dialogs.ActionSheet("Actions", cfg);
                }
            });
            this.Save = ReactiveCommand.CreateFromTask(
                async() =>
            {
                var path    = Path.Combine(this.platform.AppData.FullName, this.FileName);
                var request = new HttpTransferRequest(this.Url, path, this.IsUpload)
                {
                    UseMeteredConnection = this.UseMeteredConnection
                };
                await httpTransfers.Enqueue(request);
                appSettings.LastTransferUrl = this.Url;
                await navigationService.GoBackAsync();
            },
                this.WhenAny
                (
                    x => x.IsUpload,
                    x => x.Url,
                    x => x.FileName,
                    (up, url, fn) =>
            {
                this.ErrorMessage = String.Empty;
                if (!Uri.TryCreate(url.GetValue(), UriKind.Absolute, out _))
                {
                    this.ErrorMessage = "Invalid URL";
                }

                else if (up.GetValue() && fn.GetValue().IsEmpty())
                {
                    this.ErrorMessage = "You must select or enter a filename";
                }

                return(this.ErrorMessage.IsEmpty());
            }
                )
                );
        }
Ejemplo n.º 18
0
        public GpsViewModel(IGpsManager manager, IDialogs dialogs)
        {
            this.manager = manager;

            var l = this.manager.CurrentListener;

            this.IsUpdating            = l != null;
            this.UseBackground         = l?.UseBackground ?? true;
            this.Priority              = l?.Priority ?? GpsPriority.Normal;
            this.DesiredInterval       = l?.Interval.TotalSeconds.ToString() ?? String.Empty;
            this.ThrottledInterval     = l?.ThrottledInterval?.TotalSeconds.ToString() ?? String.Empty;
            this.MinimumDistanceMeters = l?.MinimumDistance?.TotalMeters.ToString() ?? String.Empty;

            this.NotificationTitle   = manager.Title;
            this.NotificationMessage = manager.Message;

            this.WhenAnyValue(x => x.IsUpdating)
            .Select(x => x ? "Stop Listening" : "Start Updating")
            .ToPropertyEx(this, x => x.ListenerText);

            this.WhenAnyValue(x => x.NotificationTitle)
            .Skip(1)
            .Subscribe(x => this.manager.Title = x)
            .DisposedBy(this.DestroyWith);

            this.WhenAnyValue(x => x.NotificationMessage)
            .Skip(1)
            .Subscribe(x => this.manager.Message = x)
            .DisposedBy(this.DestroyWith);

            this.GetCurrentPosition = this.CreateOneReading(dialogs, LocationRetrieve.Current);
            this.GetLastReading     = this.CreateOneReading(dialogs, LocationRetrieve.Last);
            this.GetLastOrCurrent   = this.CreateOneReading(dialogs, LocationRetrieve.LastOrCurrent);

            ReactiveCommand.Create(() => dialogs.ActionSheet(
                                       "Select Priority",
                                       false,
                                       ("Highest", () => this.Priority = GpsPriority.Highest),
                                       ("Normal", () => this.Priority = GpsPriority.Normal),
                                       ("Low", () => this.Priority = GpsPriority.Low)
                                       ));

            this.ToggleUpdates = ReactiveCommand.CreateFromTask(
                async() =>
            {
                if (this.manager.CurrentListener != null)
                {
                    await this.manager.StopListener();
                    this.gpsListener?.Dispose();
                }
                else
                {
                    var result = await dialogs.RequestAccess(async() =>
                    {
                        var access = await this.manager.RequestAccess(new GpsRequest
                        {
                            UseBackground = this.UseBackground
                        });
                        this.Access = access.ToString();
                        return(access);
                    });
                    if (!result)
                    {
                        await dialogs.Alert("Insufficient permissions");
                        return;
                    }

                    var request = new GpsRequest
                    {
                        UseBackground = this.UseBackground,
                        Priority      = this.Priority,
                    };
                    if (IsNumeric(this.DesiredInterval))
                    {
                        request.Interval = ToInterval(this.DesiredInterval);
                    }

                    if (IsNumeric(this.ThrottledInterval))
                    {
                        request.ThrottledInterval = ToInterval(this.ThrottledInterval);
                    }

                    if (IsNumeric(this.MinimumDistanceMeters))
                    {
                        request.MinimumDistance = Distance.FromMeters(Int32.Parse(this.MinimumDistanceMeters));
                    }

                    await this.manager.StartListener(request);
                }
                this.IsUpdating = this.manager.CurrentListener != null;
            },
                this.WhenAny(
                    x => x.IsUpdating,
                    x => x.DesiredInterval,
                    x => x.ThrottledInterval,
                    x => x.MinimumDistanceMeters,
                    (u, i, t, d) =>
            {
                if (u.GetValue())
                {
                    return(true);
                }

                var isdesired   = IsNumeric(i.GetValue());
                var isthrottled = IsNumeric(t.GetValue());
                var ismindist   = IsNumeric(d.GetValue());

                if (isdesired && isthrottled)
                {
                    var desired  = ToInterval(i.GetValue());
                    var throttle = ToInterval(t.GetValue());
                    if (throttle.TotalSeconds >= desired.TotalSeconds)
                    {
                        return(false);
                    }
                }
                return(true);
            }
                    )
                );

            this.UseRealtime = ReactiveCommand.Create(() =>
            {
                var rt = GpsRequest.Realtime(false);
                this.ThrottledInterval = String.Empty;
                this.DesiredInterval   = rt.Interval.TotalSeconds.ToString();
                this.Priority          = rt.Priority;
            });

            this.RequestAccess = ReactiveCommand.CreateFromTask(async() =>
            {
                var access = await this.manager.RequestAccess(new GpsRequest {
                    UseBackground = this.UseBackground
                });
                this.Access = access.ToString();
            });
            this.BindBusyCommand(this.RequestAccess);
        }