def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowIcon(QIcon('./Icons/water-dispenser.png'))
        QtWidgets.QApplication.instance().focusChanged.connect(
            self.on_focusChanged)

        self.powerOffButton.setIcon(QIcon('./Icons/turn-off.png'))

        self.userDatabase = UserDatabase()
        self.searchKeyboard = None

        self.instantiateUserListWidget()
Beispiel #2
0
    def __init__(self, config, version):
        self.configuration = config
        self.memory = {}
        self.memory['nick'] = config['nick']
        self.version = version

        # A place to keep track of the plugins with various bot functions
        # Keys are each function, values are the name of the plugins with that function
        function_list = [
            'action', 'connectionMade', 'kickedFrom', 'names', 'signedOn',
            'joined', 'on_ctcp', 'userJoined', 'userKicked', 'modeChanged',
            'userRenamed', 'userLeft', 'privmsg', 'userQuit', 'topicUpdated'
        ]

        self.users = UserDatabase(self, User, 'users/')
        self.groups = Database(self, Group, 'groups/')
        self.channels = ChannelDatabase(self, Channel)
        self.plugins = PluginDatabase(self, function_list)
        self.plugins.loadAll()
Beispiel #3
0
def register():
    p = json.loads(request.data)
    name = p["username"]
    pwd = p["password"]
    ret = US.register(name, pwd)
    if ret == 0:
        session['username'] = name
        return "0"
    if ret == 1:
        return "1"
    return ""
Beispiel #4
0
def login():
    """
    Login function.
    add session.
    return 0 if 'login success';
    return 1 if 'no such user';
    return 2 if 'password error';
    """
    p = json.loads(request.data)
    name = p["username"]
    pwd = p["password"]
    ret = US.Login(name, pwd)
    if ret == 0:
        session['logged'] = "1"
        session['username'] = name
        return "0"
    if ret == 1:
        return "1"
    if ret == 2:
        return "2"
    return ""
Beispiel #5
0
 def __init__(self):
     self.Clients = {}
     self.OnlineUser = {}
     self.Db = UserDatabase(DATABASE_PATH)
     self.InitSocket()
     self.IsGame = False
