views.py 6.84 KB
from django.http import HttpResponse
from django.shortcuts import render, redirect

from django.contrib.auth.decorators import login_required
import datetime
from common.models import Log, WeatherWatch, SiteWatch, ScientificProgram, Config, PyrosUser
from django.core import serializers
import utils.Logger as l
from django.forms import modelformset_factory
from dashboard.forms import ConfigForm, UsersForm
from dashboard.decorator import superuser_only
from django.views.generic.edit import UpdateView
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.urls import reverse_lazy, reverse
from django.http import Http404

log = l.setupLogger("dashboard", "dashboard")



@login_required
def index(request):
    return render(request, 'dashboard/index.html')                              # return the initial view (the dashboard's one)

#@login_required
#def observation_status(request):
 #   return render(request, 'dashboard/observation_status.html')

@login_required
def retrieve_env(request):
    try:
        weather_status = WeatherWatch.objects.latest('updated')
        t = datetime.datetime.now() + datetime.timedelta(hours=-7) #temporary method to demonstrate the day/night display
        isDay = False
        if t.hour > 5 and t.hour < 20:
            isDay = True
        return render(request, 'dashboard/observation_status_env.html', locals())
    except WeatherWatch.DoesNotExist:
            raise Http404("No WeatherWatch matches the given query.")
    

@login_required
def retrieve_env_navbar(request):
    if request.is_ajax():
        try:
            weather_status = WeatherWatch.objects.latest('updated')
            weather = serializers.serialize('json', [weather_status])
            return HttpResponse(weather, content_type="application/json")
        except WeatherWatch.DoesNotExist:
            raise Http404("No WeatherWatch matches the given query.")

@login_required
def users(request):
    instance = PyrosUser.objects.order_by("-id")
    return render(request, 'dashboard/users_management.html', {'instance': instance})                     # return the initial view (the users management's one) 

@login_required
def routines(request):
    url_ = reverse('admin:common_request_changelist')
    return redirect(url_)


@login_required
def weather(request):
    return render(request, 'dashboard/reload_weather.html')                                                                     # return the needed html file

@login_required
def weather_current(request):
    try:
        if (len(Config.objects.all()) == 1):
            monitoring = int(int(Config.objects.get(id=1).row_data_save_frequency) / 5)
        else:
            monitoring = 60
        if (len(WeatherWatch.objects.all()) > 0):
            weather_info = WeatherWatch.objects.order_by("-id")[:monitoring]                                                            # Use 300 seconds by default with an iteration every 5 seconds                                                                                     # Get the number of data available
        else:                                                                                                                           
            weather_info = None
        return render(request, 'dashboard/current_weather.html', {'weather_info' : weather_info, 'iteration' : monitoring})
    except Config.DoesNotExist:
        return render(request, 'dashboard/current_weather.html', {'weather_info' : None, 'iteration' : 60})


@login_required
def site(request):
    return render(request, 'dashboard/reload_site.html')                        # return the needed html file

@login_required
def site_current(request):
    try:
        if (len(Config.objects.all()) == 1):
            monitoring = int(int(Config.objects.get(id=1).row_data_save_frequency) / 5)
        else:
            monitoring = 60
        if (len(SiteWatch.objects.all()) > 0):
            site_info = SiteWatch.objects.order_by("-id")[:monitoring]                                                               
        else:                                                                                                                           
            site_info = None
        return render(request, 'dashboard/current_site.html', {'site_info' : site_info, 'iteration' : monitoring})
    except Config.DoesNotExist:
        return render(request, 'dashboard/current_site.html', {'site_info' : None, 'iteration' : 60})

@login_required
def proposal(request):
    if (len(ScientificProgram.objects.all()) > 0):                              # checking if the observatory table is empty
        proposal_info = ScientificProgram.objects.order_by("-id")[:100]         # Sorting Weather table
        nb_info_proposal = len(proposal_info)                                   # Get the number of data available

    else:                                                                       # if empty set everything to 0 / None (variables are checked in src/templates/scheduler/current_weather.html)
        proposal_info = None
        nb_info_proposal = 0

    return render(request, 'dashboard/proposal.html', {'proposal_info' : proposal_info, 'nb_info_proposal' : nb_info_proposal})

@login_required
@superuser_only
def configUpdate(request):
    instance = get_object_or_404(Config, id=1)
    form = ConfigForm(request.POST or None, instance=instance)
    if form.is_valid():
        form.save()
        return redirect('../user_manager/profile')
    return render(request, 'dashboard/configuration.html', {'form': form}) 
    

@login_required
def devices(request):
    url_ = reverse('admin:common_device_changelist')
    return redirect(url_)

@login_required
def system(request):
    return render(request, 'dashboard/system.html')

@login_required
def system_retrieve_logs(request):
    '''
        Called by the dashboard system page with ajax request every seconds, to get the logs and print them
    '''
    if request.is_ajax():
        alert_logs = Log.objects.filter(agent='Alert manager')
        scheduler_logs = Log.objects.filter(agent='Scheduler')
        majordome_logs = Log.objects.filter(agent='Majordome')
        obs_logs = Log.objects.filter(agent='Observation manager')
        analyzer_logs = Log.objects.filter(agent='Analyzer')
        monitoring_logs = Log.objects.filter(agent='Monitoring')
        return render(request, 'dashboard/system_logs.html', locals())


@login_required
def schedule(request):
    url_ = reverse('admin:common_schedule_changelist')
    return redirect(url_)


@login_required
def quotas(request):
    url_ = reverse('admin:common_pyrosuser_changelist')
    return redirect(url_)

@login_required
def change_globalMode(request):
    try :
        config = get_object_or_404(Config, id=1)
        config.global_mode = not config.global_mode
        config.save()
        return redirect('index')
    except Config.DoesNotExist:
        return redirect('index')