8
0
Fork 0
mirror of https://gitlab2.federez.net/re2o/re2o synced 2024-12-23 15:33:45 +00:00

feat: Create footprint app

This commit is contained in:
Jean-Romain Garnier 2021-12-23 22:49:08 +01:00 committed by jr-garnier
parent efc74fc8d4
commit 855115441f
18 changed files with 779 additions and 0 deletions

0
footprint/__init__.py Normal file
View file

26
footprint/admin.py Normal file
View file

@ -0,0 +1,26 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""
Footprint admin model
"""
from django.contrib import admin
from reversion.admin import VersionAdmin

27
footprint/apps.py Normal file
View file

@ -0,0 +1,27 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
from django.apps import AppConfig
class FootprintConfig(AppConfig):
"""Configuration of the optional footprint app."""
name = "footprint"

29
footprint/forms.py Normal file
View file

@ -0,0 +1,29 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""
Footprint optional app forms
"""
from django import forms
from django.forms import Form, ModelForm
from django.utils.translation import ugettext_lazy as _
from re2o.mixins import FormRevMixin

View file

@ -0,0 +1,116 @@
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
msgid ""
msgstr ""
"Project-Id-Version: 2.5\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-12-23 22:39+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Jean-Romain Garnier <git@jean-romain.com>\n"
"Language-Team: \n"
"Language: fr_FR\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: footprint/preferences/models.py:38
#: footprint/templates/footprint/preferences.html:44
msgid "Estimated monthly infrastructure emissions"
msgstr "Estimation des émissions mensuelles de l'infrastructure"
#: footprint/preferences/models.py:47
#: footprint/templates/footprint/preferences.html:55
msgid "User monthly data usage estimation script"
msgstr "Script d'estimation du volume de données mensuelles d'un utilisateur "
#: footprint/preferences/models.py:52
msgid "Estimation script timeout (in seconds)"
msgstr ""
"Temps imparti pour le script d'estimation de volume de données (en secondes)"
#: footprint/preferences/models.py:59
msgid "Footprint preferences"
msgstr "Préférences d'empreinte"
#: footprint/templates/footprint/aff_profil.html:29
#: footprint/templates/footprint/preferences.html:29
msgid "Footprint"
msgstr "Empreinte"
#: footprint/templates/footprint/aff_profil.html:38
msgid "Estimated monthly emissions"
msgstr "Estimation des émissions mensuelles"
#: footprint/templates/footprint/aff_profil.html:41
#: footprint/templates/footprint/aff_profil.html:55
msgid "n/a"
msgstr "n/a"
#: footprint/templates/footprint/aff_profil.html:43
msgid "Unavailable"
msgstr "Indisponible"
#: footprint/templates/footprint/aff_profil.html:45
#: footprint/templates/footprint/preferences.html:49
msgid "kgCO₂e/month"
msgstr "kgCO₂e/mois"
#: footprint/templates/footprint/aff_profil.html:48
#: footprint/templates/footprint/aff_profil.html:60
msgid "[Learn more]"
msgstr "[En savoir plus]"
#: footprint/templates/footprint/aff_profil.html:52
msgid "Estimated monthly data usage"
msgstr "Estimation du volume de données mensuel"
#: footprint/templates/footprint/aff_profil.html:57
msgid "Compute"
msgstr "Calculer"
#: footprint/templates/footprint/aff_profil.html:81
msgid "GiB/month"
msgstr "GiO/mois"
#: footprint/templates/footprint/aff_profil.html:83
msgid "Unknown error"
msgstr "Erreur inconnue"
#: footprint/templates/footprint/preferences.html:36
msgid "Edit"
msgstr "Modifier"
#: footprint/templates/footprint/preferences.html:47
msgid "Not specified"
msgstr "Non spécifié"
#: footprint/templates/footprint/preferences.html:60
msgid "Data estimation script timeout (in seconds)"
msgstr ""
"Temps imparti pour le script d'estimation de volume de données (en secondes)"
#: footprint/views.py:45
msgid "Nonexistent user."
msgstr "Utilisateur inconnu"
#: footprint/views.py:50
msgid "Failed to compute data usage."
msgstr "Échec du calcul du volume de données."

