Beispiel #1
0
 def __init__(self, request):
     #request.session.clear()
     if request.session.get('isConfig', False) is False:
         Config.getSession(request.session)
     leftBlocks = []
     if not request.session['user'].is_authenticated():
         leftBlocks = [render_to_string('kirinki/section.html', {'title' : 'login', 'content': render_to_string('kirinki/form.html', {'form' : LoginForm(), 'action' : request.session['base_url']+'/login'}, context_instance=RequestContext(request))})]
     centerBlocks = [render_to_string('kirinki/section.html', {'title' : 'Bienvenido', 'content' : '<p>Bienvenido a Kirinki, el sitio desde el cual podras hacer Streaming tanto en directo como en diferido de manera sencilla.</p>'})]
     rightBlocks = [self.generateArticles(), self.generateVideos()]
     self.render = MainViewer(request).render(leftBlocks, centerBlocks, rightBlocks)
Beispiel #2
0
    def __init__(self, request):
        if request.session.get('isConfig', False) is False:
            Config.getSession(request.session)

        if request.session['user'].is_authenticated():
            logout(request)
            Message.pushMessage(request, Message.INFO, 'User logged out.')
        else:
            Message.pushMessage(request, Message.ERROR, 'User not logged in.')
            
        if request.META.get('HTTP_REFERER', False) is not False:
            self.render = HttpResponseRedirect(request.META['HTTP_REFERER'])
        else:
            self.render = HttpResponse('/logout')
Beispiel #3
0
    def __init__(self, request):
        if request.session.get('isConfig', False) is False:
            Config.getSession(request.session)

        form = LoginForm(request.POST, error_class=ErrorClear)
        if request.method == 'GET':
            # GET request
            centerBlocks = []
            if not request.session['user'].is_authenticated():
                centerBlocks = [render_to_string('kirinki/section.html', {'title' : 'Login', 'content': render_to_string('kirinki/form.html', {'form' : form, 'action' : request.session['base_url']+'/login'}, context_instance=RequestContext(request))})]
            self.render = MainViewer(request).render([],centerBlocks,[])
            
        elif request.method == 'POST':
            # POST request
            Log.debug('Login POST')

            if request.session['user'].is_authenticated():
                Message.pushMessage(request, Message.ERROR, 'User already logged in')
            if form.is_valid():
                user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        Message.pushMessage(request, Message.INFO, 'User logged in')
                        request.session['user'] = user
                    else:
                        # Return a 'disabled account' error message
                        Message.pushMessage(request, Message.ERROR, 'Your account is disabled.')
                else:
                    # Return an 'invalid login' error message.
                    Message.pushMessage(request, Message.ERROR, 'Username or password error.')
            else:
                for error in form.errors:
                    Message.pushMessage(request, Message.ERROR, 'Error en ' + error + ': ' + str(form._errors[error]))

            # The return page is the same for all the situations of this request.
            if request.META.get('HTTP_REFERER', False) is not False:
                self.render = HttpResponseRedirect(request.META['HTTP_REFERER'])
            else:
                self.render = HttpResponseRedirect('/index')
                
        else:
            # If there's not GET neither POST request there's an error
            raise Http404
Beispiel #4
0
    def __init__(self, request):
        if request.session.get('isConfig', False) is False:
            Config.getSession(request.session)

        # Left block
        leftBlocks = []
        if not request.session['user'].is_authenticated():
            leftBlocks = [render_to_string('kirinki/section.html', {'title' : 'login', 'content': render_to_string('kirinki/form.html', {'form' : LoginForm(), 'action' : request.session['base_url'] + '/login'}, context_instance=RequestContext(request))})]

        # Center block
        centerBlocks = []
        try:
            videoStr = streaming.objects.all()
            for video in videoStr:
                centerBlocks = [render_to_string('kirinki/section.html', {'title' : 'login', 'content': str(video.idStreaming)})]
        except streaming.DoesNotExist:
            pass
        
        self.render = MainViewer(request).render(leftBlocks, centerBlocks, [])
