Example #1
0
    def requestRegister(self, uid):
        """The client sends the registration data to the server
        and start pings as a keepalive detection"""
        self.uuid = uid
        self.my_server = self.transport.getPeer()
        self.mylogin = MyUtils.getLoginName()
        self.hostip = NetworkUtils.get_ip_inet_address(self.transport.getPeer().host)
        is_host_not_user = (self.mylogin=='root')
        isLTSP = MyUtils.isLTSP()

        info_host = {'login' : self.mylogin,
                   'hostname' : NetworkUtils.getHostName(),
                   'hostip' : self.hostip,
                   'ltsp' : isLTSP != '',
                   'classname' : Configs.RootConfigs['classroomname'],
                   'isHostnotUser' : is_host_not_user ,
                   'uuid' : self.uuid
                   }                 

        if is_host_not_user :
            info_host['mac'] = NetworkUtils.get_inet_HwAddr(self.transport.getPeer().host)
        else:
            info_host['username'] = MyUtils.getFullUserName()
            info_host['ipLTSP'] = isLTSP
            info_host['internetEnabled'] = Configs.MonitorConfigs.GetGeneralConfig('internet') == '1'
            info_host['mouseEnabled'] = Configs.MonitorConfigs.GetGeneralConfig('mouse') == '1'
            info_host['soundEnabled'] = Configs.MonitorConfigs.GetGeneralConfig('sound') == '1'
            info_host['messagesEnabled'] = Configs.MonitorConfigs.GetGeneralConfig('messages') == '1'
            info_host['photo'] = ''
            
        self.doPing()            
        return {'result': info_host}                
Example #2
0
    def startdelayedViewer(self,target):        

        passwd=tempfile.mkstemp()[1]
        self.createVNCPassword(self.readPasswd, passwd)
        command='xvncviewer -UseLocalCursor=0 -LowColourLevel=1 -ViewOnly -MenuKey Super_R  -Shared  -Fullscreen -passwd '
        command += passwd 
        command += ' ' + target +':' + self.clientport
        self.procViewer=MyUtils.launchAsNobody(command)      
        MyUtils.dpms_on()
