def test01_init(self):
        "Testing GeoIP initialization."
        g1 = GeoIP()  # Everything inferred from GeoIP path
        path = settings.GEOIP_PATH
        g2 = GeoIP(path, 0)  # Passing in data path explicitly.
        g3 = GeoIP.open(path, 0)  # MaxMind Python API syntax.

        for g in (g1, g2, g3):
            self.assertEqual(True, bool(g._country))
            self.assertEqual(True, bool(g._city))

        # Only passing in the location of one database.
        city = os.path.join(path, 'GeoLiteCity.dat')
        cntry = os.path.join(path, 'GeoIP.dat')
        g4 = GeoIP(city, country='')
        self.assertEqual(None, g4._country)
        g5 = GeoIP(cntry, city='')
        self.assertEqual(None, g5._city)

        # Improper parameters.
        bad_params = (23, 'foo', 15.23)
        for bad in bad_params:
            self.assertRaises(GeoIPException, GeoIP, cache=bad)
            if isinstance(bad, basestring):
                e = GeoIPException
            else:
                e = TypeError
            self.assertRaises(e, GeoIP, bad, 0)
Exemplo n.º 2
0
def location(request):
    """
    Location selection of the user profile
    """
    profile, created = Profile.objects.get_or_create(user=request.user)
    geoip = hasattr(settings, "GEOIP_PATH")
    if geoip and request.method == "GET" and request.GET.get('ip') == "1":
        from django.contrib.gis.utils import GeoIP
        g = GeoIP()
        c = g.city(request.META.get("REMOTE_ADDR"))
        if c and c.get("latitude") and c.get("longitude"):
            profile.latitude = "%.6f" % c.get("latitude")
            profile.longitude = "%.6f" % c.get("longitude")
            profile.country = c.get("country_code")
            profile.location = unicode(c.get("city"), "latin1")

    if request.method == "POST":
        form = LocationForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("profile_edit_location_done"))
    else:
        form = LocationForm(instance=profile)

    template = "member/profile/location.html"
    data = {
        'section': 'location',
        'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY,
        'form': form,
        'geoip': geoip
    }
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
Exemplo n.º 3
0
def cidade_index(request, cidade_slug):
    cidade = Cidade.objects.get(slug=cidade_slug)
    cidades_disponiveis = Cidade.objects.all()
    ofertas = Oferta.objects.filter(ativo=True)
    destaque = Oferta.objects.filter(cidade=cidade, destaque=True, ativo=True)
    #geoprocessamento
    ip_address = request.META.get('REMOTE_ADDR')
    g = GeoIP()
    #local_full_cliente = g.city(ip_address)
    local_full_cliente = g.city('201.22.164.216')
    cidade_cliente = local_full_cliente.get('city')

    print(cidade_cliente)

    if ofertas:
        try:
            oferta_estreia = ofertas.filter(estreando=True)[0]
        except IndexError:
            oferta_estreia = ofertas[0]

        outras_ofertas = ofertas.exclude(pk=oferta_estreia.pk)
    else:
        oferta_estreia = None
        outras_ofertas = []

    return render_to_response(
        'index.html',
        locals(),
        context_instance=RequestContext(request),
    )
Exemplo n.º 4
0
def location(request):
    """
    Location selection of the user profile
    """
    profile, created = Profile.objects.get_or_create(user=request.user)
    geoip = hasattr(settings, "GEOIP_PATH")
    if geoip and request.method == "GET" and request.GET.get('ip') == "1":
        from django.contrib.gis.utils import GeoIP
        g = GeoIP()
        c = g.city(request.META.get("REMOTE_ADDR"))
        if c and c.get("latitude") and c.get("longitude"):
            profile.latitude = "%.6f" % c.get("latitude")
            profile.longitude = "%.6f" % c.get("longitude")
            profile.country = c.get("country_code")
            profile.location = unicode(c.get("city"), "latin1")

    if request.method == "POST":
        form = LocationForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message=_("Your profile information has been updated successfully."))

            signal_responses = signals.post_signal.send(sender=location, request=request, form=form)
            last_reponse = signals.last_response(signal_responses)
            if last_reponse:
                return last_response

    else:
        form = LocationForm(instance=profile)

    template = "userprofile/profile/location.html"
    data = { 'section': 'location', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY,
             'form': form, 'geoip': geoip }
    signals.context_signal.send(sender=location, request=request, context=data)
    return render_to_response(template, data, context_instance=RequestContext(request))