Beispiel #5
0
    def __init__(self, request):
        if request.session.get('isConfig', False) is False:
            Config.getSession(request.session)

        if request.method == 'GET':
            # GET request
            leftBlocks = [self.getMyVideos(request.session)]
            centerBlocks = [self.getUploadVideo(request.session['base_url'], request)]
            self.render = MainViewer(request).render(leftBlocks, centerBlocks, [])
            
        elif request.method == 'POST':
            # POST request.
            form = UploadForm(request.POST, request.FILES, error_class=ErrorClear)
            if form.is_valid():
                upFile = request.FILES['fileUpload']
                if upFile.size > 0:
                    path = ''
                    if request.session.get('upload_path', False):
                        path = request.session['upload_path']+'/'
                    path += upFile.name
                    destination = open(path, 'wb+')
                    for chunk in upFile.chunks():
                        destination.write(chunk)
                    destination.close()
                    v = video(name=form.cleaned_data['title'], description=form.cleaned_data['description'], path=path, format=upFile.content_type, pub_date=datetime.now(), owner=request.session['user'])
                    v.save()
                    if form.cleaned_data['convertMP4'] and path[v.path.rfind('.'):].lower() != 'mp4':
                        pass
                    if form.cleaned_data['convertOGG'] and path[v.path.rfind('.'):].lower() != 'ogg':
                        pass
                    if form.cleaned_data['convertWEBM'] and path[v.path.rfind('.'):].lower() != 'web':
                        pass
                    if path[v.path.rfind('.'):].lower() != 'flv':
                        pass
            else:
                for error in form.errors:
                    Message.pushMessage(request, Message.ERROR, 'Error en ' + error + ': ' + str(form._errors[error]))
            if request.META.get('HTTP_REFERER', False) is not False:
                self.render = HttpResponseRedirect(request.META['HTTP_REFERER'])
            else:
                self.render = HttpResponseRedirect('/index')            
        else:
            raise Http404
Beispiel #6
0
 def __init__(self, request):
     if request.session.get('isConfig', False) is False:
         Config.getSession(request.session)
     self.render = MainViewer(request).render([],[],[])
Beispiel #7
0
    def __init__(self, request):
        if request.session.get('isConfig', False) is False:
            Config.getSession(request.session)

        form = RegisterForm(request.POST, error_class=ErrorClear)
        if request.method == 'GET':
            # GET request
            centerBlocks = []
            if not request.session['user'].is_authenticated():
                centerBlocks = [render_to_string('kirinki/section.html',
                                                 {'title' : 'Register',
                                                  'content': render_to_string('kirinki/form.html', {'form' : form, 'action' : request.session['base_url']+'/register', 'captcha' : captcha.displayhtml('6LefRr8SAAAAAMncFelaGsop60Uuon0MCL6H-aP3')},
                                                                              context_instance=RequestContext(request))})]
            self.render = MainViewer(request).render([],centerBlocks,[])
            
        elif request.method == 'POST':
            # POST request
            if form.is_valid():
                Log.debug('Form valid')
                if form.cleaned_data['password'] != form.cleaned_data['rpassword']:
                    Log.debug('Passwords doesn\'t match')
                    Message.pushMessage(request, Message.INFO, 'Passwords doesn\'t match.')
                else:
                    Log.debug('Passwords match')
                    remote_ip = request.META['REMOTE_ADDR']
                    challenge = request.REQUEST.get('recaptcha_challenge_field')
                    response = request.REQUEST.get('recaptcha_response_field')
                    recaptcha_response = captcha.submit(challenge, response, '6LefRr8SAAAAAPpY8WNoxo19nh0Rre5BCB9JfLJV', remote_ip)

                    if recaptcha_response.is_valid:
                        Log.debug('Recaptcha is valid')
                        try:
                            User.objects.get(username=form.cleaned_data['username'])
                        except User.DoesNotExist:
                            user = User.objects.create_user(request.POST['username'], form.cleaned_data['email'], form.cleaned_data['password'])
                            user.is_active = False
                            user.first_name = form.cleaned_data['first_name']
                            user.last_name = form.cleaned_data['last_name']
                            user.groups.add(Group.objects.get(name='users'))
                            user.save()

                            salt = sha.new(str(random.random())).hexdigest()[:5]
                            activation_key = sha.new(salt+user.username).hexdigest()
                            key_expires = datetime.today() + timedelta(2)
                            
                            new_profile = UserProfile(user=user,
                                                      activation_key=activation_key,
                                                      key_expires=key_expires)
                            new_profile.save()
                            
                            email_subject = 'Kirinki account confirmation'
                            email_body = "Hello, %s, and thanks for signing up for an rstreaming account!\n\nTo activate your account, click this link within 48 hours:\n\n%s/account/confirm/%s" % (user.username, request.session['base_url'], new_profile.activation_key)
                            send_mail(email_subject,
                                      email_body,
                                      '*****@*****.**',
                                      [user.email.encode('utf-8')],
                                      fail_silently=False)

                            Message.pushMessage(request, Message.INFO, 'User registered. To activate the account please visit the url inicated in your email.')
                    else:
                        Log.debug('Recaptcha is not valid')
                        Message.pushMessage(request, Message.ERROR, 'User not registered. ' + recaptcha_response.error_code)
            else:
                Log.debug('Form is not valid')
                for error in form.errors:
                    Message.pushMessage(request, Message.ERROR, 'Error en ' + error + ': ' + str(form._errors[error]))

            if request.META.get('HTTP_REFERER', False) is not False:
                self.render = HttpResponseRedirect(request.META['HTTP_REFERER'])
            else:
                self.render = HttpResponseRedirect('/index')
        else:
            raise Http404