Example #3
0
 def getTreeHome(self):
     path=MyUtils.getHomeUser()
     user=MyUtils.getLoginName()
     r=['<ul class="jqueryFileTree" style="display: none;">']
     r.append('<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % (path,user))
     r.append('<li class="directory collapsed"><a href="#" rel="/media/">Media</a></li>' )        
     r.append('</ul>')
     
     return  ''.join(r)        
Example #4
0
 def screenshot(self):
     from twisted.internet import reactor        
     import xmlrpclib
     
     screenshot_thumb=os.path.join( MyUtils.getHomeUser(),'.controlaula/vnc-thumb.png')
     if MyUtils.snapshot(screenshot_thumb):        
         try:
             f = xmlrpclib.Binary(open(screenshot_thumb, 'rb').read())
             self.myteacher.screenshot(self.mylogin,self.myIP,f)         
         except:
             logging.getLogger().error('The user %s could not send its photo' % (self.mylogin))   
     if self.activeBB:     
         reactor.callLater(5, self.screenshot)
Example #5
0
 def addRequest(self, uri, file,exitfunc):
     self.exitfunc=exitfunc
     if len(self.deferreds) >= self.SIZE:
         # wait for completion of all previous requests
         DeferredList(self.deferreds
         ).addCallback(self._callback)
         self.deferreds = []
         
         # queue the request
         deferred = Deferred()
         self.requests.append((uri, file,deferred))
         
         return deferred
     else:
         # execute the request now
         #deferred = downloadPage(url, file)
         host, port, url = MyUtils.parse(uri)
         f = client.HTTPDownloader(uri, file)
         f.deferred.addCallbacks(callback=self.exitfunc,
                             callbackArgs=(file,) )
                 
         self.deferreds.append(f.deferred)
         reactor.connectTCP(host, port, f)
         
         return f.deferred
Example #6
0
def switch_off():
    from twisted.internet import reactor
    import os.path
    if os.path.exists('/usr/sbin/ethtool'):
        try:
            subprocess.call(['ethtool','-s','eth0','wol','g'])
        except:
            pass #this will fail if eth0 does not exist
                            
    if MyUtils.isLTSP()=='':                      
        subprocess.call(['killall','-9','x-session-manager'])            
    else:
        subprocess.call(['poweroff','-w'])
        try:
            server,socket = MyUtils.getLDMinfo()
            if server!='':
                subprocess.call(['ssh','-O','exit','-S',socket,server])           
        except:
            pass            

    reactor.callLater(1,die)    
Example #7
0
    def sendNext():
        global myIp
        global exitStatus
        nuevaIP = NetworkUtils.get_ip_inet_address()

        if myIp != "None" and myIp != nuevaIP:
            exitStatus = 97
            reactor.stop()
        else:
            myIp = nuevaIP

        if not MyUtils.isActive():
            reactor.stop()
Example #8
0
 def __init__(self,readonly=True,readpasswd='',writepasswd='',clientport=5400):
     '''
     Parameters:
     readonly=True if the server won't allow keyboard and mouse control
     readpasswd= passwd to use when not controlling keyboard and mouse
     writepasswd= passwd to use when controlling keyboard and mouse
     clientport=the port the client has to use to connect to a VNC server
     '''
     if readpasswd=='':
         self.readPasswd=MyUtils.generateUUID()
     else:
         self.readPasswd=readpasswd
         
     if writepasswd=='':
         self.writePasswd=MyUtils.generateUUID()
     else:
         self.writePasswd=writepasswd
         
     self.isLTSP=MyUtils.isLTSP()
         
     if self.isLTSP=='':
         self.port=str(NetworkUtils.getUsableTCPPort('127.0.0.1',5400))
     else:
         d=self.isLTSP.split('.')
         if len(d)<4: #sometimes, it needs two tries :(
             d=self.isLTSP.split('.')
         self.port=str(5400 + int(d[3]))
         
     self.readonly=readonly
     
     self.procServer=None
     self.clientport=clientport
     self.myteacher=None
     self.mylogin=MyUtils.getLoginName()
     self.myIP=''
     self.activeBB=False
Example #9
0
def disableKeyboardAndMouse(newAction=True):   
    global used_display
    
    if newAction:
        for i in glob('/tmp/*.controlaula'):
            remove( i)        
    try:
        disp=MyUtils.getXtty()[0]     
        if used_display is None:
            used_display=Display(disp)
        root = used_display.screen().root
        root.grab_pointer(1, X.PointerMotionMask|X.ButtonReleaseMask|X.ButtonPressMask,  
                    X.GrabModeAsync, X.GrabModeAsync, X.NONE, X.NONE, X.CurrentTime) 
        root.grab_keyboard(1,X.GrabModeAsync, X.GrabModeAsync,X.CurrentTime)                    
    except:
        pass           
Example #10
0
    def findNamePosition(self, hostname):
        position = -1
        number = MyUtils.getDesktopNumber(hostname)
        if number != "":
            position = int(number)
            if position > 0:
                # position -=1
                position = len(self.Desktops) - position
                if position < 1:
                    position = self.placeHostFreely()
            if self.Desktops[position].hostkey != "":
                self.shiftDesktop(position)  # The position was busy by a host and it has to be moved
        else:
            position = self.placeHostFreely()

        return position
Example #11
0
    def openSendFiles(self,path):
        import os.path,subprocess            
        commands={'gnome':'nautilus','kde':'konqueror','xfce':'thunar','lxde':'pcmanfm'}
        desktop=MyUtils.guessDesktop()            
        if desktop in commands:
            command=commands[desktop]
        else:
            command='thunar'

        if path=='dirReceivedTeacher':
            file_path=Configs.FILES_DIR
        else:
            file_path=os.path.dirname( os.path.join(Configs.FILES_DIR,path))
                   
        try:
            subprocess.Popen([command,file_path])
        except:
            pass #not recognized file browser
Example #12
0
 def _callback(self):
     if len(self.requests) >self.SIZE:
         queue = self.requests[:self.SIZE]
         self.requests = self.requests[self.SIZE:]
     else:
         queue = self.requests[:]
         self.requests = []
     
     # execute the requests
     for (uri,file,  deferredHelper) in queue:
         
         host, port, url = MyUtils.parse(uri)
         f = client.HTTPDownloader(uri, file)
         f.deferred.addCallbacks(callback=self.exitfunc,    callbackArgs=(file,))
                 
         self.deferreds.append(f.deferred)
         reactor.connectTCP(host, port, f)            
                 
         f.deferred.chainDeferred(deferredHelper)
Example #13
0
 def _handle_chat(self, request):
                
     request.content.read() 
     if request.path=='/student/':                    
         if len(request.args)>0:
             requestedfile=os.path.join(self.PageDir,'chat.html')
             try:
                 page_to_send =open(requestedfile, "r").read()
                 html_to_send=page_to_send.replace('%(student_id)', request.args['login'][0])
                 return html_to_send 
             except:
                 request.setResponseCode(404)
                 return"""
                 <html><head><title>404 - No Such Resource</title></head>
                 <body><h1>No Such Resource</h1>
                 <p>File not found: %s - No such file.</p></body></html>
                 """ % requestedfile     
     else: #chatting
         user_host=request.client.host             
         user = request.args.get('user', user_host)
         key=user[0] + '@' + user_host
         try:
             if MyUtils.getLoginName() + '@127.0.0.1'!=key: 
                 if self.teacher.classroom.LoggedUsers[key].chat_enabled==False:return self.response_ok()
         except:
             return self.response_ok()
                        
         message = request.args.get('message', None)
         
         if not message:
             return self.response_fail(['*message* not found', ])
         message = cgi.escape(message[0])
         response = self.response_ok(user= [  '('+strftime('%H:%M:%S') + ') '+ user[0]], message=message)
         chat_logger = logging.getLogger('Chat')
         chat_logger.info(user[0] + ": " + message )            
         for chann_request in self.channels['controlaula-chat']:
             chann_request.write(response)
             chann_request.finish()
         del self.channels['controlaula-chat']
         return self.response_ok()         
Example #14
0
 def receive(self,encodec=False,teacherIP=''):        
     self.destroyProcess(self.procRx) 
     my_login = MyUtils.getLoginName()
     isLTSP = (MyUtils.isLTSP()!='')
     if my_login == 'root': NetworkUtils.cleanRoutes()              
     command = 'vlc -I dummy ' 
     if isLTSP:
         command +=  ' --no-overlay --vout=xcb_x11 '
     command +=  '--quiet --video-on-top --skip-frames --sout-display-delay=1100  --sub-track=0 --no-overlay '
     
     command +='  -f  rtp://@239.255.255.0:'
     command += self.port 
     logged=MyUtils.logged_user()
     if not isLTSP and my_login != 'root':
         self.procRx=subprocess.Popen(command, stdout=subprocess.PIPE,shell=True)
         MyUtils.launchAs("xset s off",my_login)
     else:    
         if logged !='root':
             self.procRx=MyUtils.launchAs(command, logged)
             MyUtils.launchAs("xset s off",logged)                
         else:        
             self.procRx=MyUtils.launchAsNobody(command)
               
     MyUtils.dpms_on()        
     Actions.disableKeyboardAndMouse(False)
Example #15
0
    myapp = singleinstance(os.path.join(Configs.APP_DIR, 'controlaula.pid'))
    if myapp.alreadyrunning():
        sys.exit("Another instance of this program is already running")

    log_handler = logging.handlers.RotatingFileHandler(Configs.LOG_FILENAME, maxBytes = 100000, backupCount = 5)
    log_formatter = logging.Formatter(fmt = '%(asctime)s %(levelname)-8s %(message)s', datefmt = '%a, %d %b %Y %H:%M:%S')
    log_handler.setFormatter(log_formatter)
    root_logger = logging.getLogger()
    root_logger.addHandler(log_handler)
    root_logger.level = logging.DEBUG

    # Initialise the signal handler.
    signal.signal(signal.SIGINT, SigHandler)

    #Get and save some global variables:
    isTeacher = MyUtils.userIsTeacher()

    #isTeacher=False  #enable for debugging
    USERNAME = MyUtils.getLoginName()
    HOSTNAME = NetworkUtils.getHostName()
    Configs.PORT = NetworkUtils.getUsableTCPPort("localhost", PORT)
    MyUtils.putLauncher('', Configs.PORT, isTeacher)

    if not isTeacher:
        from twisted.internet import glib2reactor
        glib2reactor.install()
    from twisted.internet import reactor
    from twisted.web import server
    
    ######### Begin the application loop #######
    if  isTeacher:
Example #16
0
def die():
    if MyUtils.isLTSP()=='':
        subprocess.Popen(['poweroff','-hp'])
    else:
        subprocess.Popen(['poweroff','-fp'])    
Example #17
0
    def render_POST(self, request):
        """ Process a POST and return a response. This will handle
        all the AJAX read and write requests for data.
        """        
        if request.path=='/RPC2':
            return self.teacher.render(request)
        elif request.path == '/BROWSER':
            filter_port = request.client.port
            data_to_return = MyUtils.launcherData(str(filter_port))
            return json.dumps(data_to_return)
        
        #Filter the command needed.
        command=request.path[1:]

        handler=Handler.Plugins(self.teacher.classroom)
        respjson=None       
        args=''
        
        #print command

        if 'controlaula-chat' in request.path:
            return self._handle_chat(request)
        
        #petition from the student controlaula
        student_asks=(request.path[:9]=='/student/')
        if student_asks:
            command=command.replace('student/','')            
            if command=='':
                return self._handle_chat(request)
                    
        try:
            recvjson='{}'            
            request.content.read()          
            if request.args.has_key('data'):
                recvjson = request.args['data'][0]    
                if recvjson=='':
                    recvjson='{}'        
            if json.loads(recvjson).has_key('args'):
                args=json.loads(recvjson)['args']
        except:
            pass
        
        if command=='index.html':
            if args==Configs.TEACHER_UID:
                session = request.getSession()    
                self.teacher_login=session.uid
                request.redirect('index.html')
            return '{}'
        
        if args=='':
            try:
                if 'dir' in request.args:
                    args=request.args['dir']
                elif 'message' in request.args:
                    args=request.args['message']    
            except:
                pass
                            
        if handler.existCommand(command):          
            #if it's a petition to execute some command
            try:
                if len(args)>0:
                    handler.args=[args] 
                else:
                    handler.args=[]
                if student_asks and command!='language':
                    if 'user_id' in request.args:                                         
                        user_key=request.args['user_id'][0] + '@' + request.client.host
                        if  type(args)!=type([]):
                            args=[args]
                        self.teacher.classroom.addCommand( user_key,command,args)
                        if command=='getAllNodes':
                            self.teacher.classroom.LoggedUsers[user_key].deferred_request=request
                            return server.NOT_DONE_YET                                 
                        else:                        
                            return json.dumps({'result':'ack'})
                                                          
                    #handler.args=['/opt/'+args]
                if json.loads(recvjson).has_key('pclist'):
                    first=json.loads(recvjson)['pclist'][0]
                    if ',' in first:
                        handler.targets=first.split(',')
                    else:
                        handler.targets=json.loads(recvjson)['pclist']
                
                if json.loads(recvjson).has_key('structure'):
                    structure=json.loads(recvjson)['structure']    
                    handler.args=[structure['rows'],structure['cols'],structure['computers']]
                result=handler.process(command)
                #respjson= json.dumps({'result':'ack'})
                if command not in ( 'getAllNodes' ,'getVideoNodes'):
                    respjson=json.dumps(result)
                else:
                    respjson=result
            except:
                pass
                
        else:
            #it's sending the classroom data
            try:                
                if command == 'datosaula':
                    if self.teacher.classroom.current_request==None or args=='refresh':
                        if self.teacher.classroom.current_request!=None: #close previously open request
                            try:
                                self.teacher.classroom.current_request.finish()
                            except:
                                pass #the connection is lost
                            self.teacher.classroom.oldJSON=''                            
                        self.teacher.classroom.current_request=request
                        self.teacher.classroom.getJSONFrontend(args)
                    else:
                        self.teacher.classroom.current_request=request
                    return server.NOT_DONE_YET                          
                else:
                    # Analyse the request and construct a response.
                    respjson= self._HandleMessage(recvjson) 
                    
            except:
                # The data wasn't found in the headers.
                pass

        # Return the JSON response.
        return respjson
Example #18
0
 def getLogin(self):
     return {'login':MyUtils.getLoginName() }