Exemplo n.º 5
0
 def save(self,ip_address, *args, **kwargs):
 g = GeoIP()
 lat, lon = g.lat_lon(ip_address)
 user_location = super(registerForm, self).save(commit=False)
 user_location.latitude = lat
 user_location.longitude = lon
 user_location.save(*args, **kwargs)
Exemplo n.º 6
0
def neighborhood_monitoring(request,
                          template="geotagging/view_neighborhood_monitoring.html",
                          content_type_name=None, distance_lt_km=None):
    """
    Direct the user to a template that is able to render the `kml_neighborhood_feed`
    on a google map. This feed can be restricted based on the content type of
    the element you want to get.
    """
    if distance_lt_km == None:
        distance_lt_km = 10
    gip=GeoIP()
    if request.META["REMOTE_ADDR"] != "127.0.0.1":
        user_ip = request.META["REMOTE_ADDR"]
    else:
        user_ip = "populous.com"
    user_location_pnt = gip.geos(user_ip)

    kml_feed = reverse("geotagging-kml_neighborhood_feed",
                       kwargs={"distance_lt_km":distance_lt_km})
    criteria_pnt = {
        "point__distance_lt" : (user_location_pnt,
                                D(km=float(distance_lt_km))
                                )
            }
    geotag_points = Point.objects.filter(**criteria_pnt).distance(user_location_pnt).order_by("-distance")
    context = RequestContext(request, {
        "user_ip" : user_ip,
        "user_location_pnt" : user_location_pnt,
        "geotag_points" : geotag_points,
        "user_city" : gip.city(user_ip),
        "kml_feed" : kml_feed,
    })
    return render_to_response(template,context_instance=context)
Exemplo n.º 7
0
def kml_neighborhood_feed(request, template="geotagging/geotagging.kml",
             distance_lt_km=None ,content_type_name=None,
             object_id=None):
    """
    Return a KML feed of all the geotagging in a around the user. This view takes
    an argument called `distance_lt_km` which is the radius of the permeter your
    are searching in. This feed can be restricted based on the content type of
    the element you want to get.
    """
    from django.contrib.gis.utils import GeoIP
    gip=GeoIP()
    if request.META["REMOTE_ADDR"] != "127.0.0.1":
        user_ip = request.META["REMOTE_ADDR"]
    else:
        user_ip = "populous.com"
    user_location_pnt = gip.geos(user_ip)

    criteria_pnt = {
        "point__distance_lt" : (user_location_pnt,
                                D(km=float(distance_lt_km))
                                )
            }
    if content_type_name:
        criteria_pnt["content_type__name"]==content_type_name

    geotagging = Point.objects.filter(**criteria_pnt)

    context = RequestContext(request, {
        'places' : geotagging.kml(),

    })
    return render_to_kml(template,context_instance=context)
    def test04_city(self):
        "Testing GeoIP city querying methods."
        g = GeoIP(country='<foo>')

        addr = '130.80.29.3'
        fqdn = 'chron.com'
        for query in (fqdn, addr):
            # Country queries should still work.
            for func in (g.country_code, g.country_code_by_addr,
                         g.country_code_by_name):
                self.assertEqual('US', func(query))
            for func in (g.country_name, g.country_name_by_addr,
                         g.country_name_by_name):
                self.assertEqual('United States', func(query))
            self.assertEqual(
                {
                    'country_code': 'US',
                    'country_name': 'United States'
                }, g.country(query))

            # City information dictionary.
            d = g.city(query)
            self.assertEqual('USA', d['country_code3'])
            self.assertEqual('Houston', d['city'])
            self.assertEqual('TX', d['region'])
            self.assertEqual(713, d['area_code'])
            geom = g.geos(query)
            self.failIf(not isinstance(geom, GEOSGeometry))
            lon, lat = (-95.3670, 29.7523)
            lat_lon = g.lat_lon(query)
            lat_lon = (lat_lon[1], lat_lon[0])
            for tup in (geom.tuple, g.coords(query), g.lon_lat(query),
                        lat_lon):
                self.assertAlmostEqual(lon, tup[0], 4)
                self.assertAlmostEqual(lat, tup[1], 4)
Exemplo n.º 9
0
def create_gateway(sender, instance=None, created=False, **kwargs):
    """ create root domain of user """
    if created:
        geo = GeoIP()
        data = geo.city(instance.ip)
        instance.city = data['city']
        instance.country = data['country_name']
        instance.save()
