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, edited_last_name=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 # view for contact form
569 def contact(request):
570 if request.method == 'POST': # If the form has been submitted...
571 form = ContactForm(request.POST) # A form bound to the POST data
572 if form.is_valid(): # All validation rules pass
573 # Process the data in form.cleaned_data
574 first_name = form.cleaned_data['first_name']
575 last_name = form.cleaned_data['last_name']
576 affiliation = form.cleaned_data['affiliation']
577 subject = form.cleaned_data['subject']
578 message = form.cleaned_data['message']
579 email = form.cleaned_data['email'] # email of the sender
580 cc_myself = form.cleaned_data['cc_myself']
582 recipients = ['yasin.upmc@gmail.com']
584 recipients.append(email)
586 from django.core.mail import send_mail
587 send_mail("Onelab user submitted a query ", [first_name,last_name,affiliation,subject,message], email, recipients)
588 return render(request,'contact_sent.html') # Redirect after POST
590 form = ContactForm() # An unbound form
592 return render(request, 'contact.html', {
597 def slice_request(request):
598 if request.method == 'POST': # If the form has been submitted...
599 form = SliceRequestForm(request.POST) # A form bound to the POST data
600 if form.is_valid(): # All validation rules pass
601 # Process the data in form.cleaned_data
602 slice_name = form.cleaned_data['slice_name']
603 number_of_nodes = form.cleaned_data['number_of_nodes']
604 type_of_nodes = form.cleaned_data['type_of_nodes']
605 purpose = form.cleaned_data['purpose']
606 email = form.cleaned_data['email'] # email of the sender
607 cc_myself = form.cleaned_data['cc_myself']
609 recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
611 recipients.append(email)
613 from django.core.mail import send_mail
614 send_mail("Onelab New Slice request form submitted", [slice_name,number_of_nodes,type_of_nodes,purpose], email, recipients)
615 return render(request,'slicereq_recvd.html') # Redirect after POST
617 form = SliceRequestForm() # An unbound form
620 # template_env['form'] = form
621 # template_env['topmenu_items'] = topmenu_items('Request a slice', request)
622 # template_env['unfold1_main'] = render(request, 'slice_request_.html', {
625 # from django.shortcuts import render_to_response
626 # from django.template import RequestContext
627 # return render_to_response ('view-unfold1.html',template_env,
628 # context_instance=RequestContext(request))
630 return render(request, 'slice_request.html', {
632 'topmenu_items': topmenu_items('Request a slice', request),
633 'username': the_user (request)
637 class PresViewView(TemplateView):
638 template_name = "view-unfold1.html"
640 def get_context_data(self, **kwargs):
642 page = Page(self.request)
644 pres_view = PresView(page = page)
646 context = super(PresViewView, self).get_context_data(**kwargs)
648 #context['ALL_STATIC'] = "all_static"
649 context['unfold1_main'] = pres_view.render(self.request)
651 # XXX This is repeated in all pages
652 # more general variables expected in the template
653 context['title'] = 'Test view that combines various plugins'
654 # the menu items on the top
655 context['topmenu_items'] = topmenu_items('PresView', self.request)
656 # so we can sho who is logged
657 context['username'] = the_user(self.request)
659 prelude_env = page.prelude_env()
660 context.update(prelude_env)
664 def json_me(config_file,type):
666 for ligne in config_file:
667 if not ligne.startswith('#'):
668 args = ligne.split(';')
669 json_answer += str('{ "name": "' + args[0] + '" ,"id":"' + args[1] + '" ,"descriptif":"' + args[2]+'"')
671 json_answer += str(',"contraints":')
673 json_answer += str('""')
675 json_answer += str(args[3])
676 json_answer += str('},')
677 return json_answer[:-1]
680 DIR = '/var/myslice/'
681 STATIC = '%s/config_method_static' % DIR
682 DYNAMIC = '%s/config_method_dynamic' % DIR
683 ANIMATION = '%s/config_method_animation' % DIR
685 def pres_view_methods(request, type):
689 elif type =="static":
690 config = open(STATIC, "r")
691 json_answer = str('{ "options": [')
692 json_answer += str(json_me(config,"static"))
693 json_answer += str('] }')
695 elif type =="dynamic":
696 config = open(DYNAMIC, "r")
697 json_answer = str('{ "options": [')
698 json_answer += str(json_me(config,"dynamic"))
699 json_answer += str('] }')
701 elif type =="animation":
702 config = open(ANIMATION, "r")
703 json_answer = str('{ "options": [')
704 json_answer += str(json_me(config,"animation"))
705 json_answer += str('] }')
708 config = open(STATIC, "r")
709 json_answer = str('{ "static": [')
710 json_answer += str(json_me(config,"static"))
711 json_answer += str('],')
712 json_answer += str('"dynamic": [')
714 config = open(DYNAMIC, "r")
715 json_answer += str(json_me(config,"dynamic"))
716 json_answer += str('],')
717 json_answer += str('"animation": [')
719 config = open(ANIMATION, "r")
720 json_answer += str(json_me(config,"animation"))
721 json_answer += str('] }')
725 return HttpResponse (json_answer, mimetype="application/json")
727 def pres_view_animation(request, constraints, id):
729 # sites crees depuis 2008
730 # static.py?contraints=']date_created':1262325600&id='name_id"'
732 # method = request.getvalue('method') #ex : GetSites
733 #constraints = "']date_created':1262325600"
739 # method = 'GetSites'#request.getvalue('method') #ex : GetSites
740 # constraints = {}#request.getvalue('constraints') // nul = {}
741 # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
743 config_file = open(ANIMATION, "r")
744 for ligne in config_file:
745 if not ligne.startswith('#'):
746 ligne = ligne.split('\n')
747 first = ligne[0].split(';')
748 if (str(first[1]) == str(id)):
752 #Les print_method, print_option sont definis par le client (js)
753 #Les animations acceptent que les connexions anonymous
754 # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
755 args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
758 #Creation d'un objet event
762 "print_options": event.print_options,
763 "print_method": event.print_method,
764 "message": event.data
769 json_answer = json.dumps(cmd)
770 return HttpResponse (json_answer, mimetype="application/json")
772 def pres_view_static(request, constraints, id):
773 #constraints = "']date_created':1262325600"
776 # method = 'GetSites'#request.getvalue('method') #ex : GetSites
777 # constraints = {}#request.getvalue('constraints') // nul = {}
778 # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
780 config_file = open(STATIC, "r")
781 for ligne in config_file:
782 if not ligne.startswith('#'):
783 ligne = ligne.split('\n')
784 first = ligne[0].split(';')
785 if (str(first[1]) == str(id)):
789 #Les print_method, print_option sont definis par le client (js)
790 #Les animations acceptent que les connexions anonymous
791 # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
792 args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
795 #Creation d'un objet event
799 "print_options": event.print_options,
800 "print_method": event.print_method,
801 "message": event.data
806 json_answer = json.dumps(cmd)
807 return HttpResponse (json_answer, mimetype="application/json")