1 # -*- coding: utf-8 -*-
3 # portal/views.py: views for the portal application
4 # This file is part of the Manifold project.
7 # Jordan Augé <jordan.auge@lip6.fr>
8 # Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
9 # Copyright 2013, UPMC Sorbonne Universités / LIP6
11 # This program is free software; you can redistribute it and/or modify it under
12 # the terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 3, or (at your option) any later version.
15 # This program is distributed in the hope that it will be useful, but WITHOUT
16 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 # You should have received a copy of the GNU General Public License along with
21 # this program; see the file COPYING. If not, write to the Free Software
22 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 from django.conf import settings
25 from django.contrib.sites.models import Site, RequestSite
26 from django.contrib import messages
27 from django.views.generic import View
28 from django.views.generic.base import TemplateView
29 from django.shortcuts import render
31 from plugins.lists.simplelist import SimpleList
33 from plugins.pres_view import PresView
34 from portal.event import Event
37 from portal import signals
38 from portal.forms import UserRegisterForm, SliceRequestForm, ContactForm
39 from portal.util import RegistrationView, ActivationView
40 from portal.models import PendingUser, PendingSlice
41 from manifold.core.query import Query
42 from unfold.page import Page
43 from myslice.viewutils import topmenu_items, the_user
44 from django.http import HttpResponseRedirect, HttpResponse
47 class DashboardView(TemplateView):
48 template_name = "dashboard.html"
50 def get_context_data(self, **kwargs):
51 # We might have slices on different registries with different user accounts
52 # We note that this portal could be specific to a given registry, to which we register users, but i'm not sure that simplifies things
53 # Different registries mean different identities, unless we identify via SFA HRN or have associated the user email to a single hrn
55 #messages.info(self.request, 'You have logged in')
56 page = Page(self.request)
59 #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
60 slice_query = Query().get('user').filter_by('user_hrn', '==', '$user_hrn').select('user_hrn', 'slice.slice_hrn')
61 auth_query = Query().get('network').select('network_hrn')
62 page.enqueue_query(slice_query)
63 page.enqueue_query(auth_query)
65 page.expose_js_metadata()
68 slicelist = SimpleList(
71 key = 'slice.slice_hrn',
75 authlist = SimpleList(
82 context = super(DashboardView, self).get_context_data(**kwargs)
83 context['person'] = self.request.user
84 context['networks'] = authlist.render(self.request)
85 context['slices'] = slicelist.render(self.request)
87 # XXX This is repeated in all pages
88 # more general variables expected in the template
89 context['title'] = 'Test view that combines various plugins'
90 # the menu items on the top
91 context['topmenu_items'] = topmenu_items('Dashboard', self.request)
92 # so we can sho who is logged
93 context['username'] = the_user(self.request)
95 context.update(page.prelude_env())
99 class UserRegisterView(RegistrationView):
101 A registration backend which follows a simple workflow:
103 1. User signs up, inactive account is created.
105 2. Email is sent to user with activation link.
107 3. User clicks activation link, account is now active.
109 Using this backend requires that
111 * ``registration`` be listed in the ``INSTALLED_APPS`` setting
112 (since this backend makes use of models defined in this
115 * The setting ``ACCOUNT_ACTIVATION_DAYS`` be supplied, specifying
116 (as an integer) the number of days from registration during
117 which a user may activate their account (after that period
118 expires, activation will be disallowed).
120 * The creation of the templates
121 ``registration/activation_email_subject.txt`` and
122 ``registration/activation_email.txt``, which will be used for
123 the activation email. See the notes for this backends
124 ``register`` method for details regarding these templates.
126 Additionally, registration can be temporarily closed by adding the
127 setting ``REGISTRATION_OPEN`` and setting it to
128 ``False``. Omitting this setting, or setting it to ``True``, will
129 be interpreted as meaning that registration is currently open and
132 Internally, this is accomplished via storing an activation key in
133 an instance of ``registration.models.RegistrationProfile``. See
134 that model and its custom manager for full documentation of its
135 fields and supported operations.
138 form_class = UserRegisterForm
140 def register(self, request, **cleaned_data):
142 Given a username, email address and password, register a new
143 user account, which will initially be inactive.
145 Along with the new ``User`` object, a new
146 ``registration.models.RegistrationProfile`` will be created,
147 tied to that ``User``, containing the activation key which
148 will be used for this account.
150 An email will be sent to the supplied email address; this
151 email should contain an activation link. The email will be
152 rendered using two templates. See the documentation for
153 ``RegistrationProfile.send_activation_email()`` for
154 information about these templates and the contexts provided to
157 After the ``User`` and ``RegistrationProfile`` are created and
158 the activation email is sent, the signal
159 ``registration.signals.user_registered`` will be sent, with
160 the new ``User`` as the keyword argument ``user`` and the
161 class of this backend as the sender.
164 first_name = cleaned_data['first_name']
165 last_name = cleaned_data['last_name']
166 affiliation= cleaned_data['affiliation']
167 email = cleaned_data['email']
168 password = cleaned_data['password1']
170 #password2 = cleaned_data['password2']
171 keypair = cleaned_data['keypair']
173 #if Site._meta.installed:
174 # site = Site.objects.get_current()
176 # site = RequestSite(request)
179 new_user = PendingUser.objects.create_inactive_user(first_name, last_name, email, password, site)
180 signals.user_registered.send(sender=self.__class__,
185 def get_context_data(self, **kwargs):
186 context = super(UserRegisterView, self).get_context_data(**kwargs)
187 context['topmenu_items'] = topmenu_items('Register', self.request)
188 context['username'] = the_user (self.request)
191 def registration_allowed(self, request):
193 Indicate whether account registration is currently permitted,
194 based on the value of the setting ``REGISTRATION_OPEN``. This
195 is determined as follows:
197 * If ``REGISTRATION_OPEN`` is not specified in settings, or is
198 set to ``True``, registration is permitted.
200 * If ``REGISTRATION_OPEN`` is both specified and set to
201 ``False``, registration is not permitted.
204 return getattr(settings, 'REGISTRATION_OPEN', True)
206 def get_success_url(self, request, user):
208 Return the name of the URL to redirect to after successful
212 return ('user_register_complete', (), {})
215 class UserValidateView(ActivationView):
216 def activate(self, request, activation_key):
218 Given an an activation key, look up and activate the user
219 account corresponding to that key (if possible).
221 After successful activation, the signal
222 ``registration.signals.user_activated`` will be sent, with the
223 newly activated ``User`` as the keyword argument ``user`` and
224 the class of this backend as the sender.
227 activated_user = RegistrationProfile.objects.activate_user(activation_key)
229 signals.user_activated.send(sender=self.__class__,
232 return activated_user
234 def get_success_url(self, request, user):
235 return ('registration_activation_complete', (), {})
238 # DEPRECATED #from portal.portalpage import PortalPage
239 # DEPRECATED #from plugins.wizard import Wizard
240 # DEPRECATED #from plugins.form import CreateForm
241 # DEPRECATED #from plugins.raw.raw import Raw # XXX
243 # DEPRECATED #from myslice.viewutils import the_user
245 # DEPRECATED #from django.template.loader import render_to_string
246 # DEPRECATED #from django.template import RequestContext
247 # DEPRECATED #from django.views import generic
249 # DEPRECATED #from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView
250 # DEPRECATED ##from django.core.files.storage import FileSystemStorage
251 # DEPRECATED #from django.core.files.storage import default_storage
253 # DEPRECATED ##class MerlinWizard(NamedUrlSessionWizardView):
258 # DEPRECATED ## @classonlymethod
259 # DEPRECATED ## def as_view(cls, *args, **kwargs):
260 # DEPRECATED ## kwargs.update({
261 # DEPRECATED ## 'form_list': [
262 # DEPRECATED ## NameForm,
263 # DEPRECATED ## QuestForm,
264 # DEPRECATED ## ColorForm,
266 # DEPRECATED ## 'url_name': 'merlin_wizard'
268 # DEPRECATED ## return super(MerlinWizard, cls).as_view(*args, **kwargs)
270 # DEPRECATED #class UserRegisterWizardView(NamedUrlSessionWizardView):
271 # DEPRECATED ##class UserRegisterWizardView(LoginRequiredMixin, NamedUrlSessionWizardView):
272 # DEPRECATED # # Notice that I specify a file storage instance. If you don't specify this,
273 # DEPRECATED # # and you need to support FileField or ImageField in your forms, you'll get
274 # DEPRECATED # # errors from Django. This is something else I think could be handled by
275 # DEPRECATED # # the views better. Seems to me that it should just use whatever the
276 # DEPRECATED # # default/specified storage is for the rest of your project/application.
277 # DEPRECATED # file_storage = default_storage # FileSystemStorage()
278 # DEPRECATED # template_name = "register_user_wizard.html"
280 # DEPRECATED # def done(self, form_list, **kwargs):
281 # DEPRECATED # step1_form = form_list[0]
282 # DEPRECATED # step2_form = form_list[1]
284 # DEPRECATED # productext = self.create_product(product_form)
285 # DEPRECATED # shippings = self.create_shippings(productext, shipping_forms)
286 # DEPRECATED # images = self.create_images(productext, image_forms)
288 # DEPRECATED # if all([productext, shippings, images]):
289 # DEPRECATED # del self.request.session["wizard_product_wizard_view"]
291 # DEPRECATED # messages.success(self.request,
292 # DEPRECATED # _("Your product has been created."))
293 # DEPRECATED # return HttpResponseRedirect(self.get_success_url(productext))
295 # DEPRECATED # messages.error(self.request, _("Something went wrong creating your "
296 # DEPRECATED # "product. Please try again or contact support."))
297 # DEPRECATED # return HttpResponseRedirect(reverse("register_wizard"))
299 # DEPRECATED # #def get_form_kwargs(self, step):
300 # DEPRECATED # # if step == "product":
301 # DEPRECATED # # return {"user": self.request.user}
302 # DEPRECATED # # return {}
304 # DEPRECATED ## The portal should hook the slice and user creation pages
306 # DEPRECATED #def register_user(request):
308 # DEPRECATED # if request.method == 'POST':
309 # DEPRECATED # form = UserRegisterForm(request.POST) # Nous reprenons les données
310 # DEPRECATED # if form.is_valid():
311 # DEPRECATED # first_name = form.cleaned_data['first_name']
312 # DEPRECATED # last_name = form.cleaned_data['last_name']
313 # DEPRECATED # email = form.cleaned_data['email']
314 # DEPRECATED # password = form.cleaned_data['password']
315 # DEPRECATED # password2 = form.cleaned_data['password2']
316 # DEPRECATED # keypair = form.cleaned_data['keypair']
317 # DEPRECATED # ## Ici nous pouvons traiter les données du formulaire
318 # DEPRECATED # #sujet = form.cleaned_data['sujet']
319 # DEPRECATED # #message = form.cleaned_data['message']
320 # DEPRECATED # #envoyeur = form.cleaned_data['envoyeur']
321 # DEPRECATED # #renvoi = form.cleaned_data['renvoi']
322 # DEPRECATED # ## Nous pourrions ici envoyer l'e-mail grâce aux données que nous venons de récupérer
323 # DEPRECATED # #envoi = True
325 # DEPRECATED # form = UserRegisterForm()
326 # DEPRECATED # return render(request, 'register_user.html', locals())
328 # DEPRECATED #def index(request):
330 # DEPRECATED # WIZARD_TITLE = 'User registration'
331 # DEPRECATED # STEP1_TITLE = 'Enter your details'
332 # DEPRECATED # STEP2_TITLE = 'Select your institution'
333 # DEPRECATED # STEP3_TITLE = 'Authentication'
334 # DEPRECATED # STEP4_TITLE = 'Request a slice (optional)'
335 # DEPRECATED # STEP5_TITLE = 'Waiting for validation'
336 # DEPRECATED # STEP6_TITLE = 'Account validated'
338 # DEPRECATED # STEP0 = render_to_string('account_validated.html', context_instance=RequestContext(request))
339 # DEPRECATED # STEP2_HTML = """
340 # DEPRECATED # coucou
342 # DEPRECATED # STEP4 = """
345 # DEPRECATED # STEP5 = render_to_string('account_validated.html', context_instance=RequestContext(request))
347 # DEPRECATED # p = PortalPage(request)
349 # DEPRECATED # # This is redundant with the Wizard title
350 # DEPRECATED # p << "<h3>User registration</h3>"
352 # DEPRECATED # sons = []
353 # DEPRECATED # start_step = 1
355 # DEPRECATED # # STEP 1
356 # DEPRECATED # # If the user already exists (is logged), let's display a summary of his account details
357 # DEPRECATED # # Otherwise propose a form to fill in
358 # DEPRECATED # if the_user(request):
359 # DEPRECATED # # Fill a disabled form with user info
360 # DEPRECATED # # Please logout to register another user
361 # DEPRECATED # sons.append(Raw(page=p, title=STEP1_TITLE, togglable=False, html=STEP0))
362 # DEPRECATED # start_step += 1
364 # DEPRECATED # # We could pass a list of fields also, instead of retrieving them from metadata
365 # DEPRECATED # # Otherwise we need some heuristics to display nice forms
366 # DEPRECATED # # XXX Could we log the user in after the form is validated ?
367 # DEPRECATED # # XXX Explain the password is for XXX
368 # DEPRECATED # field_list = [{
369 # DEPRECATED # 'name' : 'First name',
370 # DEPRECATED # 'field' : 'firstname',
371 # DEPRECATED # 'type' : 'text',
372 # DEPRECATED # 'validate_rx' : '^[a-zA-Z -]+$',
373 # DEPRECATED # 'validate_err': 'Your first name must be comprised of letters only',
374 # DEPRECATED # 'description' : 'Enter your first name',
376 # DEPRECATED # 'name' : 'Last name',
377 # DEPRECATED # 'field' : 'lastname',
378 # DEPRECATED # 'type' : 'text',
379 # DEPRECATED # 'validate_rx' : '^[a-zA-Z -]+$',
380 # DEPRECATED # 'validate_err': 'Your last name must be comprised of letters only',
381 # DEPRECATED # 'description' : 'Enter your last name',
383 # DEPRECATED # 'name' : 'Email',
384 # DEPRECATED # 'field' : 'email',
385 # DEPRECATED # 'type' : 'text',
386 # DEPRECATED # 'description' : 'Enter your email address',
388 # DEPRECATED # 'name' : 'Password',
389 # DEPRECATED # 'field' : 'password',
390 # DEPRECATED # 'type' : 'password',
391 # DEPRECATED # 'description' : 'Enter your password',
393 # DEPRECATED # 'name' : 'Confirm password',
394 # DEPRECATED # 'field' : 'password2',
395 # DEPRECATED # 'type' : 'password',
396 # DEPRECATED # 'description' : 'Enter your password again',
398 # DEPRECATED # sons.append(CreateForm(page = p, title = STEP1_TITLE, togglable = False, object = 'local:user', fields = field_list))
400 # DEPRECATED # # STEP 2
401 # DEPRECATED # # If the user already exists (is logged), let's display a summary of its institution
402 # DEPRECATED # # Otherwise propose a form to fill in (we should base our selection on the email)
403 # DEPRECATED # if the_user(request):
404 # DEPRECATED # # Fill a disabled form with institution
405 # DEPRECATED # # Please logout to register another user
406 # DEPRECATED # sons.append(Raw(page=p, title=STEP2_TITLE, togglable=False, html="User created"))
407 # DEPRECATED # start_step += 1
409 # DEPRECATED # sons.append(CreateForm(page = p, title = STEP2_TITLE, togglable = False, object = 'slice')) #institution'))
411 # DEPRECATED # # STEP3
412 # DEPRECATED # # Please should your prefered authentication method
413 # DEPRECATED # # This step should allow the user to either choose the user or managed mode in MySlice
414 # DEPRECATED # sons.append(Raw(page = p, title = STEP3_TITLE, togglable = False, html = STEP2_HTML))
416 # DEPRECATED # # Step 4: Request a slice (optional)
417 # DEPRECATED # sons.append(CreateForm(page = p, title = STEP4_TITLE, togglable = False, object = 'slice'))
419 # DEPRECATED # # Step 5: Your request is waiting for validation
420 # DEPRECATED # # Periodic refresh
421 # DEPRECATED # sons.append(Raw(page = p, title = STEP5_TITLE, togglable = False, html = STEP4))
423 # DEPRECATED # # Step 6: Account validation = welcome for newly validated users
424 # DEPRECATED # # . delegation
425 # DEPRECATED # # . platforms
426 # DEPRECATED # # . slice
427 # DEPRECATED # # . pointers
428 # DEPRECATED # sons.append(Raw(page = p, title = STEP6_TITLE, togglable = False, html = STEP5))
430 # DEPRECATED # wizard = Wizard(
431 # DEPRECATED # page = p,
432 # DEPRECATED # title = WIZARD_TITLE,
433 # DEPRECATED # togglable = False,
434 # DEPRECATED # sons = sons,
435 # DEPRECATED # start_step = start_step,
438 # DEPRECATED # p << wizard.render(request) # in portal page if possible
440 # DEPRECATED # return p.render()
443 # DEPRECATED ## view for my_account
444 # DEPRECATED # class MyAccountView(TemplateView):
445 # DEPRECATED # template_name = "my_account.html"
447 # DEPRECATED # def from_process(self, request, **cleaned_data):
448 # DEPRECATED # #if request.method == 'POST':
449 # DEPRECATED # # if request.POST['submit_name']:
450 # DEPRECATED # if 'fname' in request.POST:
451 # DEPRECATED # messsag= "Got Name"
452 # DEPRECATED # #return render(request, 'portal/my_account.html')
453 # DEPRECATED # #response = HttpResponse("Here's the text of the Web page.")
454 # DEPRECATED # return HttpResponse(message)
456 # DEPRECATED # def get_context_data(self, **kwargs):
457 # DEPRECATED # page = Page(self.request)
458 # DEPRECATED # context = super(MyAccountView, self).get_context_data(**kwargs)
459 # DEPRECATED # context['person'] = self.request.user
460 # DEPRECATED # # XXX This is repeated in all pages
461 # DEPRECATED # # more general variables expected in the template
462 # DEPRECATED # context['title'] = 'User Profile Page'
463 # DEPRECATED # # the menu items on the top
464 # DEPRECATED # context['topmenu_items'] = topmenu_items('my_account', self.request)
465 # DEPRECATED # # so we can sho who is logged
466 # DEPRECATED # context['username'] = the_user(self.request)
467 # DEPRECATED # context.update(page.prelude_env())
468 # DEPRECATED # return context
472 # View for my_account form
473 def my_account(request):
474 return render(request, 'my_account.html')
476 #my_acc form value processing
477 def acc_process(request):
478 # getting the user_id from the session [now hardcoded]
479 get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
480 if 'submit_name' in request.POST:
481 edited_first_name = request.POST['fname']
482 edited_last_name = request.POST['lname']
483 #email = 'test_email@gmail.com'
484 #password = 'test_pp'
485 #message = 'F_Name: %s L_name: %s dummy_pp: %s' % (first_name, last_name, password)
488 # insert into DB [needed for registration page]
489 #approach borrowed from register view
490 #new_user = PendingUser.objects.create_inactive_user(edited_first_name, edited_last_name, email, password, site)
491 #conventional approach
492 #b = PendingUser(first_name=edited_first_name, last_name=edited_last_name)
495 # select and update [will be used throughout this view]
496 # select the logged in user [for the moment hard coded]
497 #get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
498 # update first and last name
499 get_user.first_name = edited_first_name
500 get_user.last_name = edited_last_name
503 return HttpResponse('Success: Name Updated!!')
504 elif 'submit_pass' in request.POST:
505 edited_password = request.POST['password']
506 # select the logged in user [for the moment hard coded]
507 #get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
509 get_user.password = edited_password
511 return HttpResponse('Success: Password Changed!!')
512 elif 'generate' in request.POST:
514 from M2Crypto import Rand, RSA, BIO
518 def blank_callback():
519 "Replace the default dashes"
523 Rand.rand_seed (os.urandom (KEY_LENGTH))
525 key = RSA.gen_key (KEY_LENGTH, 65537, blank_callback)
526 # Create memory buffers
527 pri_mem = BIO.MemoryBuffer()
528 pub_mem = BIO.MemoryBuffer()
529 # Save keys to buffers
530 key.save_key_bio(pri_mem, None)
531 key.save_pub_key_bio(pub_mem)
534 public_key = pub_mem.getvalue()
535 private_key = pri_mem.getvalue()
537 keypair = '{"user_public_key":"'+ public_key + '", "user_private_key":"'+ private_key + '"}'
538 #keypair = re.sub("\r", "", keypair)
539 #keypair = re.sub("\n", "\\n", keypair)
540 keypair = keypair.rstrip('\r\n')
541 get_user.keypair = keypair
543 return HttpResponse('Success: New Keypair Generated! %s' % keypair)
545 elif 'upload_key' in request.POST:
546 up_file = request.FILES['pubkey']
547 file_content = up_file.read()
548 file_name = up_file.name
549 file_extension = os.path.splitext(file_name)[1]
550 allowed_extension = ['.pub','.txt']
551 if file_extension in allowed_extension:
552 file_content = '{"user_public_key":"'+ file_content +'"}'
553 file_content = re.sub("\r", "", file_content)
554 file_content = re.sub("\n", "\\n",file_content)
555 get_user.keypair = file_content
557 return HttpResponse('Success: Publickey uploaded! Old records overwritten')
559 return HttpResponse('Please upload a valid public key.')
562 message = 'You submitted an empty form.'
563 return HttpResponse(message)
565 def register_4m_f4f(request):
566 return render(request, 'register_4m_f4f.html')
568 def reg_4m_f4f_process(request):
569 if 'submit' in request.POST:
570 return HttpResponse('Registration Successful. Please wait for account validation')
574 # view for contact form
575 def contact(request):
576 if request.method == 'POST': # If the form has been submitted...
577 form = ContactForm(request.POST) # A form bound to the POST data
578 if form.is_valid(): # All validation rules pass
579 # Process the data in form.cleaned_data
580 first_name = form.cleaned_data['first_name']
581 last_name = form.cleaned_data['last_name']
582 affiliation = form.cleaned_data['affiliation']
583 subject = form.cleaned_data['subject']
584 message = form.cleaned_data['message']
585 email = form.cleaned_data['email'] # email of the sender
586 cc_myself = form.cleaned_data['cc_myself']
588 recipients = ['yasin.upmc@gmail.com']
590 recipients.append(email)
592 from django.core.mail import send_mail
593 send_mail("Onelab user submitted a query ", [first_name,last_name,affiliation,subject,message], email, recipients)
594 return render(request,'contact_sent.html') # Redirect after POST
596 form = ContactForm() # An unbound form
598 return render(request, 'contact.html', {
603 def slice_request(request):
604 if request.method == 'POST': # If the form has been submitted...
605 form = SliceRequestForm(request.POST) # A form bound to the POST data
606 if form.is_valid(): # All validation rules pass
607 # Process the data in form.cleaned_data
608 slice_name = form.cleaned_data['slice_name']
609 number_of_nodes = form.cleaned_data['number_of_nodes']
610 type_of_nodes = form.cleaned_data['type_of_nodes']
611 purpose = form.cleaned_data['purpose']
612 email = form.cleaned_data['email'] # email of the sender
613 cc_myself = form.cleaned_data['cc_myself']
615 recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
617 recipients.append(email)
619 from django.core.mail import send_mail
620 send_mail("Onelab New Slice request form submitted", [slice_name,number_of_nodes,type_of_nodes,purpose], email, recipients)
621 return render(request,'slicereq_recvd.html') # Redirect after POST
623 form = SliceRequestForm() # An unbound form
626 # template_env['form'] = form
627 # template_env['topmenu_items'] = topmenu_items('Request a slice', request)
628 # template_env['unfold1_main'] = render(request, 'slice_request_.html', {
631 # from django.shortcuts import render_to_response
632 # from django.template import RequestContext
633 # return render_to_response ('view-unfold1.html',template_env,
634 # context_instance=RequestContext(request))
636 return render(request, 'slice_request.html', {
638 'topmenu_items': topmenu_items('Request a slice', request),
639 'username': the_user (request)
643 class PresViewView(TemplateView):
644 template_name = "view-unfold1.html"
646 def get_context_data(self, **kwargs):
648 page = Page(self.request)
650 pres_view = PresView(page = page)
652 context = super(PresViewView, self).get_context_data(**kwargs)
654 #context['ALL_STATIC'] = "all_static"
655 context['unfold1_main'] = pres_view.render(self.request)
657 # XXX This is repeated in all pages
658 # more general variables expected in the template
659 context['title'] = 'Test view that combines various plugins'
660 # the menu items on the top
661 context['topmenu_items'] = topmenu_items('PresView', self.request)
662 # so we can sho who is logged
663 context['username'] = the_user(self.request)
665 prelude_env = page.prelude_env()
666 context.update(prelude_env)
670 def json_me(config_file,type):
672 for ligne in config_file:
673 if not ligne.startswith('#'):
674 args = ligne.split(';')
675 json_answer += str('{ "name": "' + args[0] + '" ,"id":"' + args[1] + '" ,"descriptif":"' + args[2]+'"')
677 json_answer += str(',"contraints":')
679 json_answer += str('""')
681 json_answer += str(args[3])
682 json_answer += str('},')
683 return json_answer[:-1]
686 DIR = '/var/myslice/'
687 STATIC = '%s/config_method_static' % DIR
688 DYNAMIC = '%s/config_method_dynamic' % DIR
689 ANIMATION = '%s/config_method_animation' % DIR
691 def pres_view_methods(request, type):
695 elif type =="static":
696 config = open(STATIC, "r")
697 json_answer = str('{ "options": [')
698 json_answer += str(json_me(config,"static"))
699 json_answer += str('] }')
701 elif type =="dynamic":
702 config = open(DYNAMIC, "r")
703 json_answer = str('{ "options": [')
704 json_answer += str(json_me(config,"dynamic"))
705 json_answer += str('] }')
707 elif type =="animation":
708 config = open(ANIMATION, "r")
709 json_answer = str('{ "options": [')
710 json_answer += str(json_me(config,"animation"))
711 json_answer += str('] }')
714 config = open(STATIC, "r")
715 json_answer = str('{ "static": [')
716 json_answer += str(json_me(config,"static"))
717 json_answer += str('],')
718 json_answer += str('"dynamic": [')
720 config = open(DYNAMIC, "r")
721 json_answer += str(json_me(config,"dynamic"))
722 json_answer += str('],')
723 json_answer += str('"animation": [')
725 config = open(ANIMATION, "r")
726 json_answer += str(json_me(config,"animation"))
727 json_answer += str('] }')
731 return HttpResponse (json_answer, mimetype="application/json")
733 def pres_view_animation(request, constraints, id):
735 # sites crees depuis 2008
736 # static.py?contraints=']date_created':1262325600&id='name_id"'
738 # method = request.getvalue('method') #ex : GetSites
739 #constraints = "']date_created':1262325600"
745 # method = 'GetSites'#request.getvalue('method') #ex : GetSites
746 # constraints = {}#request.getvalue('constraints') // nul = {}
747 # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
749 config_file = open(ANIMATION, "r")
750 for ligne in config_file:
751 if not ligne.startswith('#'):
752 ligne = ligne.split('\n')
753 first = ligne[0].split(';')
754 if (str(first[1]) == str(id)):
758 #Les print_method, print_option sont definis par le client (js)
759 #Les animations acceptent que les connexions anonymous
760 # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
761 args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
764 #Creation d'un objet event
768 "print_options": event.print_options,
769 "print_method": event.print_method,
770 "message": event.data
775 json_answer = json.dumps(cmd)
776 return HttpResponse (json_answer, mimetype="application/json")
778 def pres_view_static(request, constraints, id):
779 #constraints = "']date_created':1262325600"
782 # method = 'GetSites'#request.getvalue('method') #ex : GetSites
783 # constraints = {}#request.getvalue('constraints') // nul = {}
784 # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
786 config_file = open(STATIC, "r")
787 for ligne in config_file:
788 if not ligne.startswith('#'):
789 ligne = ligne.split('\n')
790 first = ligne[0].split(';')
791 if (str(first[1]) == str(id)):
795 #Les print_method, print_option sont definis par le client (js)
796 #Les animations acceptent que les connexions anonymous
797 # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
798 args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
801 #Creation d'un objet event
805 "print_options": event.print_options,
806 "print_method": event.print_method,
807 "message": event.data
812 json_answer = json.dumps(cmd)
813 return HttpResponse (json_answer, mimetype="application/json")