Skip to content

Commit

Permalink
removed buttonset for link quality ETX-DBM
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzobracciale committed Jul 28, 2011
2 parents ece8411 + 822644e commit f62a160
Show file tree
Hide file tree
Showing 22 changed files with 388 additions and 79 deletions.
5 changes: 5 additions & 0 deletions .gitignore
@@ -1,4 +1,9 @@
*.pyc
__DOC
nodeshot/migrations
nodeshot.komodoproject
.git_sephiroth6/
monitor.py
settings.py
import_wnmap.py
media/admin
Expand Down
16 changes: 14 additions & 2 deletions media/js/addnode.js
Expand Up @@ -23,6 +23,11 @@ function insertNodeInfo(){
$("#node-form").live("submit", function() {

nodeshotShowLoading();
$('#nodeshot-modal-mask').css({
zIndex: 11,
opacity: 0.7
});
$('#nodeshot-overlay').css('z-index', '10');

var form_data = $(this).serialize();

Expand All @@ -31,8 +36,15 @@ $("#node-form").live("submit", function() {
nodeshotHideLoading();

if (data.length >= 10) {
$('#nodeshot-overlay').html(data); //form errors
} else {
// switch back mask and overlay
$('#nodeshot-modal-mask').css({
zIndex: 10,
opacity: 0.5
});
$('#nodeshot-overlay').css('z-index', '11');
//form errors
$('#nodeshot-overlay').html(data);
} else {
$('#node-form').fadeOut(500, function(){
nodeshotModal('Grazie per aver inserito un nuovo nodo potenziale, ti abbiamo inviato un\'email con il link di conferma.', nodeshotCloseForm);
});
Expand Down
2 changes: 1 addition & 1 deletion media/js/gmap.js
Expand Up @@ -90,7 +90,7 @@ function mapGoTo(nodeName) {
if (marker) {
google.maps.event.trigger(marker, "click");
map.panTo(marker.getPosition());
map.setZoom(15);
map.setZoom(13);
} else {
alert('il nodo non esiste!')
}
Expand Down
82 changes: 78 additions & 4 deletions nodeshot/admin.py
@@ -1,20 +1,94 @@
from django.contrib import admin
from nodeshot.models import *
from nodeshot.models import *
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from forms import AdminPasswordChangeForm

# imports for change password form
from django.contrib import messages
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.html import escape

# Nodeshot specific

class NodeAdmin(admin.ModelAdmin):
list_display = ('name', 'owner', 'status', 'added', 'updated')
list_filter = ('status', 'added', 'updated')
search_fields = ('name', 'owner', 'email', 'postal_code')
save_on_top = True
admin.site.register(Node, NodeAdmin)

fieldsets = (
(None, {'fields': ('status', 'name', 'owner', 'description', 'postal_code', 'email', 'email2', 'email3', 'password', 'lat', 'lng', 'alt' )}),
(_('Avanzate'), {'classes': ('collapse',), 'fields': ('activation_key',)}),
)

# customizations needed for password field
#form = UserChangeForm
change_password_template = None
change_password_form = AdminPasswordChangeForm

def get_urls(self):
from django.conf.urls.defaults import patterns
return patterns('',
(r'^(\d+)/password/$', self.admin_site.admin_view(self.node_change_password))
) + super(NodeAdmin, self).get_urls()

def node_change_password(self, request, id):
if not self.has_change_permission(request):
raise PermissionDenied
node = get_object_or_404(self.model, pk=id)
if request.method == 'POST':
form = self.change_password_form(node, request.POST)
if form.is_valid():
new_node = form.save()
msg = ugettext('Password changed successfully.')
messages.success(request, msg)
return HttpResponseRedirect('..')
else:
form = self.change_password_form(node)

fieldsets = [(None, {'fields': form.base_fields.keys()})]
adminForm = admin.helpers.AdminForm(form, fieldsets, {})

return render_to_response(self.change_password_template or 'admin/auth/user/change_password.html', {
'title': _('Change password: %s') % escape(node.name),
'adminForm': adminForm,
'form': form,
'is_popup': '_popup' in request.REQUEST,
'add': True,
'change': False,
'has_delete_permission': False,
'has_change_permission': True,
'has_absolute_url': False,
'opts': self.model._meta,
'original': node,
'save_as': False,
'show_save': True,
'root_path': self.admin_site.root_path,
}, context_instance=RequestContext(request))

class DeviceAdmin(admin.ModelAdmin):
list_display = ('name', 'node', 'type', 'added', 'updated')
list_filter = ('added', 'updated', 'node')
search_fields = ('name', 'type')
save_on_top = True
admin.site.register(Device, DeviceAdmin)

admin.site.register(Node, NodeAdmin)
admin.site.register(Device, DeviceAdmin)
admin.site.register(Interface)
admin.site.register(HNAv4)
admin.site.register(Link)
admin.site.register(Link)

# UserProfile

class UserProfileInline(admin.StackedInline):
model = UserProfile

class UserProfileAdmin(UserAdmin):
inlines = [UserProfileInline]

admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)
31 changes: 30 additions & 1 deletion nodeshot/forms.py
Expand Up @@ -13,6 +13,7 @@
from django import forms
from settings import DEBUG
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

def node_form(request):
# add css classes
Expand All @@ -39,7 +40,7 @@ def __init__(self, *args, **kwargs):
node = form.save(commit=False)
# save new node in the database (password encryption, activation_key and email notification is done in models.py)
node.save()

# if request is sent with ajax
if request.is_ajax():
# return a blank page with node id
Expand Down Expand Up @@ -152,3 +153,31 @@ def configuration_form(request):
formset = mInlineFormSet(instance=device, prefix=prefix_name)
return render_to_response(template_form, { "formset": formset , 'device_id': device_id , 'configuration_type': entry_type , 'description': device.name } )

class AdminPasswordChangeForm(forms.Form):
"""
A form used to change the password of a node in the admin interface.
"""
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput)

def __init__(self, node, *args, **kwargs):
self.node = node
super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)

def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2:
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2

def save(self, commit=True):
"""
Saves the new password.
"""
self.node.password = self.cleaned_data["password1"]
self.node.set_password()
if commit:
self.node.save()
return self.node
89 changes: 59 additions & 30 deletions nodeshot/models.py
Expand Up @@ -2,12 +2,22 @@
from django.db import models

import random
from django.contrib.auth.utils import make_password
from django.utils.hashcompat import sha_constructor
from django.core.mail import send_mail
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from settings import MANAGERS
from nodeshot.utils import notify_admins

# for UserProfile
from django.contrib.auth.models import User
from django.db.models.signals import post_save

# django > 1.4
try:
from django.contrib.auth.utils import make_password
# django < 1.3
except ImportError:
from nodeshot.utils import make_password

try:
from settings import NODESHOT_ROUTING_PROTOCOLS as ROUTING_PROTOCOLS, NODESHOT_DEFAULT_ROUTING_PROTOCOL as DEFAULT_ROUTING_PROTOCOL
Expand Down Expand Up @@ -140,12 +150,12 @@ class Node(models.Model):
email = models.EmailField()
email2 = models.EmailField(blank=True, null=True)
email3 = models.EmailField(blank=True, null=True)
password = models.CharField(max_length=255)
password = models.CharField(max_length=255, help_text='Per cambiare la password usa il <a href=\"password/\">form di cambio password</a>.')
lat = models.FloatField('latitudine')
lng = models.FloatField('longitudine')
alt = models.FloatField('altitudine', blank=True, null=True)
status = models.CharField('stato', max_length=1, choices=NODE_STATUS, default='p')
activation_key = models.CharField('activation key', max_length=40, blank=True, null=True)
activation_key = models.CharField('activation key', max_length=40, blank=True, null=True, help_text='Chiave per la conferma via mail del nodo. Viene cancellata una volta che il nodo è stato attivato.')
added = models.DateTimeField('aggiunto il', auto_now_add=True)
updated = models.DateTimeField('aggiornato il', auto_now=True)

Expand All @@ -166,7 +176,7 @@ def send_confirmation_mail(self):
context = {
'node': self,
'expiration_days': ACTIVATION_DAYS,
'site': SITE
'site': SITE,
}
# parse subjects
subject = render_to_string('email_notifications/confirmation_subject.txt',context)
Expand All @@ -184,22 +194,25 @@ def send_confirmation_mail(self):
'node': self,
'site': SITE
}
# parse subject
# parse subject (same for both)
subject = render_to_string('email_notifications/notify-added-emals_subject.txt',context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
# parse message
message = render_to_string('email_notifications/notify-added-emals_body.txt',context)
# initialize a list
subject = ''.join(subject.splitlines())
# initialize an empty list
recipient_list = []
# add email2 to the list
if self.email2 != '' and self.email2 != None:
recipient_list += [self.email2]
# add email3 to the list
if self.email3 != '' and self.email3 != None:
recipient_list += [self.email3]
# send mails
send_mail(subject, message, DEFAULT_FROM_EMAIL, recipient_list)
# loop over recipient_list
for recipient in recipient_list:
# insert current email in the body text
context['email'] = recipient
message = render_to_string('email_notifications/notify-added-emals_body.txt',context)
# send mail
send_mail(subject, message, DEFAULT_FROM_EMAIL, (recipient,))

def send_success_mail(self, raw_password):
''' send success emails '''
Expand All @@ -223,24 +236,8 @@ def send_success_mail(self, raw_password):
recipient_list += [self.email3]
# send mail
send_mail(subject, message, DEFAULT_FROM_EMAIL, recipient_list)
# notify all managers that a new node has been added
if(len(MANAGERS)>0):
# prepare list
recipient_list = []
# loop over MANAGERS
for manager in MANAGERS:
# if manager is not one of the owners (avoid emailing twice)
if manager[1] != self.email and manager[1] != self.email2 and manager[1] != self.email3:
# add email of manager to recipient_list
recipient_list += [manager[1]]
# parse subject
subject = render_to_string('email_notifications/new-node-managers_subject.txt',context)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
# parse message
message = render_to_string('email_notifications/new-node-managers_body.txt',context)
# send email
send_mail(subject, message, DEFAULT_FROM_EMAIL, recipient_list)
# notify admins that want to receive notifications
notify_admins(self, 'email_notifications/new-node-admin_subject.txt', 'email_notifications/new-node-admin_body.txt', context, skip=True)

def confirm(self):
'''
Expand Down Expand Up @@ -314,4 +311,36 @@ class Link(models.Model):
dbm = models.IntegerField(default=0)
sync_tx = models.IntegerField(default=0)
sync_rx = models.IntegerField(default=0)

class UserProfile(models.Model):
'''
Extending django's user model so we can have an additional field
where we can specify if admins should receive notifications or not
https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
'''
user = models.OneToOneField(User)
receive_notifications = models.BooleanField('Notifiche via email', help_text='Attiva/disattiva le notifiche email riguardanti la gestione dei nodi (aggiunta, cancellazione, abusi, ecc).')

# signal to notify admins when nodes are deleted
from django.db.models.signals import post_delete
from settings import DEBUG
from datetime import datetime, timedelta

def notify_on_delete(sender, instance, using, **kwargs):
''' Notify admins when nodes are deleted. Only for production use '''
# if in testing modedon't send emails
if DEBUG:
pass #return False
# if purging old unconfirmed nodes don't send emails
if instance.status == 'u' and instance.added + timedelta(days=ACTIVATION_DAYS) < datetime.now():
return False
# prepare context
context = {
'node': instance,
'site': SITE
}
# notify admins that want to receive notifications
notify_admins(instance, 'email_notifications/node-deleted-admin_subject.txt', 'email_notifications/node-deleted-admin_body.txt', context, skip=False)

post_delete.connect(notify_on_delete, sender=Node)
Expand Up @@ -5,4 +5,4 @@ Conferma il tuo nuovo nodo potenziale cliccando sul link seguente {% blocktrans
http://{{ site.domain }}{% url nodeshot_confirm_node node.id node.activation_key %}

Se non hai richiesto l'inserimento di un nuovo nodo potenziale su {{ site.name }} segnala un'abuso cliccando sul link seguente:
http://{{ site.domain }} TODO
http://{{ site.domain }}{% url nodeshot_report_abuse node.id node.email %}
12 changes: 12 additions & 0 deletions nodeshot/templates/email_notifications/new-node-admin_body.txt
@@ -0,0 +1,12 @@
{% load i18n %}Ciao {% if admin.first_name != '' %}{{ admin.first_name }}{% else %}{{ admin.username }}{% endif %},

Un nuovo nodo è stato appena aggiunto su {{ site.name }}.

{% include 'email_notifications/node_details_fragment.txt' %}

Puoi moderare i dettagli del nodo nel backend:
http://{{ site.domain }}{% url admin:nodeshot_node_change node.id %}

Ricevi questa email perchè sei tra gli amministratori del sito {{ site.name }} ed hai scelto di ricevere notifiche riguardanti la gestione dei nodi.
Se non vuoi più ricevere notifiche modifica il tuo profilo in:
http://{{ site.domain }}{% url admin:auth_user_change admin.id %}
@@ -0,0 +1,7 @@
{% load i18n %}Ciao {% if admin.first_name != '' %}{{ admin.first_name }}{% else %}{{ admin.username }}{% endif %},

Il nodo {{ node.name }} è stato appena cancellato da un admin.

Ricevi questa email perchè sei tra gli amministratori del sito {{ site.name }} ed hai scelto di ricevere notifiche riguardanti la gestione dei nodi.
Se non vuoi più ricevere notifiche modifica il tuo profilo in:
http://{{ site.domain }}{% url admin:auth_user_change admin.id %}
@@ -0,0 +1 @@
{% load i18n %}{% trans "Nodo cancellato su " %} {{ site.name }}

0 comments on commit f62a160

Please sign in to comment.