Beispiel #8
0
    def __init__(self, request):
        if request.session.get('isConfig', False) is False:
            Config.getSession(request.session)

        if request.method == 'GET':
            # GET request
            form = StrForm(error_class=ErrorClear)
            form.fields['isVideo'].initial = False
            form.fields['srcIP'].initial = request.META['REMOTE_ADDR']
            form.fields['srcPort'].initial = 9000
            form.fields['vStream'].choices = self.userVideos(request)
            self.render = MainViewer(request).render([], [render_to_string('kirinki/form.html', {'form' : form, 'action' : request.session['base_url'] + '/stream', 'id' : 'stream'}, context_instance=RequestContext(request))], [])
            
        elif request.method == 'POST':
            # POST request
            form = StrForm(request.POST, error_class=ErrorClear)
            form.fields['isVideo'].initial = False
            form.fields['srcIP'].initial = request.META['REMOTE_ADDR']
            form.fields['srcPort'].initial = 9000
            form.fields['vStream'].choices = self.userVideos(request)

            # Check if the form data is valid and try to start the streaming
            if form.is_valid():
                try:
                    v = video.objects.filter(idVideo=form.cleaned_data['vStream'])[0]
                except video.DoesNotExist:
                    v = None
                    
                if form.cleaned_data['isVideo'] is True and v is not None:
                    clvc = None
                    if v.format == 'video/mp4':
                        cvlc = subprocess.Popen(["/usr/bin/cvlc " + v.path + " --sout '#http{mux=ffmpeg{mux=flv},dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"],
                                                shell=True)
                    elif v.format == 'video/webm':
                        cvlc = subprocess.Popen(["/usr/bin/cvlc " + v.path + " --sout '#http{mux=webm,dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"],
                                                shell=True)
                    elif v.format == 'video/ogg':
                        cvlc = subprocess.Popen(["/usr/bin/cvlc " + v.path + " --sout '#http{mux=ogg,dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"],
                                                shell=True)
                    else:
                        Message.pushMessage(request, Message.ERROR,'Video type not supported')

                    if clvc is not None:
                        vStream = streaming(src=form.cleaned_data['srcIP'], port=form.cleaned_data['srcPort'], mux=form.cleaned_data['srcMux'], vMode=form.cleaned_data['isVideo'], pid=cvlc.pid,video=v, owner=request.session['user'])
                        vStream.save()
                        Message.pushMessage(request, Message.INFO,'Video streaming')
                elif form.cleaned_data['isVideo'] is False:
                    if form.cleaned_data['srcMux'] != "ffmpeg{mux=flv}" and form.cleaned_data['srcMux'] != "webm" and form.cleaned_data['srcMux'] != "ogg":
                        Message.pushMessage(request, Message.ERROR,'Video type not supported')
                    else:
                        cvlc = subprocess.Popen(["/usr/bin/cvlc http://" + str(form.cleaned_data['srcIP']) + ":" + str(form.cleaned_data['srcPort']) + " --sout '#http{mux=" + str(form.cleaned_data['srcMux']) + ",dst=" + request.session['strIP'] + ":" + request.session['strPort'] + "/} -no-sout-rtp-sap -no-sout-standard-sap -sout-keep' --ttl 12"],
                                                shell=True)
                        vStream = streaming(src=form.cleaned_data['srcIP'], port=form.cleaned_data['srcPort'], mux=form.cleaned_data['srcMux'], vMode=form.cleaned_data['isVideo'], pid=cvlc.pid,video=v, owner=request.session['user'])
                        vStream.save()
                        Message.pushMessage(request, Message.ERROR, 'External video streaming.')
                else:
                    Message.pushMessage(request, Message.ERROR, 'If you select the video mode you must select a video.')
                # os.waitpid(p.pid, 0)[1]
                self.render = HttpResponseRedirect('/streaming')
            else:
                for error in form.errors:
                    Message.pushMessage(request, Message.ERROR, 'Error en ' + error + ': ' + str(form._errors[error]))
                if request.META.get('HTTP_REFERER', False) is not False:
                    self.render = HttpResponseRedirect(request.META['HTTP_REFERER'])
                else:
                    self.render = HttpResponseRedirect('/index')
        else:
            raise Http404