Exemplo n.º 10
0
def getLocation(self):

	g = GeoIP()
	ip = request.META.get('REMOTE_ADDR',None)
	if ip:
		city = g.city(ip)['city']
		return city
	
	else :
		print "nothing"
Exemplo n.º 11
0
def _cidade_cliente(request):
    #geo
    ip_address = request.META.get('REMOTE_ADDR')
    g = GeoIP()
    #local_full_cliente = g.city(ip_address)
    local_full_cliente = g.city('201.22.164.216')
    cidade_cliente = local_full_cliente.get('city')
    uni = cidade_cliente.decode('cp1252')
    cidade_cliente = uni.encode('utf8')
    return cidade_cliente
Exemplo n.º 12
0
def get_geoip_coords(request):
    lat, lng = '', ''
    geoip = GeoIP()
    # TODO: Middleware to set REMOTE_ADDR from HTTP_X_FORWARDED_FOR.
    remote_addr = get_remote_ip(request)
    geoip_result = geoip.city(remote_addr)
    if geoip_result:
        lat = geoip_result.get('latitude', '')
        lng = geoip_result.get('longitude', '')
    return lat, lng
Exemplo n.º 13
0
def whereami(request):
	g = GeoIP()
	remote_ip = request.META['REMOTE_ADDR']
	if remote_ip == '127.0.0.1':
	    remote_ip = get_my_ip()
	remote_location = g.city(remote_ip)
	if remote_location:
	    return render_to_response('gmaps.html', {'remote_location': remote_location, 'GOOGLE_MAPS_API_KEY':settings.GOOGLE_MAPS_API_KEY})
	else: # localhost ip cannot be found
	    return render_to_response('not_found.html')
Exemplo n.º 14
0
    def test02_bad_query(self):
        "Testing GeoIP query parameter checking."
        cntry_g = GeoIP(city='<foo>')
        # No city database available, these calls should fail.
        self.assertRaises(GeoIPException, cntry_g.city, 'google.com')
        self.assertRaises(GeoIPException, cntry_g.coords, 'yahoo.com')

        # Non-string query should raise TypeError
        self.assertRaises(TypeError, cntry_g.country_code, 17)
        self.assertRaises(TypeError, cntry_g.country_name, GeoIP)
Exemplo n.º 15
0
def whereis(request, ip):
	g = GeoIP()
	ip_match = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
	try:
	    remote_ip = ip_match.findall(ip)[0]
	except:
	    remote_ip = ''
	remote_location = g.city(remote_ip)
	if remote_location:
	    return render_to_response('gmaps.html', {'remote_location': remote_location, 'GOOGLE_MAPS_API_KEY':settings.GOOGLE_MAPS_API_KEY})
	else: # localhost ip cannot be found
	    return render_to_response('not_found.html')
Exemplo n.º 16
0
def get_geoip_position(request):
    """Returns the user's position as a (lat, lng) tuple based on his IP."""
    result = (None, None)
    g = GeoIP()
    ip = (request.META.get('HTTP_X_FORWARDED_FOR')
          or request.META.get('REMOTE_ADDR'))
    result = g.lon_lat(ip)
    if result is None:
        ip = settings.SERVER_IP
        result = g.lon_lat(ip)
        if result is None:
            return None
    return (result[1], result[0])
Exemplo n.º 17
0
 def wrapper(*args, **kw):
     request = args[0]
     user = request.user
     org = Organization.objects.get(org_id=user.get_profile().org_id)
     try:
         country_code = GeoIP().country_code(
             request.META.get('REMOTE_ADDR'))
     except Exception as e:
         logger.exception("Error resolving country from IP : \n%s" % e)
         raise
     if country_code is None or org.country.code == country_code:
         return f(*args, **kw)
     return HttpResponse(status=401)
Exemplo n.º 18
0
def detect_currency(request):
    country = GeoIP().country(request.META['REMOTE_ADDR'])
    currency_id = Currency.objects.get(symbol='EUR').id
    if country['country_name']:
        country_up = country['country_name'].upper()
        if country_up in COUNTRY_CURRENCY_MAP:
            symbol = COUNTRY_CURRENCY_MAP[country_up]
            try:
                currency = Currency.objects.get(symbol=symbol)
                currency_id = currency.id
            except ObjectDoesNotExist:
                pass
    return currency_id