View file

@ -0,0 +1,29 @@
# Generated by Django 2.2.18 on 2021-12-23 21:44
import django.core.validators
from django.db import migrations, models
import re2o.mixins
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='FootprintOption',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('monthly_infra_emissions', models.DecimalField(blank=True, decimal_places=2, default=None, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0)], verbose_name='Estimated monthly infrastructure emissions')),
('data_usage_script_path', models.CharField(default='footprint/scripts/default_data_usage_estimator.py', max_length=4096, verbose_name='User monthly data usage estimation script')),
('data_usage_script_timeout', models.DecimalField(decimal_places=2, default=10, max_digits=4, verbose_name='Estimation script timeout (in seconds)')),
],
options={
'verbose_name': 'Footprint preferences',
},
bases=(re2o.mixins.AclMixin, models.Model),
),
]

View file

31
footprint/models.py Normal file
View file

@ -0,0 +1,31 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""
Footprint optional app models
"""
from __future__ import absolute_import
from django.db import models
from django.utils.translation import ugettext_lazy as _
from preferences.models import PreferencesModel
from re2o.mixins import AclMixin, RevMixin

View file

View file

@ -0,0 +1,33 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2019 Gabriel Détraz
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
from django import forms
from django.forms import Form, ModelForm
from django.utils.translation import ugettext_lazy as _
from .models import FootprintOption
class EditFootprintOptionForm(ModelForm):
"""Form used to edit the settings of the footprint optional app."""
class Meta:
model = FootprintOption
fields = "__all__"

View file

@ -0,0 +1,59 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2019 Gabriel Détraz
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""
footprint optional app preferences model
"""
from django.db import models
from django.core.validators import MinValueValidator
from django.utils.translation import ugettext_lazy as _
from preferences.models import PreferencesModel
from re2o.mixins import AclMixin, RevMixin
class FootprintOption(AclMixin, PreferencesModel):
"""Definition of the settings of the footprint app."""
# https://www.ademe.fr/expertises/consommer-autrement/passer-a-laction/reconnaitre-produit-plus-respectueux-lenvironnement/dossier/laffichage-environnemental/affichage-environnemental-secteur-numerique
monthly_infra_emissions = models.DecimalField(
verbose_name=_("Estimated monthly infrastructure emissions"),
max_digits=10,
decimal_places=2,
null=True,
blank=True,
default=None,
validators=[MinValueValidator(0)],
)
data_usage_script_path = models.CharField(
verbose_name=_("User monthly data usage estimation script"),
default="footprint/scripts/default_data_usage_estimator.py",
max_length=4096,
)
data_usage_script_timeout = models.DecimalField(
verbose_name=_("Estimation script timeout (in seconds)"),
max_digits=4,
decimal_places=2,
default=10,
)
class Meta:
verbose_name = _("Footprint preferences")

View file

@ -0,0 +1,48 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.translation import ugettext as _
from preferences.views import edit_options_template_function
from re2o.acl import can_create, can_edit, can_view, can_view_all
from re2o.base import re2o_paginator
from . import forms, models
def aff_preferences(request):
"""View used to display the settings of the footprint app in the preferences page."""
pref, _ = models.FootprintOption.objects.get_or_create()
context = {
"preferences": pref,
}
return render_to_string(
"footprint/preferences.html", context=context, request=request, using=None
)
@login_required
def edit_options(request, section):
return edit_options_template_function(request, section, forms, models)

View file

@ -0,0 +1,35 @@
#!/usr/bin/env python3
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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 sys
def main(user_id: int) -> float:
return None
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: ./default_data_usage_estimator.py <re2o user id>")
exit(1)
usage = main(sys.argv[1])
print(usage)