Beispiel #6
0
class ChatroomServer:
    def __init__(self):
        self.Clients = {}
        self.OnlineUser = {}
        self.Db = UserDatabase(DATABASE_PATH)
        self.InitSocket()
        self.IsGame = False

    def InitSocket(self):
        self.ServerSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.ServerSocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        self.ServerSocket.bind((SERVER_IP,SERVER_PORT))
        self.ServerSocket.listen(MAX_CLIENT_NUM)
        self.SocketList = [self.ServerSocket]

    def Start(self):
        while True:
            print ('Waiting client connect..')
            rx,_,ex = select.select(self.SocketList,[],[])
            for notified_socket in rx:
                if notified_socket == self.ServerSocket:
                    client_socket,client_addr = self.ServerSocket.accept()
                    self.SocketList.append(client_socket)
                    self.Clients[client_socket] = SocketInfo()
                    client_socket.sendall('>>>Successfully connected to server\r\n$')
                    print ('Accepted new connection from {}'.format(*client_addr))
                else:
                    message = self.Readline(notified_socket)
                    if message is False:
                        self.SocketList.remove(notified_socket)
                        self.HandleLogout(notified_socket)
                    elif self.ParseMessage(notified_socket,message) is False:
                            notified_socket.sendall('>>>Command error!\r\n$')

    def Readline(self,client_socket):
        message = ''
        while True:
            try:
                c = client_socket.recv(BUFFER_SIZE)
                if not c:
                    return False
                elif c == '\r\n':
                    return message
                elif c == '\b':
                    if not message:
                        client_socket.sendall('$')
                    else:
                        message = message[:-1]
                        client_socket.sendall('\x20\x08')
                else:
                    message += c
            except:
                return False

    def ParseMessage(self,client_socket,msg):
        msg = msg.strip().split(' ')
        length = len(msg)
        if length == 3 and msg[0] == MSG_LOGIN:
            self.HandleLogin(client_socket,msg[1],msg[2])
        elif length == 3 and msg[0] == MSG_REGISTER:
            self.HandleRegister(client_socket,msg[1],msg[2])
        elif length > 1 and msg[0] == MSG_CHAT:
            message = ' '.join(msg[1:])
            self.HandleChat(client_socket, message)
        elif length == 2 and msg[0] == MSG_INFO:
            self.HandleInfo(client_socket, msg[1])
        elif length == 2 and msg[0] == MSG_ROLLSTART:
            self.HandleGameStart(client_socket,msg[1])
        elif length == 1 and  msg[0] == MSG_LOGOUT:
            self.HandleLogout(client_socket)
        elif length == 1 and msg[0] == MSG_ROLL:
            self.HandleRoll(client_socket)
        else:
            return False
        return True

    def HandleRegister(self,client_socket,name,password):
        state = self.Clients[client_socket].state
        if state == STATE_ONLINE:
            client_socket.sendall('>>>you need to logout\r\n$')
        elif not self.Db.QueryUserName(name):
            register_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.Db.AddUser(name,password,register_time)
            client_socket.sendall('>>>{} has been created successfully!\r\n$'.format(name))
        else:
            client_socket.sendall('>>>{} already exist!\r\n$'.format(name))


    def HandleLogin(self,client_socket,name,password):
        state = self.Clients[client_socket].state
        if name in self.OnlineUser.keys():
            client_socket.sendall('>>>{} logged in!\r\n$'.format(name))
        elif state == STATE_ONLINE:
            client_socket.sendall('>>>you have logged in another user!\r\n$')
        elif not self.Db.QueryUserLogin(name,password):
            client_socket.sendall('>>>login failed!\r\n$')
        else:
            self.OnlineUser[name] = UserInfo()
            self.OnlineUser[name].onlineTime,_,flag = self.Db.GetUserTimeInfo(name)
            self.OnlineUser[name].startTime = time.time()
            self.Clients[client_socket].username = name
            self.Clients[client_socket].message = password
            self.Clients[client_socket].state = STATE_ONLINE
            self.BroadcastMessage('{} login'.format(name),client_socket)

    def HandleLogout(self,client_socket):
        state = self.Clients[client_socket].state
        if state == STATE_OFFLINE:
            client_socket.sendall('>>>you need to login\r\n$')
        else:
            name = self.Clients[client_socket].username
            self.BroadcastMessage('{} logout'.format(name),client_socket)
            self.Clients[client_socket].state = STATE_OFFLINE
            self.Db.UpdateOnlineTime(name,self.GetOnlineTime(name))
            del self.OnlineUser[name]

    def HandleInfo(self,client_socket,name):
        state = self.Clients[client_socket].state
        if state == STATE_OFFLINE:
            client_socket.sendall('>>>you need to login\r\n$')
        elif not self.Db.QueryUserName(name):
            client_socket.sendall('>>>{} does not exist\r\n$'.format(name))
        else:
            if self.OnlineUser.has_key(name):
                self.Db.UpdateOnlineTime(name,self.GetOnlineTime(name))
            onlineTime, createTime, _ = self.Db.GetUserTimeInfo(name)
            client_socket.sendall('>>>{} info:\r\n'.format(name))
            client_socket.sendall('>>>create time: {}\r\n'.format(createTime))
            client_socket.sendall('>>>online time: {}\r\n$'.format(onlineTime))


    def HandleChat(self,client_socket,message):
        state = self.Clients[client_socket].state
        if state == STATE_OFFLINE:
            client_socket.sendall('>>>you need to login\r\n$')
        else:
            name = self.Clients[client_socket].username
            self.BroadcastMessage('{}:{}'.format(name,message),client_socket)

    def HandleGameStart(self,client_socket,inputTime):
        try:
            state = self.Clients[client_socket].state
            if self.IsGame is True:
                client_socket.sendall('>>>The game has started\r\n$')
            elif state == STATE_OFFLINE:
                client_socket.sendall('>>>you need to login\r\n$')
            else:
                gameTime = int(inputTime)
                Timer(gameTime,self.HandleGameOver).start()
                name = self.Clients[client_socket].username
                message = '{} start a roll game (will end in {} sec)'.format(name,gameTime)
                self.IsGame = True
                self.BroadcastMessage(message,client_socket)

        except ValueError:
            client_socket.sendall('>>>Please enter a proper time\r\n$')


    def HandleGameOver(self):
        winners,flag = self.GetWinner()
        if not flag:
            self.BroadcastMessage('No winner')
        else:
            for winner in winners:
                message = '{}({}) win the roll game!'.format(winner[0],winner[1])
                self.BroadcastMessage(message)
        self.IsGame = False
        self.ClearUserRoll()


    def HandleRoll(self,client_socket):
        state = self.Clients[client_socket].state
        if state == STATE_OFFLINE:
            client_socket.sendall('>>>you need to login\r\n$')
        elif self.IsGame:
            name = self.Clients[client_socket].username
            roll = random.randint(1,100)
            self.OnlineUser[name].rollValue = roll
            self.BroadcastMessage('{} roll:{}'.format(name,str(roll)),client_socket)
        else:
            client_socket.sendall('>>>Game not start\r\n$')

    def BroadcastMessage(self,message,client_socket=''):
        for other_socket in self.Clients.keys():
            state = self.Clients[other_socket].state
            if state == STATE_ONLINE:
                if other_socket != client_socket:
                    other_socket.sendall('\r\n>>>{}\r\n$'.format(message))
                else:
                    other_socket.sendall('>>>{}\r\n$'.format(message))

    def GetWinner(self):
        res = [('',0)]
        flag = True
        for name in self.OnlineUser.keys():
            rollValue = self.OnlineUser[name].rollValue
            if rollValue >= res[-1][1]:
                if rollValue != res[-1][1]:
                    res.pop()
                res.append((name,rollValue))
        if res[-1][0] == '':
            flag = False
        return res,flag

    def ClearUserRoll(self):
        for name in self.OnlineUser.keys():
            self.OnlineUser[name].rollValue = -1

    def GetOnlineTime(self,name):
        startTime = self.OnlineUser[name].startTime
        onlineTime,_,_ = self.Db.GetUserTimeInfo(name)
        curTime = time.time()
        self.OnlineUser[name].startTime = curTime
        return int(curTime - startTime) + onlineTime
