Projet

Général

Profil

Télécharger (3,71 ko) Statistiques
| Branche: | Tag: | Révision:

univnautes / usr / local / univnautes / sp / sp / management / commands / update-geoinfos.py @ 06507017

1
# -*- coding: utf-8 -*-
2
#
3
# UnivNautes
4
# Copyright (C) 2014  Entr'ouvert
5
#
6
# This program is free software: you can redistribute it and/or modify it under
7
# the terms of the GNU Affero General Public License as published by the Free
8
# Software Foundation, either version 3 of the License, or (at your option) any
9
# later version.
10
#
11
# This program is distributed in the hope that it will be useful, but WITHOUT
12
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
# FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
14
# details.
15
#
16
# You should have received a copy of the GNU Affero General Public License
17
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18

    
19
from django.core.management.base import BaseCommand, CommandError
20

    
21
import os
22
import sys
23
from sp import pfconfigxml
24
import urllib2
25
import json
26
import math
27

    
28
from authentic2.saml.models import LibertyProvider
29
from django.conf import settings
30
from sp import pfconfigxml
31

    
32
GEOINFOS_JS = os.path.join(settings.STATIC_ROOT, 'univnautes', 'geoinfos.js')
33

    
34
def laxfloat(x):
35
    try:
36
        return float(x)
37
    except:
38
        return 666
39

    
40
class Command(BaseCommand):
41
    help = 'build geoinfo.js from UnivNautes/pfSense config.xml geo URLs'
42

    
43
    def handle(self, *args, **options):
44
        idps = {}
45
    
46
        sp = pfconfigxml.get_sp()
47
        for url in sp.get('ui', {}).get('geolocations', []):
48
            try:
49
                print 'download geo locations from %s' % str(url)
50
                geolist = json.load(urllib2.urlopen(url))
51
            except urllib2.HTTPError as e:
52
                print 'Error loading JSON data source (%s)' % str(e)
53
            except urllib2.URLError as e:
54
                print 'Error loading JSON data source (%s)' % str(e)
55
            except ValueError as e:
56
                print 'Error reading JSON data source output (%s)' % str(e)
57
            else:
58
                for idp in geolist:
59
                    entityid = idp.get('entityID')
60
                    if not entityid:
61
                        # idp with no entityID ?... just ignore
62
                        continue
63
                    geos = idp.get('geo')
64
                    if not geos:
65
                        print 'warn: no geo info for %s' % entityid
66
                        continue
67
                    if isinstance(geos, dict):
68
                        geos = [geos]
69
                    dots = set()
70
                    for geo in geos:
71
                        if not isinstance(geo, dict) \
72
                                or not 'lat' in geo \
73
                                or not 'lon' in geo:
74
                            print 'warn: geo is not a lat/lon dict for %s' % entityid
75
                            continue
76
                        dots.add((laxfloat(geo['lat']), laxfloat(geo['lon'])))
77
                    if entityid not in idps:
78
                        idps[entityid] = dots
79
                    else:
80
                        idps[entityid].update(dots)
81
    
82
        geoinfos = []
83
    
84
        n = 0
85
        for idp in LibertyProvider.objects.all():
86
            if idp.entity_id in idps:
87
                geos = list(idps[idp.entity_id])
88
            else:
89
                print 'idp %s do not have geo, randomize it' % idp.entity_id
90
                geos = [(47.0+2.0*math.sin(n), 2.5+3.0*math.cos(n))]
91
                n += 1
92
            geoinfos.append({
93
                'slug': idp.slug,
94
                'entityid': idp.entity_id,
95
                'geo': geos
96
            })
97
    
98
        tempfilename = '/var/tmp/univnautes-geoinfo.js-%s' % os.getpid()
99
    
100
        with open(tempfilename, 'wb') as f:
101
            f.write('geoinfos = ')
102
            json.dump(geoinfos, f, indent=2)
103
            f.write('\n')
104
    
105
        os.rename(tempfilename, GEOINFOS_JS)
106

    
(2-2/2)