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
|
# Copyright (C) 2012 Canonical
#
# Authors:
# Michael Vogt
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
import locale
import logging
import os
import xml.etree.ElementTree
from gettext import dgettext
from gettext import gettext as _
LOG = logging.getLogger(__name__)
# warning displayed if region does not match
REGION_WARNING_STRING = _("Sorry, this software is not available in your "
"region.")
# the prefix tag for regions that the software is most useful in
REGIONTAG = "iso3166::"
# blacklist this region
REGION_BLACKLIST_TAG = "blacklist-iso3166::"
def get_region_name(countrycode):
""" return translated region name from countrycode using iso3166 """
# find translated name
if countrycode:
for iso in ["iso_3166", "iso_3166_2"]:
path = os.path.join("/usr/share/xml/iso-codes/", iso + ".xml")
if os.path.exists(path):
root = xml.etree.ElementTree.parse(path)
xpath = ".//%s_entry[@alpha_2_code='%s']" % (iso, countrycode)
match = root.find(xpath)
if match is not None:
name = match.attrib.get("common_name")
if not name:
name = match.attrib["name"]
return dgettext(iso, name)
return ""
# the first parameter of SetRequirements
class AccuracyLevel:
NONE = 0
COUNTRY = 1
REGION = 2
LOCALITY = 3
POSTALCODE = 4
STREET = 5
DETAILED = 6
class AllowedResources:
NONE = 0
NETWORK = 1 << 0
CELL = 1 << 1
GPS = 1 << 2
ALL = (1 << 10) - 1
class RegionDiscover(object):
def get_region(self):
""" return a dict with at least "county" and "countrycode" as
keys - they may be empty if no region is found
"""
res = {}
# try geoclue first
try:
res = self._get_region_geoclue()
if res:
return res
except Exception as e:
LOG.warn("failed to use geoclue: '%s'" % e)
# fallback
res = self._get_region_dumb()
return res
def _get_region_dumb(self):
""" return dict estimate about the current countrycode/country """
res = {'countrycode': '',
'country': '',
}
try:
# use LC_MONETARY as the best guess
loc = locale.getlocale(locale.LC_MONETARY)[0]
except Exception as e:
LOG.warn("Failed to get locale: '%s'" % e)
return res
if not loc:
return res
countrycode = loc.split("_")[1]
res["countrycode"] = countrycode
res["country"] = get_region_name(countrycode)
return res
def _get_region_geoclue(self):
""" return the dict with at least countrycode,country from a geoclue
provider
"""
bus = dbus.SessionBus()
master = bus.get_object(
'org.freedesktop.Geoclue.Master',
'/org/freedesktop/Geoclue/Master')
client = bus.get_object(
'org.freedesktop.Geoclue.Master', master.Create())
client.SetRequirements(AccuracyLevel.COUNTRY, # (i) accuracy_level
0, # (i) time
False, # (b) require_updates
AllowedResources.ALL) # (i) allowed_resoures
# this is crucial
client.AddressStart()
# now get the data
time, address_res, accuracy = client.GetAddress()
return address_res
my_region = None
def get_region_cached():
global my_region
if my_region is None:
rd = RegionDiscover()
my_region = rd.get_region()
return my_region
|