Exemplo n.º 19
0
 def test03_country(self):
     "Testing GeoIP country querying methods."
     g = GeoIP(city='<foo>')
     
     fqdn = 'www.google.com'
     addr = '12.215.42.19'
     
     for query in (fqdn, addr):
         for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name):
             self.assertEqual('US', func(query))
         for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name):
             self.assertEqual('United States', func(query))
         self.assertEqual({'country_code' : 'US', 'country_name' : 'United States'},
                          g.country(query))
Exemplo n.º 20
0
 def wrapper(*args, **kw):
     request = args[0]
     user = request.user
     org = Organization.objects.get(org_id=user.get_profile().org_id)
     try:
         country_code = GeoIP().country_code(
             request.META.get('REMOTE_ADDR'))
     except Exception as e:
         logger.exception("Error resolving country from IP : \n%s" % e)
         raise
     log_message = 'User: %s, IP: %s resolved in %s, for Oragnization id: %s located in country: %s ' %\
                   (user, request.META.get('REMOTE_ADDR'), country_code, org.org_id, org.country)
     logger.info(log_message)
     return f(*args, **kw)
Exemplo n.º 21
0
 def __init__(self):
     if getattr(settings, 'IS_DEV_SERVER', False
                ) or 'django.contrib.sites' not in settings.INSTALLED_APPS:
         raise MiddlewareNotUsed()
     try:
         from django.contrib.gis.utils import GeoIP, GeoIPException
         self.g = GeoIP()
         self.redirect_sites = dict(settings.SITE_GEOIP_REDIRECT)
     except (ImportError, GeoIPException, ValueError, TypeError,
             AttributeError):
         raise ImproperlyConfigured(
             "The GeoIPRedirectMiddleware requires the"
             " setting SITE_GEOIP_REDIRECT and GEOIP_PATH to be defined"
             " along with a working GeoIP installation."
             " Please see 'django.contrib.gis.utils.geoip.py'.")
     self.srs_url_re = re.compile("^/siteinfo/srs/?$")
     self.srs_getvarname = getattr(settings,
                                   'SITE_GEOIP_REDIRECT_GETVARNAME', 'srs')
Exemplo n.º 22
0
    def _get_geoip_data(self):
        """
        Attempts to retrieve MaxMind GeoIP data based upon the visitor's IP
        """

        if not HAS_GEOIP or not USE_GEOIP:
            # go no further when we don't need to
            log.debug('Bailing out.  HAS_GEOIP: %s; TRACKING_USE_GEOIP: %s' % (HAS_GEOIP, USE_GEOIP))
            return None

        if not hasattr(self, '_geoip_data'):
            self._geoip_data = None
            try:
                gip = GeoIP(cache=CACHE_TYPE)
                self._geoip_data = gip.city(self.ip_address)
            except GeoIPException:
                # don't even bother...
                log.error('Error getting GeoIP data for IP "%s": %s' % (self.ip_address, traceback.format_exc()))

        return self._geoip_data
Exemplo n.º 23
0
    def set_redirect_by_ip(self, request):
        g = GeoIP()
        ip = get_real_ip(request)
        user_city = g.city(ip)
        target_city = None
        if user_city:
            target_city = get_object_or_None(City,
                                             name_by_geoip=user_city['city'])

        if not target_city:
            target_city = City.objects.get(is_default=True)

        target_domain = target_city.site.domain
        if not target_city.site.domain.startswith('http'):
            target_domain = 'http://%s' % target_domain
        target_url = urlparse(target_domain)
        request_url = urlparse('http://%s/' % request.get_host())

        if not target_url.netloc == request_url.netloc:
            self.redirect_to = target_city.site.domain
Exemplo n.º 24
0
 def parse_data(self):
     self.parse_useragent()
     if self.ip:
         try:
             g = GeoIP()
             location = g.city(self.ip)
             if location:
                 country = ox.get_country_name(location['country_code'])
                 if location['city']:
                     city = location['city']
                     if type(city) != unicode:
                         city = city.decode('latin-1')
                     self.location = u'%s, %s' % (city, country)
                     self.location_sort = u'%s, %s' % (country, city)
                 else:
                     self.location_sort = self.location = country
             else:
                 self.location_sort = self.location = None
         except:
             self.location_sort = self.location = None
             pass