View file

@ -0,0 +1,97 @@
{% comment %}
Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
se veut agnostique au réseau considéré, de manière à être installable en
quelques clics.
Copyright © 2021 Jean-Romain Garnier
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; either version 2 of the License, or
(at your option) any later version.
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.
{% endcomment %}
{% load acl %}
{% load i18n %}
<div class="panel panel-default">
<div class="panel-heading clearfix profil" data-parent="#accordion" data-toggle="collapse" data-target="#footprint">
<h3 class="panel-title pull-left">
<i class="fa fa-leaf"></i> {% trans "Footprint" %}
</h3>
</div>
<div id="footprint" class="panel-collapse collapse">
<div class="panel-body">
<div class="table-responsive">
<table class="table">
<tr>
<th>{% trans "Estimated monthly emissions" %}</th>
{% if not user.has_access %}
<td>{% trans "n/a" %}</td>
{% elif monthly_emissions is None %}
<td>{% trans "Unavailable" %}</td>
{% else %}
<td>{{ monthly_emissions }} {% trans "kgCO₂e/month" %}</td>
{% endif %}
<td><a target="_blank" rel="noreferrer noopener" href="https://www.ademe.fr/expertises/consommer-autrement/passer-a-laction/reconnaitre-produit-plus-respectueux-lenvironnement/dossier/laffichage-environnemental/affichage-environnemental-secteur-numerique">{% trans "[Learn more]" %}</a></td>
</tr>
<tr>
<th>{% trans "Estimated monthly data usage" %}</th>
{% if not user.has_access %}
<td>{% trans "n/a" %}</td>
{% else %}
<td id="data_usage_estimate"><a href="javascript:get_data_usage_estimate()">{% trans "Compute" %}</a></td>
{% endif %}
<td><a target="_blank" rel="noreferrer noopener" href="https://www.ademe.fr/expertises/consommer-autrement/passer-a-laction/reconnaitre-produit-plus-respectueux-lenvironnement/dossier/laffichage-environnemental/affichage-environnemental-secteur-numerique">{% trans "[Learn more]" %}</a></td>
</tr>
</table>
</div>
</div>
</div>
<script>
function get_data_usage_estimate() {
td = document.getElementById("data_usage_estimate");
td.innerHTML = "<progress></progress>"
$.ajax({
url: "{% url 'footprint:data-usage-estimate' user.id %}",
type: "get",
dataType: "json",
success: function(data) {
if (data["error"] != null) {
td.innerHTML = "<i class=\"text-danger\">" + data["error"] + "</i>";
td.style.color = "red";
} else if (data["data"] != null) {
td.innerHTML = data["data"] + " {% trans 'GiB/month' %}";
} else {
td.innerHTML = "<i class=\"text-danger\">{% trans 'Unknown error' %}</i>";
}
},
error: function(xhr, errmsg, err) {
td.innerHTML = "<i class=\"text-danger\">" + errmsg + "</i>";
}
});
}
/*$(document).ready(function() {
$("#data_usage_estimate_action").href(function() {
});
});*/
</script>
</div>

View file

