1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16 
17 package com.android.incallui.calllocation.impl;
18 
19 import android.location.Location;
20 import android.net.TrafficStats;
21 import android.os.AsyncTask;
22 import com.android.dialer.common.LogUtil;
23 import com.android.dialer.constants.TrafficStatsTags;
24 import com.android.incallui.calllocation.impl.LocationPresenter.LocationUi;
25 import java.lang.ref.WeakReference;
26 import org.json.JSONArray;
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 
30 class ReverseGeocodeTask extends AsyncTask<Location, Void, String> {
31 
32   // Below are the JSON keys for the reverse geocode response.
33   // Source: https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
34   private static final String JSON_KEY_RESULTS = "results";
35   private static final String JSON_KEY_ADDRESS = "formatted_address";
36   private static final String JSON_KEY_ADDRESS_COMPONENTS = "address_components";
37   private static final String JSON_KEY_PREMISE = "premise";
38   private static final String JSON_KEY_TYPES = "types";
39   private static final String JSON_KEY_LONG_NAME = "long_name";
40   private static final String JSON_KEY_SHORT_NAME = "short_name";
41 
42   private WeakReference<LocationUi> uiReference;
43 
ReverseGeocodeTask(WeakReference<LocationUi> uiReference)44   public ReverseGeocodeTask(WeakReference<LocationUi> uiReference) {
45     this.uiReference = uiReference;
46   }
47 
48   @Override
doInBackground(Location... locations)49   protected String doInBackground(Location... locations) {
50     LocationUi ui = uiReference.get();
51     if (ui == null) {
52       return null;
53     }
54     if (locations == null || locations.length == 0) {
55       LogUtil.e("ReverseGeocodeTask.onLocationChanged", "No location provided");
56       return null;
57     }
58 
59     try {
60       String address = null;
61       String url = LocationUrlBuilder.getReverseGeocodeUrl(locations[0]);
62 
63       TrafficStats.setThreadStatsTag(TrafficStatsTags.REVERSE_GEOCODE_TAG);
64       String jsonResponse = HttpFetcher.getRequestAsString(ui.getContext(), url);
65 
66       // Parse the JSON response for the formatted address of the first result.
67       JSONObject responseObject = new JSONObject(jsonResponse);
68       if (responseObject != null) {
69         JSONArray results = responseObject.optJSONArray(JSON_KEY_RESULTS);
70         if (results != null && results.length() > 0) {
71           JSONObject topResult = results.optJSONObject(0);
72           if (topResult != null) {
73             address = topResult.getString(JSON_KEY_ADDRESS);
74 
75             // Strip off the Premise component from the address, if present.
76             JSONArray components = topResult.optJSONArray(JSON_KEY_ADDRESS_COMPONENTS);
77             if (components != null) {
78               boolean stripped = false;
79               for (int i = 0; !stripped && i < components.length(); i++) {
80                 JSONObject component = components.optJSONObject(i);
81                 JSONArray types = component.optJSONArray(JSON_KEY_TYPES);
82                 if (types != null) {
83                   for (int j = 0; !stripped && j < types.length(); j++) {
84                     if (JSON_KEY_PREMISE.equals(types.getString(j))) {
85                       String premise = null;
86                       if (component.has(JSON_KEY_SHORT_NAME)
87                           && address.startsWith(component.getString(JSON_KEY_SHORT_NAME))) {
88                         premise = component.getString(JSON_KEY_SHORT_NAME);
89                       } else if (component.has(JSON_KEY_LONG_NAME)
90                           && address.startsWith(component.getString(JSON_KEY_LONG_NAME))) {
91                         premise = component.getString(JSON_KEY_SHORT_NAME);
92                       }
93                       if (premise != null) {
94                         int index = address.indexOf(',', premise.length());
95                         if (index > 0 && index < address.length()) {
96                           address = address.substring(index + 1).trim();
97                         }
98                         stripped = true;
99                         break;
100                       }
101                     }
102                   }
103                 }
104               }
105             }
106 
107             // Strip off the country, if its USA.  Note: unfortunately the country in the formatted
108             // address field doesn't match the country in the address component fields (USA != US)
109             // so we can't easily strip off the country for all cases, thus this hack.
110             if (address.endsWith(", USA")) {
111               address = address.substring(0, address.length() - 5);
112             }
113           }
114         }
115       }
116 
117       return address;
118     } catch (AuthException ex) {
119       LogUtil.e("ReverseGeocodeTask.onLocationChanged", "AuthException", ex);
120       return null;
121     } catch (JSONException ex) {
122       LogUtil.e("ReverseGeocodeTask.onLocationChanged", "JSONException", ex);
123       return null;
124     } catch (Exception ex) {
125       LogUtil.e("ReverseGeocodeTask.onLocationChanged", "Exception!!!", ex);
126       return null;
127     } finally {
128       TrafficStats.clearThreadStatsTag();
129     }
130   }
131 
132   @Override
onPostExecute(String address)133   protected void onPostExecute(String address) {
134     LocationUi ui = uiReference.get();
135     if (ui == null) {
136       return;
137     }
138 
139     try {
140       ui.setAddress(address);
141     } catch (Exception ex) {
142       LogUtil.e("ReverseGeocodeTask.onPostExecute", "Exception!!!", ex);
143     }
144   }
145 }
146