public override async Task <string> UpdateLocationQuery(WeatherData.Weather weather)
        {
            string query = string.Empty;
            var    coord = new WeatherUtils.Coordinate(double.Parse(weather.location.latitude), double.Parse(weather.location.longitude));
            var    qview = await GetLocation(coord);

            if (String.IsNullOrEmpty(qview.LocationQuery))
            {
                query = string.Format("lat={0}&lon={1}", coord.Latitude, coord.Longitude);
            }
            else
            {
                query = qview.LocationQuery;
            }

            return(query);
        }
Beispiel #2
0
        private async void LocationSearchFragment_clickListener(object sender, RecyclerClickEventArgs e)
        {
            // Get selected query view
            LocationQuery          v        = (LocationQuery)e.View;
            LocationQueryViewModel query_vm = null;

            try
            {
                if (!String.IsNullOrEmpty(mAdapter.Dataset[e.Position].LocationQuery))
                {
                    query_vm = mAdapter.Dataset[e.Position];
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                query_vm = null;
            }
            finally
            {
                if (query_vm == null)
                {
                    query_vm = new LocationQueryViewModel();
                }
            }

            if (String.IsNullOrWhiteSpace(query_vm.LocationQuery))
            {
                // Stop since there is no valid query
                return;
            }

            if (Settings.UsePersonalKey && String.IsNullOrWhiteSpace(Settings.API_KEY) && wm.KeyRequired)
            {
                Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_invalidkey), ToastLength.Short).Show();
                return;
            }

            // Cancel pending searches
            CtsCancel();
            var ctsToken = cts.Token;

            ShowLoading(true);

            if (ctsToken.IsCancellationRequested)
            {
                ShowLoading(false);
                return;
            }

            // Get Weather Data
            var location = new WeatherData.LocationData(query_vm);

            if (!location.IsValid())
            {
                Toast.MakeText(App.Context, App.Context.GetString(Resource.String.werror_noweather), ToastLength.Short).Show();
                ShowLoading(false);
                return;
            }
            WeatherData.Weather weather = await Settings.GetWeatherData(location.query);

            if (weather == null)
            {
                try
                {
                    weather = await wm.GetWeather(location);
                }
                catch (WeatherException wEx)
                {
                    weather = null;
                    Toast.MakeText(App.Context, wEx.Message, ToastLength.Short).Show();
                }
            }

            if (weather == null)
            {
                ShowLoading(false);
                return;
            }

            // We got our data so disable controls just in case
            mAdapter.Dataset.Clear();
            mAdapter.NotifyDataSetChanged();
            mRecyclerView.Enabled = false;

            // Save weather data
            await Settings.DeleteLocations();

            await Settings.AddLocation(location);

            if (wm.SupportsAlerts && weather.weather_alerts != null)
            {
                await Settings.SaveWeatherAlerts(location, weather.weather_alerts);
            }
            await Settings.SaveWeatherData(weather);

            // If we're using search
            // make sure gps feature is off
            Settings.FollowGPS     = false;
            Settings.WeatherLoaded = true;

            // Send data for wearables
            mActivity.StartService(new Intent(mActivity, typeof(WearableDataListenerService))
                                   .SetAction(WearableDataListenerService.ACTION_SENDSETTINGSUPDATE));
            mActivity.StartService(new Intent(mActivity, typeof(WearableDataListenerService))
                                   .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));
            mActivity.StartService(new Intent(mActivity, typeof(WearableDataListenerService))
                                   .SetAction(WearableDataListenerService.ACTION_SENDWEATHERUPDATE));

            if (mAppWidgetId == AppWidgetManager.InvalidAppwidgetId)
            {
                // Start WeatherNow Activity with weather data
                Intent intent = new Intent(mActivity, typeof(MainActivity));
                intent.PutExtra("data", location.ToJson());

                mActivity.StartActivity(intent);
                mActivity.FinishAffinity();
            }
            else
            {
                // Create return intent
                Intent resultValue = new Intent();
                resultValue.PutExtra(AppWidgetManager.ExtraAppwidgetId, mAppWidgetId);
                resultValue.PutExtra("data", location.ToJson());
                mActivity.SetResult(Android.App.Result.Ok, resultValue);
                mActivity.Finish();
            }
        }
        public override async Task <WeatherData.Weather> GetWeather(string location_query)
        {
            WeatherData.Weather weather = null;

            string currentAPI  = null;
            Uri    currentURL  = null;
            string forecastAPI = null;
            Uri    forecastURL = null;
            string query       = null;

#if WINDOWS_UWP
            var userlang = Windows.System.UserProfile.GlobalizationPreferences.Languages.First();
            var culture  = new System.Globalization.CultureInfo(userlang);
#else
            var culture = System.Globalization.CultureInfo.CurrentCulture;
#endif
            string locale = LocaleToLangCode(culture.TwoLetterISOLanguageName, culture.Name);

            if (int.TryParse(location_query, out int id))
            {
                query = string.Format("id={0}", id);
            }
            else
            {
                query = location_query;
            }

            string key = Settings.UsePersonalKey ? Settings.API_KEY : GetAPIKey();

            currentAPI  = "https://api.openweathermap.org/data/2.5/weather?{0}&appid={1}&lang=" + locale;
            currentURL  = new Uri(string.Format(currentAPI, query, key));
            forecastAPI = "https://api.openweathermap.org/data/2.5/forecast?{0}&appid={1}&lang=" + locale;
            forecastURL = new Uri(string.Format(forecastAPI, query, key));

            HttpClient       webClient = new HttpClient();
            WeatherException wEx       = null;

            try
            {
                // Get response
                HttpResponseMessage currentResponse = await webClient.GetAsync(currentURL);

                currentResponse.EnsureSuccessStatusCode();
                HttpResponseMessage forecastResponse = await webClient.GetAsync(forecastURL);

                forecastResponse.EnsureSuccessStatusCode();

                Stream currentStream  = null;
                Stream forecastStream = null;
#if WINDOWS_UWP
                currentStream  = WindowsRuntimeStreamExtensions.AsStreamForRead(await currentResponse.Content.ReadAsInputStreamAsync());
                forecastStream = WindowsRuntimeStreamExtensions.AsStreamForRead(await forecastResponse.Content.ReadAsInputStreamAsync());
#elif __ANDROID__
                currentStream = await currentResponse.Content.ReadAsStreamAsync();

                forecastStream = await forecastResponse.Content.ReadAsStreamAsync();
#endif
                // Reset exception
                wEx = null;

                // Load weather
                CurrentRootobject  currRoot = null;
                ForecastRootobject foreRoot = null;
                await Task.Run(() =>
                {
                    currRoot = JSONParser.Deserializer <CurrentRootobject>(currentStream);
                });

                await Task.Run(() =>
                {
                    foreRoot = JSONParser.Deserializer <ForecastRootobject>(forecastStream);
                });

                // End Streams
                currentStream.Dispose();
                forecastStream.Dispose();

                weather = new WeatherData.Weather(currRoot, foreRoot);
            }
            catch (Exception ex)
            {
                weather = null;
#if WINDOWS_UWP
                if (WebError.GetStatus(ex.HResult) > WebErrorStatus.Unknown)
#elif __ANDROID__
                if (ex is WebException || ex is HttpRequestException)
#endif
                {
                    wEx = new WeatherException(WeatherUtils.ErrorStatus.NetworkError);
                }

                Logger.WriteLine(LoggerLevel.Error, ex, "OpenWeatherMapProvider: error getting weather data");
            }

            // End Stream
            webClient.Dispose();

            if (weather == null || !weather.IsValid())
            {
                wEx = new WeatherException(WeatherUtils.ErrorStatus.NoWeather);
            }
            else if (weather != null)
            {
                if (SupportsWeatherLocale)
                {
                    weather.locale = locale;
                }

                weather.query = location_query;
            }

            if (wEx != null)
            {
                throw wEx;
            }

            return(weather);
        }