@ -0,0 +1,66 @@
{% comment %}
Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
se veut agnostique au réseau considéré, de manière à être installable en
quelques clics.
Copyright © 2021 Jean-Romain Garnier
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; either version 2 of the License, or
(at your option) any later version.
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.
{% endcomment %}
{% load design %}
{% load i18n %}
<div class="panel panel-default" id="footprint">
<div class="panel-heading" data-toggle="collapse" href="#collapse_footprint">
<h4 class="panel-title">
<a><i class="fa fa-leaf"></i> {% trans "Footprint" %}</a>
</h4>
</div>
<div id="collapse_footprint" class="panel-collapse panel-body collapse">
<a class="btn btn-primary btn-sm" role="button" href="{% url 'footprint:edit-options' 'FootprintOption' %}">
<i class="fa fa-edit"></i>
{% trans "Edit" %}
</a>
<p></p>
<div class="table-responsive">
<table class="table">
<tr>
<th><p>{% trans "Estimated monthly infrastructure emissions" %}</p></th>
{% if preferences.monthly_infra_emissions is None %}
<td><p>{% trans "Not specified" %}</p></td>
{% else %}
<td><p>{{ preferences.monthly_infra_emissions }} {% trans "kgCO₂e/month" %}</p></td>
{% endif %}
</tr>
<tr>
<th><p>{% trans "User monthly data usage estimation script" %}</p></th>
<td><p>{{ preferences.data_usage_script_path }}</p></td>
</tr>
<tr>
<th><p>{% trans "Data estimation script timeout (in seconds)" %}</p></th>
<td><p>{{ preferences.data_usage_script_timeout }}</p></td>
</tr>
</table>
</div>
</div>

43
footprint/urls.py Normal file
View file

@ -0,0 +1,43 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""
Footprint optional app urls
"""
from django.urls import path, re_path
from . import views
from .preferences.views import edit_options
app_name = "footprint"
urlpatterns = [
re_path(
r"^edit_options/(?P<section>FootprintOption)$",
edit_options,
name="edit-options",
),
path(
"data_usage_estimate/<int:userid>",
views.get_data_usage_estimate,
name="data-usage-estimate",
),
]

73
footprint/utils.py Normal file
View file

@ -0,0 +1,73 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""
Footprint optional app utils
"""
import os
import pathlib
import subprocess
from django.contrib import messages
from django.utils.translation import ugettext as _
from re2o.utils import all_has_access
from .preferences.models import FootprintOption
def get_user_monthly_emissions(request, user):
if not user.has_access:
return None
monthly_infra_emissions = FootprintOption.get_cached_value(
"monthly_infra_emissions"
)
if monthly_infra_emissions is None:
return None
user_count = all_has_access(including_asso=False).count()
return monthly_infra_emissions / max(user_count, 1)
def get_user_monthly_data_usage(request, user):
if not user.has_access:
return None
data_usage_script_path = FootprintOption.get_cached_value("data_usage_script_path")
if data_usage_script_path is None:
return None
script_path = pathlib.Path(data_usage_script_path)
if not script_path.is_absolute():
re2o_base_path = pathlib.Path(__file__).parent.parent.resolve()
script_path = re2o_base_path / script_path
timeout = float(FootprintOption.get_cached_value("data_usage_script_timeout"))
cmd = [script_path, str(user.id)]
out = subprocess.check_output(cmd, timeout=timeout).decode("utf-8").strip()
if out == "None":
out = None
else:
out = float(out)
return out

67
footprint/views.py Normal file
View file

@ -0,0 +1,67 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au Rézo Metz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2021 Jean-Romain Garnier
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
"""
Footprint optional app views
"""
from django.contrib.auth.decorators import login_required
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.http import JsonResponse
from users.models import User
from re2o.acl import can_view
from .utils import get_user_monthly_emissions, get_user_monthly_data_usage
@login_required
@can_view(User)
def get_data_usage_estimate(request, user, userid):
"""View used to compute a user's estimated data usage."""
data = None
error = None
try:
user_req = User.objects.get(pk=userid)
except User.DoesNotExist:
return JsonResponse({"data": None, "error": _("Nonexistent user.")})
try:
data = get_user_monthly_data_usage(request, user_req)
except Exception:
return JsonResponse({"data": None, "error": _("Failed to compute data usage.")})
return JsonResponse({"data": data, "error": None})
# Canonic views for optional apps
def aff_profil(request, user):
"""View used to display the footprint on a user's profile."""
monthly_emissions = get_user_monthly_emissions(request, user)
context = {
"user": user,
"monthly_emissions": monthly_emissions,
}
return render_to_string(
"footprint/aff_profil.html", context=context, request=request, using=None
)