summaryrefslogtreecommitdiffstats
path: root/app/src/main/java/org/lineageos/yahooweatherprovider/YahooWeatherProviderService.java
blob: 11e46f8bbfe17caccd741f4160c4f20e5ddc0761 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/**
 * Copyright (C) 2016 The CyanogenMod Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.lineageos.yahooweatherprovider;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import org.lineageos.yahooweatherprovider.yahoo.WeakReferenceHandler;
import org.lineageos.yahooweatherprovider.yahoo.YahooWeatherRequestCallback;
import org.lineageos.yahooweatherprovider.yahoo.YahooWeatherResponseListener;
import org.lineageos.yahooweatherprovider.yahoo.YahooWeatherServiceManager;
import org.lineageos.yahooweatherprovider.yahoo.response.Atmosphere;
import org.lineageos.yahooweatherprovider.yahoo.response.Channel;
import org.lineageos.yahooweatherprovider.yahoo.response.Condition;
import org.lineageos.yahooweatherprovider.yahoo.response.Forecast;
import org.lineageos.yahooweatherprovider.yahoo.response.Location;
import org.lineageos.yahooweatherprovider.yahoo.response.Place;
import org.lineageos.yahooweatherprovider.yahoo.response.Query;
import org.lineageos.yahooweatherprovider.yahoo.response.Results;
import org.lineageos.yahooweatherprovider.yahoo.response.Wind;
import org.lineageos.yahooweatherprovider.yahoo.response.YQLResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import cyanogenmod.providers.WeatherContract;
import cyanogenmod.weather.RequestInfo;
import cyanogenmod.weather.WeatherInfo;
import cyanogenmod.weather.WeatherLocation;
import cyanogenmod.weatherservice.ServiceRequest;
import cyanogenmod.weatherservice.ServiceRequestResult;
import cyanogenmod.weatherservice.WeatherProviderService;
import retrofit2.Call;

public class YahooWeatherProviderService extends WeatherProviderService
        implements YahooWeatherResponseListener {

    private static final String TAG = YahooWeatherProviderService.class.getSimpleName();
    private static final int SERVICE_REQUEST_CANCELLED = -1;
    private static final int SERVICE_REQUEST_SUBMITTED = 0;

    //TODO, add a setting for this
    private static final int MAX_FORECAST_DAYS = 5;

    @Inject
    public YahooWeatherServiceManager mYahooWeatherServiceManager;

    @Override
    public void onCreate() {
        super.onCreate();
        YahooCMWeatherApplication.get(this).inject(this);
    }

    @Override
    protected void onRequestSubmitted(ServiceRequest serviceRequest) {
        Log.d(TAG, "Received service request: " + serviceRequest.toString());
        Message request = mHandler.obtainMessage(SERVICE_REQUEST_SUBMITTED, serviceRequest);
        request.sendToTarget();
    }

    @Override
    protected void onRequestCancelled(ServiceRequest serviceRequest) {
        Log.d(TAG, "Received service request cancelled: " + serviceRequest.toString());
        Message request = mHandler.obtainMessage(SERVICE_REQUEST_CANCELLED, serviceRequest);
        request.sendToTarget();
    }

    private final NonLeakyMessageHandler mHandler = new NonLeakyMessageHandler(this);

    private static class NonLeakyMessageHandler
            extends WeakReferenceHandler<YahooWeatherProviderService> {
        public NonLeakyMessageHandler(YahooWeatherProviderService reference) {
            super(reference);
        }

        @Override
        protected void handleMessage(YahooWeatherProviderService reference,
                                     Message inputMessage) {
            ServiceRequest serviceRequest = (ServiceRequest)inputMessage.obj;
            switch (inputMessage.what) {
                case SERVICE_REQUEST_SUBMITTED:
                    RequestInfo requestInfo = serviceRequest.getRequestInfo();
                    switch (requestInfo.getRequestType()) {
                        case RequestInfo.TYPE_WEATHER_BY_WEATHER_LOCATION_REQ:
                        case RequestInfo.TYPE_WEATHER_BY_GEO_LOCATION_REQ:
                            reference.handleWeatherRequest(serviceRequest);
                            break;
                        case RequestInfo.TYPE_LOOKUP_CITY_NAME_REQ:
                            reference.handleLookupRequest(serviceRequest);
                            break;
                        default:
                            //Don't support anything else, fail.
                            serviceRequest.fail();
                            break;
                    }
                    break;
                case SERVICE_REQUEST_CANCELLED:
                    //TODO; Implement
                    break;
                default:
                    //Don't support anything else, fail.
                    if (serviceRequest != null) {
                        serviceRequest.fail();
                    }
            }
        }
    }

    private void handleLookupRequest(ServiceRequest serviceRequest) {
        final RequestInfo requestInfo = serviceRequest.getRequestInfo();

        String cityName = requestInfo.getCityName();

        if (TextUtils.isEmpty(cityName)) {
            Log.d(TAG, "Null citname return");
            serviceRequest.fail();
            return;
        }

        Call<YQLResponse> wundergroundCall = mYahooWeatherServiceManager.lookupCity(cityName);
        wundergroundCall.enqueue(new YahooWeatherRequestCallback(serviceRequest, this));
    }


    private void handleWeatherRequest(final ServiceRequest serviceRequest) {
        final RequestInfo requestInfo = serviceRequest.getRequestInfo();
        Log.d(TAG, "Received weather request info: " + requestInfo.toString());

        if (requestInfo.getRequestType() == RequestInfo.TYPE_WEATHER_BY_GEO_LOCATION_REQ) {
            android.location.Location location = requestInfo.getLocation();
            if (location == null) {
                LocationManager locationManager = (LocationManager)
                        getSystemService(Context.LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_HIGH);
                location = locationManager.getLastKnownLocation(locationManager.getBestProvider(
                        criteria, false));
            }
            handleRequestByGeoLocation(location, serviceRequest);
        } else {
            WeatherLocation weatherLocation = requestInfo.getWeatherLocation();
            handleRequestByWeatherLocation(weatherLocation, serviceRequest);
        }
    }

    /**
     * Enqueue request by geolocation (lat/long)
     */
    private void handleRequestByGeoLocation(android.location.Location location,
            final ServiceRequest serviceRequest) {
        Geocoder gcd = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = gcd.getFromLocation(location.getLatitude(),
                    location.getLongitude(), 1);
            Address address = addresses.get(0);
            Call<YQLResponse> wundergroundCall =
                    mYahooWeatherServiceManager.query(address.getCountryName(),
                            address.getLocality());
            wundergroundCall.enqueue(new YahooWeatherRequestCallback(serviceRequest, this));
        } catch (IOException e) {
            Log.d(TAG, "Failed to get addresses");
            serviceRequest.fail();
        }
    }

    /**
     * Enqueue request by weatherlocation
     */
    private void handleRequestByWeatherLocation(WeatherLocation weatherLocation,
            final ServiceRequest serviceRequest) {

        Call<YQLResponse> wundergroundCall = null;
        if (weatherLocation.getCity() != null) {
            wundergroundCall =
                    mYahooWeatherServiceManager.query(weatherLocation.getState(),
                            weatherLocation.getCity());
        }
        //TODO: Add postal code support
        //else if (weatherLocation.getPostalCode() != null) {
        //  wundergroundCall =
        //            mYahooWeatherServiceManager.query(weatherLocation.getPostalCode());
        //}
        else {
            Log.e(TAG, "Unable to handle service request");
            serviceRequest.fail();
            return;
        }

        wundergroundCall.enqueue(new YahooWeatherRequestCallback(serviceRequest, this));
    }

    @Override
    public void processYahooWeatherResponse(YQLResponse yqlResponse, ServiceRequest serviceRequest) {
        switch (serviceRequest.getRequestInfo().getRequestType()) {
            case RequestInfo.TYPE_WEATHER_BY_WEATHER_LOCATION_REQ:
            case RequestInfo.TYPE_WEATHER_BY_GEO_LOCATION_REQ:
                processWeatherRequest(yqlResponse, serviceRequest);
                break;
            case RequestInfo.TYPE_LOOKUP_CITY_NAME_REQ:
                processCityLookupRequest(yqlResponse, serviceRequest);
                break;
            default:
                //Don't support anything else, fail.
                serviceRequest.fail();
        }
    }

    private void processWeatherRequest(YQLResponse yqlResponse, ServiceRequest serviceRequest) {
        final Query queryResponse = yqlResponse.getQuery();
        final Results results =  queryResponse.getResults();

        if (results == null) {
            Log.d(TAG, "Null query results, return");
            serviceRequest.fail();
            return;
        }
        final Channel channel = results.getChannel();
        final Location location = channel.getLocation();
        final Condition condition = channel.getItem().getCondition();
        final Atmosphere atmosphere = channel.getAtmosphere();
        final Wind wind = channel.getWind();
        final Forecast[] forecasts = channel.getItem().getForecast();

        final WeatherInfo.Builder weatherInfoBuilder = new WeatherInfo.Builder(location.getCity(),
                Double.parseDouble(condition.getTemp()),
                WeatherContract.WeatherColumns.TempUnit.FAHRENHEIT);

        // Set current weather condition code
        weatherInfoBuilder.setWeatherCondition(
                ConverterUtils.offset(Integer.parseInt(condition.getCode())));

        // Set humidity
        weatherInfoBuilder.setHumidity(Double.parseDouble(atmosphere.getHumidity()));

        // Set wind arguments
        weatherInfoBuilder.setWind(Double.parseDouble(wind.getSpeed()),
                Double.parseDouble(wind.getDirection()),
                WeatherContract.WeatherColumns.WindSpeedUnit.MPH);

        // Set high and low for today from the simple forecast days
        weatherInfoBuilder.setTodaysHigh(Double.parseDouble(forecasts[0].getHigh()));
        weatherInfoBuilder.setTodaysLow(Double.parseDouble(forecasts[0].getLow()));

        ArrayList<WeatherInfo.DayForecast> forecastList =
                ConverterUtils.convertForecastsToDayForecasts(
                Arrays.asList(forecasts), MAX_FORECAST_DAYS);

        weatherInfoBuilder.setForecast(forecastList);

        ServiceRequestResult serviceRequestResult =
                new ServiceRequestResult.Builder(weatherInfoBuilder.build())
                        .build();
        serviceRequest.complete(serviceRequestResult);
    }

    private void processCityLookupRequest(YQLResponse yqlResponse, ServiceRequest serviceRequest) {
        final Query queryResponse = yqlResponse.getQuery();
        final Results results =  queryResponse.getResults();

        if (results == null) {
            Log.d(TAG, "Null query results, return");
            serviceRequest.fail();
            return;
        }

        final Place[] places = results.getPlace();

        if (places == null) {
            Log.d(TAG, "Null places, return");
            serviceRequest.fail();
            return;
        }

        ServiceRequestResult serviceRequestResult =
                new ServiceRequestResult.Builder(ConverterUtils.convertPlacesToWeatherLocations(
                        Arrays.asList(places))).build();
        serviceRequest.complete(serviceRequestResult);
    }
}