views.py 16.4 KB
Newer Older
1 2 3 4 5 6
# -*- coding: utf-8 -*- vim:encoding=utf-8:
# vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab

from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect,Http404
from django.template import RequestContext
7
from django.core.urlresolvers import reverse
8 9
from django.contrib.auth.decorators import login_required
from edumanage.models import *
10 11
from edumanage.forms import *
from django import forms
12 13 14 15
from django.forms.models import modelformset_factory
from django.forms.models import inlineformset_factory
from django.contrib.contenttypes.generic import generic_inlineformset_factory
import json 
16 17 18 19
import math
from xml.etree import cElementTree as ET

from django.conf import settings
20 21

def index(request):
22
    return render_to_response('front/index.html', context_instance=RequestContext(request, base_response(request)))
23 24 25 26 27

@login_required
def manage(request):
    services_list = []
    servers_list = []
28 29 30 31 32 33 34 35 36 37
    user = request.user
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    services = ServiceLoc.objects.filter(institutionid=inst)
    services_list.extend([s for s in services])
    servers = InstServer.objects.filter(instid=inst)
    servers_list.extend([s for s in servers])
38 39
    return render_to_response('edumanage/welcome.html', 
                              {
40
                               'institution': inst, 
41 42 43
                               'services': services_list,
                               'servers': servers_list
                               },  
44
                              context_instance=RequestContext(request, base_response(request)))
45 46 47 48

@login_required
def institutions(request):
    user = request.user
49 50 51 52 53 54 55 56 57 58 59 60
    dict = {}
    
    try:
        profile = user.get_profile()
        inst = profile.institution
        inst.__unicode__ = inst.get_name(request.LANGUAGE_CODE)
    except UserProfile.DoesNotExist:
        inst = False
    dict['institution'] = inst.pk
    form = InstDetailsForm(initial=dict)
    form.fields['institution'].widget.attrs['readonly'] = True
    return render_to_response('edumanage/institution.html', 
61
                              {
62 63
                               'institution': inst,
                               'form': form, 
64
                               },  
65
                              context_instance=RequestContext(request, base_response(request)))
66 67 68 69 70 71



@login_required
def add_institution_details(request, institution_pk):
    user = request.user
72 73 74 75 76 77 78 79 80 81
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
        
    if (not inst) or (int(inst.pk) != int(institution_pk)):
    #            messages.add_message(request, messages.WARNING,
    #                             _("Insufficient rights on Institution. Contact your administrator"))
        return HttpResponseRedirect(reverse("institutions"))
82 83
    if request.method == "GET":

84 85 86 87 88 89 90 91 92 93
        # Determine add or edit
        request_data = request.POST.copy()
        try:         
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(instance=inst_details)
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm()
            form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
        
        
94
        return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form},
95
                                  context_instance=RequestContext(request, base_response(request)))
96 97
    elif request.method == 'POST':
        request_data = request.POST.copy()
98 99 100 101 102
        try:         
            inst_details = InstitutionDetails.objects.get(institution=inst)
            form = InstDetailsForm(request_data, instance=inst_details)
        except InstitutionDetails.DoesNotExist:
            form = InstDetailsForm(request_data)
103
        if form.is_valid():
104 105
            instdets = form.save()
            return HttpResponseRedirect(reverse("institutions"))
106 107 108 109 110 111 112 113
        else:
            try:
                profile = user.get_profile()
                inst = profile.institution
            except UserProfile.DoesNotExist:
                inst = False
                form.fields['institution'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=institution_pk), empty_label=None)
            return render_to_response('edumanage/institution_edit.html', { 'institution': inst, 'form': form},
114
                                  context_instance=RequestContext(request, base_response(request)))
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

@login_required
def services(request):
    user = request.user
    dict = {}
    
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    try:
        services = ServiceLoc.objects.filter(institutionid = inst)
    except ServiceLoc.DoesNotExist:
        services = False 
        
    
    return render_to_response('edumanage/services.html', 
                              {
                               'institution': inst,
                               'services': services, 
                               },  
138
                              context_instance=RequestContext(request, base_response(request)))
139 140 141 142 143 144



@login_required
def add_services(request, service_pk):
    user = request.user
145
    service = False
146 147 148 149 150
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
151

152 153 154 155 156 157 158 159
    if request.method == "GET":

        # Determine add or edit
        try:         
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
            form = ServiceLocForm(instance=service)
        except ServiceLoc.DoesNotExist:
            form = ServiceLocForm()
160
        form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
161 162 163 164
        UrlFormSet =  generic_inlineformset_factory(URL_i18n, extra=2, can_delete=True)
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=2, can_delete=True)
        urls_form = UrlFormSet(prefix='urlsform') 
        names_form = NameFormSet(prefix='namesform')