Exemplo n.º 25
0
def get_country_by_ip(ip):
    from api.views import create_dump_file
    g = GeoIP()
    country = None
    try:
        name = g.country(ip)['country_name']
        if name == 'Russian Federation':
            name = 'Russia'
        elif name == 'United States':
            name = 'USA'
        elif name == 'Moldova, Republic of':
            name = 'Moldova'
        elif name == 'United Kingdom':
            name = 'UK'
        elif name == 'Iran, Islamic Republic of':
            name = 'Iran'
        try:
            country = Country.objects.get(name_en=name)
        except Country.DoesNotExist:
            pass
            '''
            if name:
                with open('%s/dump_geoip_nof_country.xml' % settings.NOF_DUMP_PATH, 'r') as f:
                    xml_data = BeautifulSoup(f.read(), from_encoding="utf-8")
                
                name_slug = low(del_separator(name))
                countries_slugs = [i.get('slug') for i in xml_data.findAll('country')]
                
                data_nof_country = ''
                if name_slug not in countries_slugs:
                    data_nof_country = '<country name="%s" slug="%s"></country>' % (name, name_slug)
                    
                xml_data = str(xml_data).replace('<html><head></head><body><data>','').replace('</data></body></html>','')
                xml_data = '<data>%s%s</data>' % (xml_data, data_nof_country)
                create_dump_file('geoip_nof_country', settings.NOF_DUMP_PATH, xml_data)
            '''
    except TypeError:
        pass
    return country
Exemplo n.º 26
0
def dashboard_create(request):
    if request.method == "POST":
        form = DashboardForm(request.POST)
        if form.is_valid():
            dashboard = form.save(commit=False)
            dashboard.user = request.user
            route_formset = RouteFormSet(request.POST, instance=dashboard)
            if route_formset.is_valid():
                dashboard.save()
                route_formset.save()
                messages.success(request, "Created!")
                return HttpResponseRedirect(dashboard.get_absolute_url())
        else:
            route_formset = RouteFormSet(instance=Dashboard())
    else:
        # try to find the best city match
        initial = {}
        if request.user.dashboards.exists():
            # Use existing city to start with
            initial['city'] = request.user.dashboards.all()[0].city
        else:
            # try a GeoIP lookup
            geoip = GeoIP().geos(request.META['REMOTE_ADDR'])
            if geoip:
                initial['city'] = City.objects.distance(geoip).order_by(
                    '-distance')[0]

        form = DashboardForm(initial=initial)
        route_formset = RouteFormSet(instance=Dashboard())

    context = {
        'form': form,
        'route_formset': route_formset,
        'title': 'New Dashboard',
        'stopFusionTableId': settings.GTFS_STOP_FUSION_TABLE_ID,
        'city_data': json.dumps(City.objects.get_map_info()),
    }
    return TemplateResponse(request, "mine/dashboard_form.html", context)
Exemplo n.º 27
0
    def process_request(self, request):
        from django.conf import settings
        from meegloo.international.models import Country

        try:
            from django.contrib.gis.utils import GeoIP
        except ImportError:
            request.country = Country.objects.get(
                pk=getattr(settings, 'COUNTRY_ID'))

            return

        g = GeoIP()
        ip = request.META.get(
            'HTTP_X_FORWARDED_FOR',
            request.META.get('REMOTE_IP', request.META.get('REMOTE_ADDR')))

        if ip != '127.0.0.1':
            d = g.country(ip)
            code = d['country_code']
            request.country = Country.objects.get(code=code)
        else:
            pk = getattr(settings, 'COUNTRY_ID')
            request.country = Country.objects.get(pk=pk)
Exemplo n.º 28
0
 def save(self, *args, **kwargs):
     g = GeoIP()
     self.coords = g.geos(self.ip_address)
     super(Hit, self).save(*args, **kwargs)
Exemplo n.º 29
0
import re
from urlparse import urlparse

from django.contrib.gis.utils import GeoIP
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _

from IPy import IP
import dns.resolver
import dns.reversename

from plugin import PluginMixin
from scanner.models import STATUS, RESULT_STATUS, RESULT_GROUP
from webscanner.utils.geo import make_map

geoip = GeoIP()


class PluginDNSmail(PluginMixin):
    name = unicode(_("Check dns MAIL"))
    description = unicode(_("Check dns MAIL"))
    wait_for_download = False

    def run(self, command):
        from scanner.models import Results
        domain = command.test.domain()
        test = command.test

        if not command.test.check_mail:
            return STATUS.success
        try:
Exemplo n.º 30
0
from django.contrib.gis.utils import GeoIP
g = GeoIP()
ip = request.META.get('REMOTE_ADDR', None)
if ip:
    city = g.city(ip)['city']
else:
    city = 'Rome' # default city

# proceed with city