Beispiel #9
0
    def __init__(self, request, action=0, key=None):
        if request.session.get('isConfig', False) is False:
            Config.getSession(request.session)

        # Blocks assigned to the left area
        leftBlocks = []
        if not request.session['user'].is_authenticated():
            leftBlocks = [render_to_string('kirinki/section.html', {'title' : 'login', 'content': render_to_string('kirinki/form.html', {'form' : LoginForm(), 'action' : request.session['base_url'] + '/login'}, context_instance=RequestContext(request))})]
        else:
            try:
                myVideos = video.objects.filter(owner = request.session['user'])
                leftBlocks = [render_to_string('kirinki/section.html', {'title' : 'Mis vídeos', 'content' : render_to_string('kirinki/myVideo.html', {'videos' : myVideos, 'session' : request.session}).encode('utf-8')})]
            except video.DoesNotExist:
                pass

        # Blocks assigned to the center area
        centerBlocks = []
        if action == self.LIST:
            try:
                videoList = video.objects.all()
                centerBlocks = [render_to_string('kirinki/section.html', {'title' : 'Lista de videos', 'content': render_to_string('kirinki/videoList.html', {'videos' : videoList, 'session' : request.session}).encode('utf-8')})]
            except video.DoesNotExist:
                pass
        elif action == self.VIEW:
            if key is not None:
                try:
                    v = video.objects.get(idVideo=key)
                    bfile = '/media/'+v.path[v.path.rfind('/')+1:v.path.rfind('.')]
                    src = {'orig' : request.session['base_url'] + '/media/'+v.path[v.path.rfind('/')+1:]}
                    if os.path.exists(v.path[:v.path.rfind('.')]+'.ogv'):
                        src['ogv'] = request.session['base_url'] +bfile+'.ogv'
                    if os.path.exists(v.path[:v.path.rfind('.')]+'.webm'):
                        src['webm'] = request.session['base_url'] +bfile+'.webm'
                    if os.path.exists(v.path[:v.path.rfind('.')]+'.mp4'):
                        src['mp4'] = request.session['base_url'] +bfile+'.mp4'
                    if os.path.exists(v.path[:v.path.rfind('.')]+'.flv'):
                        src['flv'] = request.session['base_url'] +bfile+'.flv'
                    src['flash'] = request.session['base_url']+'/static/flowplayer/flowplayer-3.2.5.swf'
                    src['flash_str'] = request.session['base_url']+'/static/flowplayer.pseudostreaming/flowplayer.pseudostreaming-3.2.5.swf'
                    centerBlocks = [render_to_string('kirinki/section.html', {'title' : v.name, 'content': render_to_string('kirinki/video.html', {'controls' : True, 'src' : src})})]
                except video.DoesNotExist:
                    pass
        elif action == self.DELETE:
                try:
                    v = video.objects.get(idVideo=key, owner=request.session['user'])
                    name = v.name
                    os.remove(v.path)
                    v.delete()
                    centerBlocks = ['<p>Video ' + name + ' deleted.</p>']
                except video.DoesNotExist:
                    pass
        elif action == self.REFERENCE:
            pass
        else:
            # Error. Action not defined
            raise Http404

        # Blocks assigned to the right area
        # Ultimos subidos, ultimos usuarios que han subido, usuarios que mas han subido, ...
        rightBlocks = []

        self.render = MainViewer(request).render(leftBlocks, centerBlocks, rightBlocks)