165
        if (service):
166 167 168 169 170 171
            NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
            names_form = NameFormSet(instance=service, prefix='namesform')
            UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
            urls_form = UrlFormSet(instance=service, prefix='urlsform')
        return render_to_response('edumanage/services_edit.html', { 'form': form, 'services_form':names_form, 'urls_form': urls_form},
                                  context_instance=RequestContext(request, base_response(request)))
172 173
    elif request.method == 'POST':
        request_data = request.POST.copy()
174 175
        NameFormSet = generic_inlineformset_factory(Name_i18n, extra=1, formset=NameFormSetFact, can_delete=True)
        UrlFormSet = generic_inlineformset_factory(URL_i18n, extra=2, formset=UrlFormSetFact, can_delete=True)
176 177 178
        try:         
            service = ServiceLoc.objects.get(institutionid=inst, pk=service_pk)
            form = ServiceLocForm(request_data, instance=service)
179 180
            names_form = NameFormSet(request_data, instance=service, prefix='namesform')
            urls_form = UrlFormSet(request_data, instance=service, prefix='urlsform')
181 182
        except ServiceLoc.DoesNotExist:
            form = ServiceLocForm(request_data)
183 184
            names_form = NameFormSet(request_data, prefix='namesform')
            urls_form = UrlFormSet(request_data, prefix='urlsform')
185
        
186
        if form.is_valid() and names_form.is_valid() and urls_form.is_valid():
187
            serviceloc = form.save()
188 189 190 191 192 193 194 195 196 197 198
            service = serviceloc
            names_form.instance = service
            urls_form.instance = service
            names_inst = names_form.save()
            urls_inst = urls_form.save()
#            for nform in names_inst:
#                nform.content_object = serviceloc
#                nform.save()
#            for uform in urls_inst:
#                uform.content_object = serviceloc
#                uform.save()
199 200
            return HttpResponseRedirect(reverse("services"))
        else:
201 202
            form.fields['institutionid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)

203 204 205
        return render_to_response('edumanage/services_edit.html', { 'institution': inst, 'form': form, 'services_form':names_form, 'urls_form': urls_form},
                                  context_instance=RequestContext(request, base_response(request)))

206

207 208 209 210 211 212 213 214 215 216 217

@login_required
def get_service_points(request):
    if request.method == "GET":
        user = request.user
        try:
            profile = user.get_profile()
            inst = profile.institution
        except UserProfile.DoesNotExist:
            inst = False
        servicelocs = ServiceLoc.objects.filter(institutionid=inst)
218
        
219 220 221 222 223
        locs = []
        for sl in servicelocs:
            response_location = {}
            response_location['lat'] = u"%s"%sl.latitude
            response_location['lng'] = u"%s"%sl.longitude
Leonidas Poulopoulos's avatar
Leonidas Poulopoulos committed
224 225 226
            response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
            response_location['enc'] = u"%s"%(sl.enc_level)
            response_location['AP_no'] = u"%s"%(sl.AP_no)
227
            response_location['name'] = sl.loc_name.get(lang='en').name
Leonidas Poulopoulos's avatar
Leonidas Poulopoulos committed
228 229 230 231 232 233
            response_location['port_restrict'] = u"%s"%(sl.port_restrict)
            response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
            response_location['IPv6'] = u"%s"%(sl.IPv6)
            response_location['NAT'] = u"%s"%(sl.NAT)
            response_location['wired'] = u"%s"%(sl.wired)
            response_location['SSID'] = u"%s"%(sl.SSID)
234 235 236 237 238
            response_location['key'] = u"%s"%sl.pk
            locs.append(response_location)
        return HttpResponse(json.dumps(locs), mimetype='application/json')
    else:
       return HttpResponseNotFound('<h1>Something went really wrong</h1>')
239 240


241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
def get_all_services(request):
    servicelocs = ServiceLoc.objects.all()
    locs = []
    for sl in servicelocs:
        response_location = {}
        response_location['lat'] = u"%s"%sl.latitude
        response_location['lng'] = u"%s"%sl.longitude
        response_location['address'] = u"%s<br>%s"%(sl.address_street, sl.address_city)
        response_location['enc'] = u"%s"%(sl.enc_level)
        response_location['AP_no'] = u"%s"%(sl.AP_no)
        response_location['inst'] = sl.institutionid.org_name.get(lang='en').name
        response_location['name'] = sl.loc_name.get(lang='en').name
        response_location['port_restrict'] = u"%s"%(sl.port_restrict)
        response_location['transp_proxy'] = u"%s"%(sl.transp_proxy)
        response_location['IPv6'] = u"%s"%(sl.IPv6)
        response_location['NAT'] = u"%s"%(sl.NAT)
        response_location['wired'] = u"%s"%(sl.wired)
        response_location['SSID'] = u"%s"%(sl.SSID)
        response_location['key'] = u"%s"%sl.pk
        locs.append(response_location)
    return HttpResponse(json.dumps(locs), mimetype='application/json')



265
def servers(request):
266 267 268 269 270 271 272 273 274
    user = request.user
    servers = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False
    if inst:
        servers = InstServer.objects.filter(instid=inst)
275
    return render_to_response('edumanage/servers.html', { 'servers': servers},
276 277
                                  context_instance=RequestContext(request, base_response(request)))

278 279


280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
@login_required
def adduser(request):
    if request.method == "GET":
        form = ContactForm()
        return render_to_response('edumanage/add_user.html', { 'form': form},
                                  context_instance=RequestContext(request, base_response(request)))
    elif request.method == 'POST':
        request_data = request.POST.copy()
        form = ContactForm(request_data)
        if form.is_valid():
            contact = form.save()
            response_data = {}
            response_data['value'] = "%s" %contact.pk
            response_data['text'] = "%s" %contact
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
        else:
            return render_to_response('edumanage/add_user.html', {'form': form,},
                                      context_instance=RequestContext(request, base_response(request)))

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
@login_required
def add_server(request, server_pk):
    user = request.user
    server = False
    try:
        profile = user.get_profile()
        inst = profile.institution
    except UserProfile.DoesNotExist:
        inst = False

    if request.method == "GET":

        # Determine add or edit
        try:         
            server = InstServer.objects.get(instid=inst, pk=server_pk)
            form = InstServerForm(instance=server)
        except InstServer.DoesNotExist:
            form = InstServerForm()
        form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
        
        return render_to_response('edumanage/servers_edit.html', { 'form': form},
320
                                  context_instance=RequestContext(request, base_response(request)))
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    elif request.method == 'POST':
        request_data = request.POST.copy()
        try:         
            server = InstServer.objects.get(instid=inst, pk=server_pk)
            form = InstServerForm(request_data, instance=server)
        except InstServer.DoesNotExist:
            form = InstServerForm(request_data)
        
        if form.is_valid():
            instserverf = form.save()
            return HttpResponseRedirect(reverse("servers"))
        else:
            form.fields['instid'] = forms.ModelChoiceField(queryset=Institution.objects.filter(pk=inst.pk), empty_label=None)
        print form.errors
        return render_to_response('edumanage/servers_edit.html', { 'institution': inst, 'form': form},
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
                                  context_instance=RequestContext(request, base_response(request)))

@login_required
def base_response(request):
    user = request.user
    inst = []
    server = []
    services = []
    try:
        profile = user.get_profile()
        institution = profile.institution
        inst.append(institution)
        server = InstServer.objects.filter(instid=institution)
        services = ServiceLoc.objects.filter(institutionid=institution)
    except UserProfile.DoesNotExist:
        pass
        
    return { 
            'inst_num': len(inst),
            'servers_num': len(server),
            'services_num': len(services),
            
        }

def geolocate(request):
    return render_to_response('front/geolocate.html',
                                  context_instance=RequestContext(request))


def closest(request):
    if request.method == 'GET':
        locs = []
        request_data = request.GET.copy()
        response_location = {}
        response_location["lat"] = request_data['lat']
        response_location["lng"] = request_data['lng']
        lat = float(request_data['lat'])
        lng = float(request_data['lng'])
        R = 6371
        distances = {}
        closestMarker = {}
        closest = -1
        doc = ET.parse(settings.KML_FILE)
        root = doc.getroot()
        r = root.getchildren()[0]
        for (counter, i) in enumerate(r.getchildren()):
            if "id" in i.keys():
                j = i.getchildren()
                pointname = j[0].text
                point = j[2].getchildren()[0].text
                pointlng, pointlat, pointele = point.split(',')
                dLat = rad(float(pointlat)-float(lat))
                dLong = rad(float(pointlng)-float(lng))
                a = math.sin(dLat/2) * math.sin(dLat/2) + math.cos(rad(lat)) * math.cos(rad(float(pointlat))) * math.sin(dLong/2) * math.sin(dLong/2) 
                c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
                d = R * c
                distances[counter] = d
                if (closest == -1 or d < distances[closest]):
                    closest = counter
                    closestMarker = {"name": pointname, "lat": pointlat, "lng": pointlng, "text": j[1].text}
        return HttpResponse(json.dumps(closestMarker), mimetype='application/json')
        
        

def rad(x):
    return x*math.pi/180