class MainWindow(QWidget, MainWindow_ui.Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowIcon(QIcon('./Icons/water-dispenser.png'))
        QtWidgets.QApplication.instance().focusChanged.connect(
            self.on_focusChanged)

        self.powerOffButton.setIcon(QIcon('./Icons/turn-off.png'))

        self.userDatabase = UserDatabase()
        self.searchKeyboard = None

        self.instantiateUserListWidget()

    @pyqtSlot()
    def on_addNewUserButton_clicked(self):

        addingNewUserDialog = AddingNewUser(parent=self,
                                            userDatabase=self.userDatabase)
        addingNewUserDialog.show()

        self.instantiateUserListWidget()

    def instantiateUserListWidget(self):
        usersList = self.userDatabase.getUsersList()
        self.userListWidget.clear()
        for user in usersList:
            self.userListWidget.addItem("%s %s" %
                                        (user.lastName, user.firstName))

        self.userListWidget.sortItems(Qt.AscendingOrder)

    @pyqtSlot()
    def on_powerOffButton_clicked(self):
        resp = QMessageBox.question(self, 'Restart',
                                    'Do you want to turn off the device?',
                                    QMessageBox.Yes | QMessageBox.No,
                                    QMessageBox.No)
        if resp == QMessageBox.Yes:
            print('Power off')
            exit(0)

    @pyqtSlot("QWidget*", "QWidget*")
    def on_focusChanged(self, old, currentWidget):
        if self.nameSearchEdit == currentWidget:
            if not self.searchKeyboard:
                self.searchKeyboard = VirtualKeyboard(
                    parent=self, parentLineEdit=self.nameSearchEdit)
            self.searchKeyboard.exec()

    @pyqtSlot(QListWidgetItem)
    def on_userListWidget_itemClicked(self, item):
        lastName = item.text().split()[0]
        firstName = item.text().split()[1]
        user, status = self.userDatabase.findUserFromNames(firstName, lastName)

        if status == NOT_FOUND:
            return

        weightScreenDialog = WeightScreen(parent=self,
                                          user=user,
                                          userDatabase=self.userDatabase)
        weightScreenDialog.show()

        self.instantiateUserListWidget()

    @pyqtSlot(str)
    def on_nameSearchEdit_textChanged(self, keyword):
        self.userListWidget.clear()
        usersList = self.userDatabase.getUsersList()
        filtered_usersList = list(
            filter(
                lambda u: str("%s %s" % (u.lastName, u.firstName)).lower(
                ).startswith(keyword.lower()) or str("%s %s" % (
                    u.firstName, u.lastName)).lower().startswith(keyword.lower(
                    )) or u.firstName.lower().startswith(keyword.lower()) or u.
                lastName.lower().startswith(keyword.lower()), usersList))

        for user in filtered_usersList:
            self.userListWidget.addItem("%s %s" %
                                        (user.lastName, user.firstName))

        self.userListWidget.sortItems(Qt.AscendingOrder)
Beispiel #8
0
class EyeRCbot(irc.IRCClient):
    '''Here is the bot logic.'''
    linerate = 1
    sourceURL = 'http://code.google.com/p/eyercbot'

    def __init__(self, config, version):
        self.configuration = config
        self.memory = {}
        self.memory['nick'] = config['nick']
        self.version = version

        # A place to keep track of the plugins with various bot functions
        # Keys are each function, values are the name of the plugins with that function
        function_list = [
            'action', 'connectionMade', 'kickedFrom', 'names', 'signedOn',
            'joined', 'on_ctcp', 'userJoined', 'userKicked', 'modeChanged',
            'userRenamed', 'userLeft', 'privmsg', 'userQuit', 'topicUpdated'
        ]

        self.users = UserDatabase(self, User, 'users/')
        self.groups = Database(self, Group, 'groups/')
        self.channels = ChannelDatabase(self, Channel)
        self.plugins = PluginDatabase(self, function_list)
        self.plugins.loadAll()

    # ----------------------------- #
    # Protocol methods #
    # ----------------------------- #

    def connectionMade(self):
        '''Overide to allow nicks from yaml config'''
        # container for deferreds
        self._events = {}
        # container for NAME replies
        self._namreply = {}
        self._queue = []
        if self.performLogin:
            self.register(self.factory.configuration['nick'])

    # ---------------------------------- #
    # Callbacks for events #
    # --------------------------------- #
    # TODO: Add code so that function is only called if plugin is loaded for that channel?
    def signedOn(self):
        '''Called when succesfully signed on to server'''
        # Join channel when welcomed (?)
        for chan in self.channels.database:
            if chan != 'pm':
                self.join(chan)
        # if a plugin has the signedOn function, call it.
        for plugin in self.plugins.function['signedOn']:
            plugin.signedOn(self)

#	def joined(self, channel):
#		'''
#		Called when bot joins a channel. We use a pached library and defers to populate channel.
#		'''
#		def checkNames(defer):
#			self.channels.database[channel].nicks = defer[channel]
#			for nick in self.channels.database[channel].nicks:
#				i = self.channels.database[channel].nicks.index(nick)
#				self.channels.database[channel].nicks[i] = nick.lstrip('!@+%')
#		defered = self.names(channel)
#		defered.addCallback(checkNames)
#		'''Called when bot joins a channel'''
#		self.msg(channel, 'EyeRCbot Version: ' + str(self.version))
#		# If a plugin has joined function, call it
#		for plugin in self.plugins.function['joined']:
#			plugin.joined(self, channel.lower())

    def privmsg(self, user, target, msg):
        '''Called when bot receives public or private messages'''
        if self.configuration['isNew'] and msg.split()[0].startswith(
                'password'):
            self.newuser(user, msg)
        # If a plugin has privmsg function, call it
        for plugin in self.plugins.function['privmsg']:
            plugin.privmsg(self, user, target, msg)
        # Removes formatting as it inhibits commands
        text = re.compile(
            '[\x02\x1f\x16\x0f \x03[0-9]{1,2}(,[0-9]{1,2})?]').sub(
                '', msg).lower()
        # Bug fix -- empty line causes crash, so we just skip it
        if text.split() == []:
            return None
        # If user says first word a !, we react
        # We will need to check if the users plugin is installed and, if so, check their permissions
        if text.startswith('!'):
            try:
                # TODO: This should be threaded?
                # TODO: Remove !command from string before passing?
                # TODO: Command aliases
                if target.lower() == self.memory['nick'].lower(): target = 'pm'
                # Channel is lowered due to case sensitiviy here, but not in irc
                if text.split()[0].lstrip(
                        '!') in self.plugins.commands and text.split(
                        )[0].lstrip('!') in self.channels.database[
                            target.lower()].plugins:
                    # Scan for permission
                    if self.users.checkPermission(user, msg):
                        self.plugins.commands[text.split()[0].lstrip(
                            '!')].main(self, user, target, msg)
                    else:
                        self.message(user, target,
                                     "I can't let you use that command")
            except:
                print "Trigger Exception, traceback info forward to log file."
                self.message(
                    user, target,
                    "There has been an error. Diagnostics written to errlog.txt.  Please report this bug and upload this file to: http://code.google.com/p/eyercbot/issues/list"
                )
                traceback.print_exc(file=open("errlog.txt", "a"))

    def message(self, user, target, msg):
        '''Message logic to determine how to send response based on query (prv vs pub)
		Use msg() or notice() to overide this behavior.'''
        if target == self.memory['nick']:
            # Get by pm, respond by pm
            self.msg(user.split('!')[0], msg)
        else:
            # Get by public, respond by public
            self.msg(target, msg)

#	def irc_JOIN(self, prefix, params):
#		"""
#		Called when a user joins a channel.
#		"""
#		nick = string.split(prefix,'!')[0]
#		channel = params[-1]
#		joinSuccessful = self._events['JOIN'][channel.lower()]
#		if nick == self.nickname:
#			self.joined(channel)
#		else:
#			self.userJoined(prefix, channel)
#		# yet the callback has always nick, channel because it's hard
#		# to write callbacks that have to react on both possibilities
#		joinSuccessful.callback((nick, channel))
#

    def userJoined(self, user, channel):
        '''
		Call back when someone joins the channel.
		Logs nick to channel database.
		'''
        self.channels.database[channel.lower()].addNick(user)
        # if a plugin has the on_join function, call it.
        for plugin in self.plugins.function['userJoined']:
            plugin.userJoined(self, user, channel)

    def irc_PART(self, prefix, params):
        nick = string.split(prefix, '!')[0]
        channel = params[0]
        if nick == self.nickname:
            self.left(channel)
        else:
            self.userLeft(prefix, channel)

    def userLeft(self, user, channel):
        '''
		Callback for user leaving.
		Removes user from channel.
		'''
        self.channels.database[channel].removeNick(user.split('!')[0])
        # if a plugin has the on_part function, call it.
        for plugin in self.plugins.function['userLeft']:
            plugin.userLeft(self, user, channel)

    def irc_QUIT(self, prefix, params):
        nick = string.split(prefix, '!')[0]
        self.userQuit(prefix, params[0])

    # Reacts to clients leaving
    def userQuit(self, user, quitMessage):
        '''
		Callback for clients who quit.
		Removes user from all channels.
		'''
        self.channels.userQuit(user.split('!')[0])
        # if a plugin has the on_quit function, call it.
        for plugin in self.plugins.function['userQuit']:
            plugin.userQuit(self, user, quitMessage)

    def userKicked(self, kickee, channel, kicker, message):
        '''
		Callback when someone is kicked.
		Removes user form channel database.'''
        self.channels.database[channel].removeNick(kickee.split('!')[0])
        # if a plugin has the on_kick function, call it.
        for plugin in self.plugins.function['userKicked']:
            plugin.userKicked(self, kickee, channel, kicker, message)

    # When I see a user perform an action
    def action(self, user, channel, data):
        # if a plugin has the on_kick function, call it.
        for plugin in self.plugins.function['action']:
            plugin.action(self, user, channel, data)

    # On topic changes (and first join channel)
    def topicUpdated(self, user, channel, newTopic):
        # if a plugin has the on_topic function, call it.
        for plugin in self.plugins.function['topicUpdated']:
            plugin.topicUpdated(self, user, channel, newTopic)

    # On other user nick changes
    def userRenamed(self, oldname, newname):
        '''
		Callback when other users rename themselvs.
		Changes nick in database.
		Plugins are called before change in database
		'''
        # if a plugin has the on_nick function, call it.
        for plugin in self.plugins.function['userRenamed']:
            plugin.userRenamed(self, oldname, newname)
        self.channels.userRenamed(oldname.split('!')[0], newname.split('!')[0])

    #On mode changes
    def modeChanged(self, user, channel, set, modes, args):
        '''user	The user and hostmask which instigated this change. (type: str )
		channel	The channel for which the modes are changing. (type: str )
		set	true if the mode is being added, false if it is being removed. (type: bool or int )
		modes	The mode or modes which are being changed. (type: str )
		args	Any additional information required for the mode change. (type: tuple )'''
        # On user op: [email protected] #civfanatics True o ('TwistedEye',)
        # if a plugin has the on_mode function, call it.
        for plugin in self.plugins.function['modeChanged']:
            plugin.modeChanged(self, user, channel, set, modes, args)

    # When I am kicked
    def kickedFrom(self, channel, kicker, message):
        # If we are kicked we will attempt to rejoin
        self.join(channel)

    def quit(self, message=''):
        '''Clean shutdown of myself. Overides twisted library'''
        for chan in self.channels.database:
            self.msg(chan, 'Bot is shutting down. Saving database and memory.')
        self.users.saveAll()
        self.groups.saveAll()
        self.saveConfig()
        self.saveMemory()
        self.sendLine("QUIT :%s" % message)
        self.factory.halt()

    # -------------------------------- #
    # Application methods #
    # TODO: Move these?  #
    # -------------------------------- #

    def newuser(self, user, msg):
        '''First user to PM their password will be registered as owner'''
        self.users.makeEntry(user.split('!')[0])
        self.users.database[user.split('!')[0]].register(
            user,
            msg.split()[1], 'owner')
        # We now write the new user file
        self.users.save(user.split('!')[0])
        self.configuration['isNew'] = False
        self.saveMemory()
        self.saveConfig()
        self.users.load(user.split('!')[0])
        self.msg(user.split('!')[0], 'You have been registered as my owner.')

    def saveConfig(self):
        stream = file(self.configuration['nick'] + '.yaml', 'w')
        yaml.dump(self.configuration, stream)
        stream.close()

    # Bot will save its memory in a yaml file for backup
    def saveMemory(self):
        stream = file('memory/' + self.configuration['nick'] + '.yaml', 'w')
        yaml.dump_all([self.memory, self.users, self.groups], stream)
        stream.close()