plugins: added pres_view + small fixes
[myslice.git] / portal / views.py
1 # -*- coding: utf-8 -*-
2 #
3 # portal/views.py: views for the portal application
4 # This file is part of the Manifold project.
5 #
6 # Authors:
7 #   Jordan AugĂ© <jordan.auge@lip6.fr>
8 #   Mohammed Yasin Rahman <mohammed-yasin.rahman@lip6.fr>
9 # Copyright 2013, UPMC Sorbonne UniversitĂ©s / LIP6
10 #
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.
14
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
18 # details.
19
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.
23
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
30
31 from plugins.lists.simplelist    import SimpleList
32
33 from plugins.pres_view           import PresView
34 from portal.event import Event
35 import json
36
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
45
46 class DashboardView(TemplateView):
47     template_name = "dashboard.html"
48
49     def get_context_data(self, **kwargs):
50         user_hrn = 'ple.upmc.jordan_auge'
51         #user_hrn = 'iotlab.auge'
52
53         #messages.info(self.request, 'You have logged in')
54         page = Page(self.request)
55
56         # Slow...
57         #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
58         slice_query = Query().get('user').filter_by('user_hrn', '==', user_hrn).select('user_hrn', 'slice.slice_hrn')
59         auth_query  = Query().get('network').select('network_hrn')
60         page.enqueue_query(slice_query)
61         page.enqueue_query(auth_query)
62
63         page.expose_queries()
64
65         slicelist = SimpleList(
66             title = None,
67             page  = page,
68             key   = 'slice.slice_hrn',
69             query = slice_query,
70         )
71          
72         authlist = SimpleList(
73             title = None,
74             page  = page,
75             key   = 'network_hrn',
76             query = auth_query,
77         )
78
79         context = super(DashboardView, self).get_context_data(**kwargs)
80         context['person']   = self.request.user
81         context['networks'] = authlist.render(self.request) 
82         context['slices']   = slicelist.render(self.request)
83
84         # XXX This is repeated in all pages
85         # more general variables expected in the template
86         context['title'] = 'Test view that combines various plugins'
87         # the menu items on the top
88         context['topmenu_items'] = topmenu_items('Dashboard', self.request) 
89         # so we can sho who is logged
90         context['username'] = the_user(self.request) 
91
92         context.update(page.prelude_env())
93
94         return context
95
96 class UserRegisterView(RegistrationView):
97     """
98     A registration backend which follows a simple workflow:
99
100     1. User signs up, inactive account is created.
101
102     2. Email is sent to user with activation link.
103
104     3. User clicks activation link, account is now active.
105
106     Using this backend requires that
107
108     * ``registration`` be listed in the ``INSTALLED_APPS`` setting
109       (since this backend makes use of models defined in this
110       application).
111
112     * The setting ``ACCOUNT_ACTIVATION_DAYS`` be supplied, specifying
113       (as an integer) the number of days from registration during
114       which a user may activate their account (after that period
115       expires, activation will be disallowed).
116
117     * The creation of the templates
118       ``registration/activation_email_subject.txt`` and
119       ``registration/activation_email.txt``, which will be used for
120       the activation email. See the notes for this backends
121       ``register`` method for details regarding these templates.
122
123     Additionally, registration can be temporarily closed by adding the
124     setting ``REGISTRATION_OPEN`` and setting it to
125     ``False``. Omitting this setting, or setting it to ``True``, will
126     be interpreted as meaning that registration is currently open and
127     permitt ed.
128
129     Internally, this is accomplished via storing an activation key in
130     an instance of ``registration.models.RegistrationProfile``. See
131     that model and its custom manager for full documentation of its
132     fields and supported operations.
133     
134     """
135     form_class = UserRegisterForm
136     
137     def register(self, request, **cleaned_data):
138         """
139         Given a username, email address and password, register a new
140         user account, which will initially be inactive.
141
142         Along with the new ``User`` object, a new
143         ``registration.models.RegistrationProfile`` will be created,
144         tied to that ``User``, containing the activation key which
145         will be used for this account.
146
147         An email will be sent to the supplied email address; this
148         email should contain an activation link. The email will be
149         rendered using two templates. See the documentation for
150         ``RegistrationProfile.send_activation_email()`` for
151         information about these templates and the contexts provided to
152         them.
153
154         After the ``User`` and ``RegistrationProfile`` are created and
155         the activation email is sent, the signal
156         ``registration.signals.user_registered`` will be sent, with
157         the new ``User`` as the keyword argument ``user`` and the
158         class of this backend as the sender.
159
160         """
161         first_name = cleaned_data['first_name']
162         last_name  = cleaned_data['last_name']
163         affiliation= cleaned_data['affiliation']
164         email      = cleaned_data['email']
165         password   = cleaned_data['password1']
166         
167         #password2  = cleaned_data['password2']
168         keypair    = cleaned_data['keypair']
169
170         #if Site._meta.installed:
171         #    site = Site.objects.get_current()
172         #else:
173         #    site = RequestSite(request) 
174         site = None
175
176         new_user = PendingUser.objects.create_inactive_user(first_name, last_name, email, password, site)
177         signals.user_registered.send(sender=self.__class__,
178                                      user=new_user,
179                                      request=request)
180         return new_user
181
182     def get_context_data(self, **kwargs):
183         context = super(UserRegisterView, self).get_context_data(**kwargs)
184         context['topmenu_items'] = topmenu_items('Register', self.request)
185         context['username'] = the_user (self.request)
186         return context
187
188     def registration_allowed(self, request):
189         """
190         Indicate whether account registration is currently permitted,
191         based on the value of the setting ``REGISTRATION_OPEN``. This
192         is determined as follows:
193
194         * If ``REGISTRATION_OPEN`` is not specified in settings, or is
195           set to ``True``, registration is permitted.
196
197         * If ``REGISTRATION_OPEN`` is both specified and set to
198           ``False``, registration is not permitted.
199         
200         """
201         return getattr(settings, 'REGISTRATION_OPEN', True)
202
203     def get_success_url(self, request, user):
204         """
205         Return the name of the URL to redirect to after successful
206         user registration.
207         
208         """
209         return ('user_register_complete', (), {})
210
211
212 class UserValidateView(ActivationView):
213     def activate(self, request, activation_key):
214         """
215         Given an an activation key, look up and activate the user
216         account corresponding to that key (if possible).
217
218         After successful activation, the signal
219         ``registration.signals.user_activated`` will be sent, with the
220         newly activated ``User`` as the keyword argument ``user`` and
221         the class of this backend as the sender.
222         
223         """
224         activated_user = RegistrationProfile.objects.activate_user(activation_key)
225         if activated_user:
226             signals.user_activated.send(sender=self.__class__,
227                                         user=activated_user,
228                                         request=request)
229         return activated_user
230
231     def get_success_url(self, request, user):
232         return ('registration_activation_complete', (), {})
233
234
235 # DEPRECATED #from portal.portalpage  import PortalPage
236 # DEPRECATED #from plugins.wizard     import Wizard
237 # DEPRECATED #from plugins.form       import CreateForm
238 # DEPRECATED #from plugins.raw.raw    import Raw          # XXX
239 # DEPRECATED #
240 # DEPRECATED #from myslice.viewutils  import the_user
241 # DEPRECATED #
242 # DEPRECATED #from django.template.loader import render_to_string
243 # DEPRECATED #from django.template import RequestContext
244 # DEPRECATED #from django.views import generic
245 # DEPRECATED #
246 # DEPRECATED #from django.contrib.formtools.wizard.views import NamedUrlSessionWizardView
247 # DEPRECATED ##from django.core.files.storage import FileSystemStorage
248 # DEPRECATED #from django.core.files.storage import default_storage
249 # DEPRECATED #
250 # DEPRECATED ##class MerlinWizard(NamedUrlSessionWizardView):
251 # DEPRECATED ##
252 # DEPRECATED ##    ...
253 # DEPRECATED ##    ...
254 # DEPRECATED ##
255 # DEPRECATED ##    @classonlymethod
256 # DEPRECATED ##    def as_view(cls, *args, **kwargs):
257 # DEPRECATED ##        kwargs.update({
258 # DEPRECATED ##            'form_list': [
259 # DEPRECATED ##                NameForm,
260 # DEPRECATED ##                QuestForm,
261 # DEPRECATED ##                ColorForm,
262 # DEPRECATED ##            ],
263 # DEPRECATED ##            'url_name': 'merlin_wizard'
264 # DEPRECATED ##        })
265 # DEPRECATED ##        return super(MerlinWizard, cls).as_view(*args, **kwargs)
266 # DEPRECATED #
267 # DEPRECATED #class UserRegisterWizardView(NamedUrlSessionWizardView):
268 # DEPRECATED ##class UserRegisterWizardView(LoginRequiredMixin, NamedUrlSessionWizardView):
269 # DEPRECATED #    # Notice that I specify a file storage instance. If you don't specify this,
270 # DEPRECATED #    # and you need to support FileField or ImageField in your forms, you'll get
271 # DEPRECATED #    # errors from Django. This is something else I think could be handled by
272 # DEPRECATED #    # the views better. Seems to me that it should just use whatever the
273 # DEPRECATED #    # default/specified storage is for the rest of your project/application.
274 # DEPRECATED #    file_storage = default_storage # FileSystemStorage()
275 # DEPRECATED #    template_name = "register_user_wizard.html"
276 # DEPRECATED #
277 # DEPRECATED #    def done(self, form_list, **kwargs):
278 # DEPRECATED #        step1_form = form_list[0]
279 # DEPRECATED #        step2_form = form_list[1]
280 # DEPRECATED #
281 # DEPRECATED #        productext = self.create_product(product_form)
282 # DEPRECATED #        shippings = self.create_shippings(productext, shipping_forms)
283 # DEPRECATED #        images = self.create_images(productext, image_forms)
284 # DEPRECATED #
285 # DEPRECATED #        if all([productext, shippings, images]):
286 # DEPRECATED #            del self.request.session["wizard_product_wizard_view"]
287 # DEPRECATED #
288 # DEPRECATED #            messages.success(self.request,
289 # DEPRECATED #                _("Your product has been created."))
290 # DEPRECATED #            return HttpResponseRedirect(self.get_success_url(productext))
291 # DEPRECATED #
292 # DEPRECATED #        messages.error(self.request, _("Something went wrong creating your "
293 # DEPRECATED #            "product. Please try again or contact support."))
294 # DEPRECATED #        return HttpResponseRedirect(reverse("register_wizard"))
295 # DEPRECATED #
296 # DEPRECATED #    #def get_form_kwargs(self, step):
297 # DEPRECATED #    #    if step == "product":
298 # DEPRECATED #    #        return {"user": self.request.user}
299 # DEPRECATED #    #    return {}
300 # DEPRECATED #
301 # DEPRECATED ## The portal should hook the slice and user creation pages
302 # DEPRECATED #
303 # DEPRECATED #def register_user(request):
304 # DEPRECATED #    
305 # DEPRECATED #    if request.method == 'POST':
306 # DEPRECATED #        form = UserRegisterForm(request.POST) # Nous reprenons les donnĂ©es
307 # DEPRECATED #        if form.is_valid():
308 # DEPRECATED #            first_name = form.cleaned_data['first_name']
309 # DEPRECATED #            last_name  = form.cleaned_data['last_name']
310 # DEPRECATED #            email      = form.cleaned_data['email']
311 # DEPRECATED #            password   = form.cleaned_data['password']
312 # DEPRECATED #            password2  = form.cleaned_data['password2']
313 # DEPRECATED #            keypair    = form.cleaned_data['keypair']
314 # DEPRECATED #            ## Ici nous pouvons traiter les donnĂ©es du formulaire
315 # DEPRECATED #            #sujet = form.cleaned_data['sujet']
316 # DEPRECATED #            #message = form.cleaned_data['message']
317 # DEPRECATED #            #envoyeur = form.cleaned_data['envoyeur']
318 # DEPRECATED #            #renvoi = form.cleaned_data['renvoi']
319 # DEPRECATED #            ## Nous pourrions ici envoyer l'e-mail grâce aux donnĂ©es que nous venons de rĂ©cupĂ©rer
320 # DEPRECATED #            #envoi = True
321 # DEPRECATED #    else:
322 # DEPRECATED #        form = UserRegisterForm()
323 # DEPRECATED #    return render(request, 'register_user.html', locals())
324 # DEPRECATED #
325 # DEPRECATED #def index(request):
326 # DEPRECATED #
327 # DEPRECATED #    WIZARD_TITLE = 'User registration'
328 # DEPRECATED #    STEP1_TITLE  = 'Enter your details'
329 # DEPRECATED #    STEP2_TITLE  = 'Select your institution'
330 # DEPRECATED #    STEP3_TITLE  = 'Authentication'
331 # DEPRECATED #    STEP4_TITLE  = 'Request a slice (optional)'
332 # DEPRECATED #    STEP5_TITLE  = 'Waiting for validation'
333 # DEPRECATED #    STEP6_TITLE  = 'Account validated'
334 # DEPRECATED #
335 # DEPRECATED #    STEP0 = render_to_string('account_validated.html', context_instance=RequestContext(request))
336 # DEPRECATED #    STEP2_HTML   = """
337 # DEPRECATED #    coucou
338 # DEPRECATED #    """
339 # DEPRECATED #    STEP4 = """
340 # DEPRECATED #    mede
341 # DEPRECATED #    """
342 # DEPRECATED #    STEP5 = render_to_string('account_validated.html', context_instance=RequestContext(request))
343 # DEPRECATED #
344 # DEPRECATED #    p = PortalPage(request)
345 # DEPRECATED #
346 # DEPRECATED #    # This is redundant with the Wizard title
347 # DEPRECATED #    p << "<h3>User registration</h3>"
348 # DEPRECATED #
349 # DEPRECATED #    sons = []
350 # DEPRECATED #    start_step = 1
351 # DEPRECATED #
352 # DEPRECATED #    # STEP 1
353 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of his account details
354 # DEPRECATED #    # Otherwise propose a form to fill in
355 # DEPRECATED #    if the_user(request):
356 # DEPRECATED #        # Fill a disabled form with user info
357 # DEPRECATED #        # Please logout to register another user
358 # DEPRECATED #        sons.append(Raw(page=p, title=STEP1_TITLE, togglable=False, html=STEP0))
359 # DEPRECATED #        start_step += 1
360 # DEPRECATED #    else:
361 # DEPRECATED #        # We could pass a list of fields also, instead of retrieving them from metadata
362 # DEPRECATED #        # Otherwise we need some heuristics to display nice forms
363 # DEPRECATED #        # XXX Could we log the user in after the form is validated ?
364 # DEPRECATED #        # XXX Explain the password is for XXX
365 # DEPRECATED #        field_list = [{
366 # DEPRECATED #            'name'        : 'First name',
367 # DEPRECATED #            'field'       : 'firstname',
368 # DEPRECATED #            'type'        : 'text',
369 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
370 # DEPRECATED #            'validate_err': 'Your first name must be comprised of letters only',
371 # DEPRECATED #            'description' : 'Enter your first name',
372 # DEPRECATED #        }, {
373 # DEPRECATED #            'name'        : 'Last name',
374 # DEPRECATED #            'field'       : 'lastname',
375 # DEPRECATED #            'type'        : 'text',
376 # DEPRECATED #            'validate_rx' : '^[a-zA-Z -]+$',
377 # DEPRECATED #            'validate_err': 'Your last name must be comprised of letters only',
378 # DEPRECATED #            'description' : 'Enter your last name',
379 # DEPRECATED #        }, { 
380 # DEPRECATED #            'name'        : 'Email',
381 # DEPRECATED #            'field'       : 'email',
382 # DEPRECATED #            'type'        : 'text',
383 # DEPRECATED #            'description' : 'Enter your email address',
384 # DEPRECATED #        }, {
385 # DEPRECATED #            'name'        : 'Password',
386 # DEPRECATED #            'field'       : 'password',
387 # DEPRECATED #            'type'        : 'password',
388 # DEPRECATED #            'description' : 'Enter your password',
389 # DEPRECATED #        }, {
390 # DEPRECATED #            'name'        : 'Confirm password',
391 # DEPRECATED #            'field'       : 'password2',
392 # DEPRECATED #            'type'        : 'password',
393 # DEPRECATED #            'description' : 'Enter your password again',
394 # DEPRECATED #        }]
395 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP1_TITLE, togglable = False, object = 'local:user', fields = field_list))
396 # DEPRECATED #
397 # DEPRECATED #    # STEP 2
398 # DEPRECATED #    # If the user already exists (is logged), let's display a summary of its institution
399 # DEPRECATED #    # Otherwise propose a form to fill in (we should base our selection on the email)
400 # DEPRECATED #    if the_user(request):
401 # DEPRECATED #        # Fill a disabled form with institution
402 # DEPRECATED #        # Please logout to register another user
403 # DEPRECATED #        sons.append(Raw(page=p, title=STEP2_TITLE, togglable=False, html="User created"))
404 # DEPRECATED #        start_step += 1
405 # DEPRECATED #    else:
406 # DEPRECATED #        sons.append(CreateForm(page = p, title = STEP2_TITLE, togglable = False, object = 'slice')) #institution'))
407 # DEPRECATED #
408 # DEPRECATED #    # STEP3
409 # DEPRECATED #    # Please should your prefered authentication method
410 # DEPRECATED #    # This step should allow the user to either choose the user or managed mode in MySlice
411 # DEPRECATED #    sons.append(Raw(page = p, title = STEP3_TITLE, togglable = False, html = STEP2_HTML))
412 # DEPRECATED #
413 # DEPRECATED #    # Step 4: Request a slice (optional)
414 # DEPRECATED #    sons.append(CreateForm(page = p, title = STEP4_TITLE, togglable = False, object = 'slice'))
415 # DEPRECATED #
416 # DEPRECATED #    # Step 5: Your request is waiting for validation
417 # DEPRECATED #    # Periodic refresh
418 # DEPRECATED #    sons.append(Raw(page = p, title = STEP5_TITLE, togglable = False, html = STEP4))
419 # DEPRECATED #
420 # DEPRECATED #    # Step 6: Account validation  = welcome for newly validated users
421 # DEPRECATED #    # . delegation
422 # DEPRECATED #    # . platforms
423 # DEPRECATED #    # . slice
424 # DEPRECATED #    # . pointers
425 # DEPRECATED #    sons.append(Raw(page = p, title = STEP6_TITLE, togglable = False, html = STEP5))
426 # DEPRECATED #
427 # DEPRECATED #    wizard = Wizard(
428 # DEPRECATED #        page       = p,
429 # DEPRECATED #        title      = WIZARD_TITLE,
430 # DEPRECATED #        togglable  = False,
431 # DEPRECATED #        sons       = sons,
432 # DEPRECATED #        start_step = start_step,
433 # DEPRECATED #    )
434 # DEPRECATED #
435 # DEPRECATED #    p << wizard.render(request) # in portal page if possible
436 # DEPRECATED #
437 # DEPRECATED #    return p.render()
438
439
440 # DEPRECATED ## view for my_account
441 # DEPRECATED # class MyAccountView(TemplateView):
442 # DEPRECATED #    template_name = "my_account.html"
443 # DEPRECATED #    
444 # DEPRECATED #    def from_process(self, request, **cleaned_data): 
445 # DEPRECATED #        #if request.method == 'POST':
446 # DEPRECATED #         #       if request.POST['submit_name']:
447 # DEPRECATED #        if 'fname' in request.POST:            
448 # DEPRECATED #                messsag= "Got Name"
449 # DEPRECATED #                #return render(request, 'portal/my_account.html')
450 # DEPRECATED #                #response = HttpResponse("Here's the text of the Web page.")    
451 # DEPRECATED #                return HttpResponse(message)
452 # DEPRECATED #            
453 # DEPRECATED #    def get_context_data(self, **kwargs):
454 # DEPRECATED #        page = Page(self.request)
455 # DEPRECATED #        context = super(MyAccountView, self).get_context_data(**kwargs)
456 # DEPRECATED #        context['person']   = self.request.user
457 # DEPRECATED #        # XXX This is repeated in all pages
458 # DEPRECATED #        # more general variables expected in the template
459 # DEPRECATED #        context['title'] = 'User Profile Page'
460 # DEPRECATED #        # the menu items on the top
461 # DEPRECATED #        context['topmenu_items'] = topmenu_items('my_account', self.request)
462 # DEPRECATED #        # so we can sho who is logged
463 # DEPRECATED #        context['username'] = the_user(self.request)
464 # DEPRECATED #        context.update(page.prelude_env())
465 # DEPRECATED #        return context
466
467
468
469 # View for my_account form
470 def my_account(request):
471     return render(request, 'my_account.html')
472
473 #my_acc form value processing
474 def acc_process(request):
475     if 'submit_name' in request.POST:
476         edited_first_name =  request.POST['fname']
477         edited_last_name =  request.POST['lname']
478         #email = 'test_email@gmail.com'
479         #password = 'test_pp'
480         #message = 'F_Name: %s L_name: %s dummy_pp: %s' % (first_name, last_name, password)
481         #site = None
482         
483         # insert into DB [needed for registration page]
484         #approach borrowed from register view     
485         #new_user = PendingUser.objects.create_inactive_user(edited_first_name, edited_last_name, email,  password, site) 
486         #conventional approach
487         #b = PendingUser(first_name=edited_first_name, edited_last_name=last_name)
488         #b.save()
489         
490         # select and update [will be used throughout this view]
491         # select the logged in user [for the moment hard coded]
492         get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
493         # update first and last name
494         get_user.first_name = edited_first_name
495         get_user.last_name = edited_last_name
496         get_user.save() 
497
498         return HttpResponse('Success: Name Updated!!')       
499     elif 'submit_pass' in request.POST:
500         edited_password = request.POST['password']
501         # select the logged in user [for the moment hard coded]
502         get_user = PendingUser.objects.get(id='1') # here we will get the id/email from session e.g., person.email
503         # update password
504         get_user.password = edited_password
505         get_user.save()
506         return HttpResponse('Success: Password Changed!!')
507     elif 'generate' in request.POST:
508         a =2
509         message = 'Here will generate ssh-rsa keys :D %d' %a
510         return HttpResponse(message)
511     else:
512         message = 'You submitted an empty form.'
513         return HttpResponse(message)
514
515
516
517 # view for contact form
518 def contact(request):
519     if request.method == 'POST': # If the form has been submitted...
520         form = ContactForm(request.POST) # A form bound to the POST data
521         if form.is_valid(): # All validation rules pass
522             # Process the data in form.cleaned_data
523             first_name = form.cleaned_data['first_name']
524             last_name = form.cleaned_data['last_name']
525             affiliation = form.cleaned_data['affiliation']
526             subject = form.cleaned_data['subject']
527             message = form.cleaned_data['message']
528             email = form.cleaned_data['email'] # email of the sender
529             cc_myself = form.cleaned_data['cc_myself']
530
531             recipients = ['yasin.upmc@gmail.com']
532             if cc_myself:
533                 recipients.append(email)
534
535             from django.core.mail import send_mail
536             send_mail("Onelab user submitted a query ", [first_name,last_name,affiliation,subject,message], email, recipients)
537             return render(request,'contact_sent.html') # Redirect after POST
538     else:
539         form = ContactForm() # An unbound form
540
541     return render(request, 'contact.html', {
542         'form': form,
543     })
544
545
546 def slice_request(request):
547     if request.method == 'POST': # If the form has been submitted...
548         form = SliceRequestForm(request.POST) # A form bound to the POST data
549         if form.is_valid(): # All validation rules pass
550             # Process the data in form.cleaned_data
551             slice_name = form.cleaned_data['slice_name']
552             number_of_nodes = form.cleaned_data['number_of_nodes']
553             type_of_nodes = form.cleaned_data['type_of_nodes']
554             purpose = form.cleaned_data['purpose']
555             email = form.cleaned_data['email'] # email of the sender
556             cc_myself = form.cleaned_data['cc_myself']
557
558             recipients = ['yasin.upmc@gmail.com','jordan.auge@lip6.fr']
559             if cc_myself:
560                 recipients.append(email)
561
562             from django.core.mail import send_mail
563             send_mail("Onelab New Slice request form submitted", [slice_name,number_of_nodes,type_of_nodes,purpose], email, recipients)
564             return render(request,'slicereq_recvd.html') # Redirect after POST
565     else:
566         form = SliceRequestForm() # An unbound form
567
568 #    template_env = {}
569 #    template_env['form'] = form
570 #    template_env['topmenu_items'] = topmenu_items('Request a slice', request) 
571 #    template_env['unfold1_main'] = render(request, 'slice_request_.html', {
572 #        'form': form,
573 #    })
574 #    from django.shortcuts                import render_to_response
575 #    from django.template                 import RequestContext
576 #    return render_to_response ('view-unfold1.html',template_env,
577 #                               context_instance=RequestContext(request))
578
579     return render(request, 'slice_request.html', {
580         'form': form,
581         'topmenu_items': topmenu_items('Request a slice', request),
582         'username': the_user (request) 
583     })
584
585
586 class PresViewView(TemplateView):
587     template_name = "view-unfold1.html"
588
589     def get_context_data(self, **kwargs):
590
591         page = Page(self.request)
592
593         pres_view = PresView(page = page)
594
595         context = super(PresViewView, self).get_context_data(**kwargs)
596
597         #context['ALL_STATIC'] = "all_static"
598         context['unfold1_main'] = pres_view.render(self.request)
599
600         # XXX This is repeated in all pages
601         # more general variables expected in the template
602         context['title'] = 'Test view that combines various plugins'
603         # the menu items on the top
604         context['topmenu_items'] = topmenu_items('PresView', self.request)
605         # so we can sho who is logged
606         context['username'] = the_user(self.request)
607
608         prelude_env = page.prelude_env()
609         context.update(prelude_env)
610
611         return context
612
613 def json_me(config_file,type):
614     json_answer = ''
615     for ligne in config_file:
616         if not ligne.startswith('#'):
617             args = ligne.split(';')
618             json_answer += str('{ "name": "' + args[0] + '" ,"id":"' + args[1]  + '" ,"descriptif":"' + args[2]+'"')
619             if type!="dynamic":
620                 json_answer += str(',"contraints":')
621                 if args[3]=="":
622                     json_answer += str('""')
623                 else:
624                     json_answer += str(args[3])
625             json_answer += str('},')
626     return json_answer[:-1]
627
628
629 DIR = '/var/myslice/'
630 STATIC = '%s/config_method_static' % DIR
631 DYNAMIC = '%s/config_method_dynamic' % DIR
632 ANIMATION = '%s/config_method_animation' % DIR
633
634 def pres_view_methods(request, type):
635
636     if type ==None:
637         return 0
638     elif type =="static":
639         config = open(STATIC, "r")
640         json_answer = str('{ "options": [')
641         json_answer += str(json_me(config,"static"))
642         json_answer += str('] }')
643         config.close()
644     elif type =="dynamic":
645         config = open(DYNAMIC, "r")
646         json_answer = str('{ "options": [')
647         json_answer += str(json_me(config,"dynamic"))
648         json_answer += str('] }')
649         config.close()
650     elif type =="animation":
651         config = open(ANIMATION, "r")
652         json_answer = str('{ "options": [')
653         json_answer += str(json_me(config,"animation"))
654         json_answer += str('] }')
655         config.close()
656     elif type =="all":
657         config = open(STATIC, "r")
658         json_answer = str('{ "static": [')
659         json_answer += str(json_me(config,"static"))
660         json_answer += str('],')
661         json_answer += str('"dynamic": [')
662         config.close()
663         config = open(DYNAMIC, "r")
664         json_answer += str(json_me(config,"dynamic"))
665         json_answer += str('],')
666         json_answer += str('"animation": [')
667         config.close()
668         config = open(ANIMATION, "r")
669         json_answer += str(json_me(config,"animation"))
670         json_answer += str('] }')
671         config.close()
672     else:
673         return 0
674     return HttpResponse (json_answer, mimetype="application/json")
675
676 def pres_view_animation(request, constraints, id):
677
678 # sites crees depuis 2008
679 # static.py?contraints=']date_created':1262325600&id='name_id"'
680
681     # method = request.getvalue('method') #ex : GetSites
682     #constraints = "']date_created':1262325600"
683     #id = "2"
684
685     if id == None:
686         return 0
687
688     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
689     # constraints = {}#request.getvalue('constraints') // nul = {}
690     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
691
692     config_file = open(ANIMATION, "r")
693     for ligne in config_file:
694         if not ligne.startswith('#'):
695             ligne = ligne.split('\n')
696             first = ligne[0].split(';')
697             if (str(first[1]) == str(id)):
698                 save = first
699     config_file.close()
700
701     #Les print_method, print_option sont definis par le client (js)
702     #Les animations acceptent que les connexions anonymous
703     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
704     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
705
706
707     #Creation d'un objet event
708     event = Event(args)
709     cmd = [{"params": {
710             "data": {
711                 "print_options": event.print_options,
712                 "print_method": event.print_method,
713                 "message": event.data
714             }
715         }
716     }]
717
718     json_answer = json.dumps(cmd)
719     return HttpResponse (json_answer, mimetype="application/json")
720
721 def pres_view_static(request, constraints, id):
722     #constraints = "']date_created':1262325600"
723     #id = "2"
724
725     # method = 'GetSites'#request.getvalue('method') #ex : GetSites
726     # constraints = {}#request.getvalue('constraints') // nul = {}
727     # response_field = "'site_id','name','date_created'"#request.getvalue('response_field')
728
729     config_file = open(STATIC, "r")
730     for ligne in config_file:
731         if not ligne.startswith('#'):
732             ligne = ligne.split('\n')
733             first = ligne[0].split(';')
734             if (str(first[1]) == str(id)):
735                 save = first
736     config_file.close()
737
738     #Les print_method, print_option sont definis par le client (js)
739     #Les animations acceptent que les connexions anonymous
740     # args = "postmsg;animation;;;anonymous;https://www.planet-lab.eu/PLCAPI/;"
741     args = ";;"+str(save[8])+";"+str(save[9])+";anonymous;"+str(save[5])+";"+str(save[6])+";{"+str(constraints)+"};"+str(save[7])+";"
742
743
744     #Creation d'un objet event
745     event = Event(args)
746     cmd = [{"params": {
747             "data": {
748                 "print_options": event.print_options,
749                 "print_method": event.print_method,
750                 "message": event.data
751             }
752         }
753     }]
754
755     json_answer = json.dumps(cmd)
756     return HttpResponse (json_answer, mimetype="application/json")