coordinates_by_name()   F
last analyzed

↳ Parent: Project

Complexity

Conditions 12

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 44

Importance

Changes 0
Metric Value
cc 12
dl 0
loc 44
rs 2.7855
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like coordinates_by_name() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""Look up geolocation information for media objects."""
2
from __future__ import print_function
3
from __future__ import division
4
from future import standard_library
5
from past.utils import old_div
6
7
standard_library.install_aliases()  # noqa
8
9
from os import path
10
11
import requests
12
import urllib.request
13
import urllib.parse
14
import urllib.error
15
16
from elodie.config import load_config
17
from elodie import constants
18
from elodie import log
19
from elodie.localstorage import Db
20
21
__KEY__ = None
22
23
24
def coordinates_by_name(name):
25
    # Try to get cached location first
26
    db = Db()
27
    cached_coordinates = db.get_location_coordinates(name)
28
    if(cached_coordinates is not None):
29
        return {
30
            'latitude': cached_coordinates[0],
31
            'longitude': cached_coordinates[1]
32
        }
33
34
    # If the name is not cached then we go ahead with an API lookup
35
    geolocation_info = lookup(location=name)
36
37
    if(geolocation_info is not None):
38
        if(
39
            'results' in geolocation_info and
40
            len(geolocation_info['results']) != 0 and
41
            'locations' in geolocation_info['results'][0] and
42
            len(geolocation_info['results'][0]['locations']) != 0
43
        ):
44
45
            # By default we use the first entry unless we find one with
46
            #   geocodeQuality=city.
47
            geolocation_result = geolocation_info['results'][0]
48
            use_location = geolocation_result['locations'][0]['latLng']
49
            # Loop over the locations to see if we come accross a
50
            #   geocodeQuality=city.
51
            # If we find a city we set that to the use_location and break
52
            for location in geolocation_result['locations']:
53
                if(
54
                    'latLng' in location and
55
                    'lat' in location['latLng'] and
56
                    'lng' in location['latLng'] and
57
                    location['geocodeQuality'].lower() == 'city'
58
                ):
59
                    use_location = location['latLng']
60
                    break
61
62
            return {
63
                'latitude': use_location['lat'],
64
                'longitude': use_location['lng']
65
            }
66
67
    return None
68
69
70
def decimal_to_dms(decimal):
71
    decimal = float(decimal)
72
    decimal_abs = abs(decimal)
73
    minutes, seconds = divmod(decimal_abs*3600, 60)
74
    degrees, minutes = divmod(minutes, 60)
75
    degrees = degrees
76
    sign = 1 if decimal >= 0 else -1
77
    return (degrees, minutes, seconds, sign)
78
79
80
def dms_to_decimal(degrees, minutes, seconds, direction=' '):
81
    sign = 1
82
    if(direction[0] in 'WSws'):
83
        sign = -1
84
    return (
85
        float(degrees) + old_div(float(minutes), 60) +
86
        old_div(float(seconds), 3600)
87
    ) * sign
88
89
90
def dms_string(decimal, type='latitude'):
91
    # Example string -> 38 deg 14' 27.82" S
92
    dms = decimal_to_dms(decimal)
93
    if type == 'latitude':
94
        direction = 'N' if decimal >= 0 else 'S'
95
    elif type == 'longitude':
96
        direction = 'E' if decimal >= 0 else 'W'
97
    return '{} deg {}\' {}" {}'.format(dms[0], dms[1], dms[2], direction)
98
99
100
def get_key():
101
    global __KEY__
102
    if __KEY__ is not None:
103
        return __KEY__
104
105
    config_file = '%s/config.ini' % constants.application_directory
106
    if not path.exists(config_file):
107
        return None
108
109
    config = load_config()
110
    if('MapQuest' not in config):
111
        return None
112
113
    __KEY__ = config['MapQuest']['key']
114
    return __KEY__
115
116
117
def place_name(lat, lon):
118
    # Convert lat/lon to floats
119
    if not isinstance(lat, float):
120
        lat = float(lat)
121
    if not isinstance(lon, float):
122
        lon = float(lon)
123
124
    # Try to get cached location first
125
    db = Db()
126
    # 3km distace radious for a match
127
    cached_place_name = db.get_location_name(lat, lon, 3000)
128
    # We check that it's a dict to coerce an upgrade of the location
129
    #  db from a string location to a dictionary. See gh-160.
130
    if(isinstance(cached_place_name, dict)):
131
        return cached_place_name
132
133
    lookup_place_name = {}
134
    geolocation_info = lookup(lat=lat, lon=lon)
135
    if(geolocation_info is not None):
136
        if('address' in geolocation_info):
137
            address = geolocation_info['address']
138
            for loc in ['city', 'state', 'country']:
139
                if(loc in address):
140
                    lookup_place_name[loc] = address[loc]
141
                    # In many cases the desired key is not available so we
142
                    #  set the most specific as the default.
143
                    if('default' not in lookup_place_name):
144
                        lookup_place_name['default'] = address[loc]
145
146
    if('default' not in lookup_place_name):
147
        lookup_place_name = {'default': 'Unknown Location'}
148
149
    if(lookup_place_name is not {}):
150
        db.add_location(lat, lon, lookup_place_name)
151
        # TODO: Maybe this should only be done on exit and not for every write.
152
        db.update_location_db()
153
    return lookup_place_name
154
155
156
def lookup(**kwargs):
157
    if(
158
        'location' not in kwargs and
159
        'lat' not in kwargs and
160
        'lon' not in kwargs
161
    ):
162
        return None
163
164
    key = get_key()
165
166
    if(key is None):
167
        return None
168
169
    try:
170
        params = {'format': 'json', 'key': key}
171
        params.update(kwargs)
172
        path = '/geocoding/v1/address'
173
        if('lat' in kwargs and 'lon' in kwargs):
174
            path = '/nominatim/v1/reverse.php'
175
        url = 'http://open.mapquestapi.com%s?%s' % (
176
                    path,
177
                    urllib.parse.urlencode(params)
178
              )
179
        r = requests.get(url)
180
        return parse_result(r.json())
181
    except requests.exceptions.RequestException as e:
182
        log.error(e)
183
        return None
184
    except ValueError as e:
185
        log.error(r.text)
186
        log.error(e)
187
        return None
188
189
190
def parse_result(result):
191
    if('error' in result):
192
        return None
193
194
    if(
195
        'results' in result and
196
        len(result['results']) > 0 and
197
        'locations' in result['results'][0]
198
        and len(result['results'][0]['locations']) > 0 and
199
        'latLng' in result['results'][0]['locations'][0]
200
    ):
201
        latLng = result['results'][0]['locations'][0]['latLng']
202
        if(latLng['lat'] == 39.78373 and latLng['lng'] == -100.445882):
203
            return None
204
205
    return result
206