def voiceCommand(self):
		#restricts guests from using this function
		if self.ww.name == None:
			self.label.setText('You must be logged in to use this function.')
			return

		self.label.setText('Please say a command.')

		#turns on microphone and returns audio as a string
		self.r = sr.Recognizer()
		with sr.Microphone() as source:
			audio = self.r.listen(source)

		#defines the logic for each type of voice command
		if 'go to' in self.r.recognize_google(audio):
			self.textbox.setText('')
			items = self.r.recognize_google(audio).split()
			self.goto(items[2].lower())
		elif 'clear data' in self.r.recognize_google(audio):
			self.textbox.setText('')
			database.deleteUser(self.ww.name)
			database.addUser(self.ww.name)
			self.ww.websites = ['google https://www.google.com/']
			self.ww.websitesDictionary = {'google': 'https://www.google.com/'}
			self.ww.homeScreen()
		elif 'add site' in self.r.recognize_google(audio):
			self.textbox.setText('')
			self.ww.addSite()
			self.label.setText('Done')
		elif 'go home' in self.r.recognize_google(audio):
			self.ww.homeScreen()
			self.label.setText('')
Exemple #2
0
def signup():
    users = database.getUsers()
    # checks if credentials for flash message
    if request.form.get('username') in users:
        flash("Username already taken")
    elif request.form.get('password0') != request.form.get('password1'):
        flash("Passwords do not match")
    else:
        flash("Please log in with your new credentials!")
        database.addUser(request.form.get('username'), request.form.get('password0'))
    return redirect(url_for('authentication'))
Exemple #3
0
def main():
    if(request.method == 'GET'):
        return render_template("home.html")
    else:
        username = request.form['username']
        password = request.form['password']
        if request.form['button'] == "login":
            if(database.verifyUser(username,password)):
                resp = make_response(redirect(url_for('scheduleMaker')))
                resp.set_cookie('username',username)
                return resp
            return redirect(url_for('main'))
        elif request.form['button'] == "register":
            database.addUser(username,password)
            return redirect(url_for('main'))
Exemple #4
0
def signup():
    users = database.getUsers()
    # checks if credentials for flash message
    if request.form.get('username') in users:
        flash("Yikes! Username already taken")
        return redirect(url_for('crt_acct'))
    elif request.form.get('password0') != request.form.get('password1'):
        flash("Yikes! Passwords do not match")
        return redirect(url_for('crt_acct'))
    else:
        flash("Yay! Please log in with your new credentials!")
        hash_object = hashlib.sha224(request.form.get('password0'))
        hashed_pass = hash_object.hexdigest()
        database.addUser(request.form.get('username'), hashed_pass)
        return redirect(url_for('authentication'))
def add_user():
    # Fetch form data
    userDetails = request.get_json()
    name = userDetails.get('name')
    password = userDetails.get('password')

    # Check if all data is supplied
    if name is None:
        return jsonify({"error": "Username not specified"}), 400
    if password is None:
        return jsonify({"error": "Password not specified"}), 400

    # Strip leading and trailing spaces
    name = name.strip()

    # Check is username and password comply to the requirements
    username_message = function.check_username(name)
    password_message = function.check_password(password)
    if (username_message is not "ok"):
        return jsonify({"error": username_message}), 400
    elif (password_message is not "ok"):
        return jsonify({"error": password_message}), 400

    # Check if the user already exists
    user = database.getUserByName(name)
    if user is not None:
        return "Username already exists", 400

    # Hash the userpassword for secure storage
    hashedpass = function.hash_password(password)

    # Add user to the database and return newly created userID
    user = database.addUser(name, hashedpass)
    return jsonify(user), 201
Exemple #6
0
def signup():
    username = ""
    displayName = ""
    errors = {}
    global user
    if request.method == "POST":
        with database.connect() as conn:
            username = request.form.get("username")
            if not username:
                errors["username"] = "******"
            elif len(username.split()) > 1 or username != username.strip():
                errors["username"] = "******"
            elif not database.unique(conn, "username", username):
                errors["username"] = username + " has been taken"

            displayName = request.form.get("displayName")
            if not displayName:
                errors["displayName"] = "enter a display name"
            elif displayName != displayName.strip():
                errors[
                    "displayName"] = "display name cannot start or end with spaces"
            elif not database.unique(conn, "displayName", displayName):
                errors["displayName"] = displayName + " has been taken"

            password = request.form.get("password")
            if not password:
                errors["password"] = "******"
            elif len(password.split()) > 1 or password != password.strip():
                errors["password"] = "******"

            confirmPassword = request.form.get("confirmPassword")
            if not confirmPassword:
                errors["confirmPassword"] = "******"
            elif password != None and password != confirmPassword:
                errors["confirmPassword"] = "******"

            if len(errors) == 0:
                user = User(username, displayName, password, 0)
                database.addUser(conn, user)
                return redirect("/")

    return render_template("signup.html",
                           username=username,
                           displayName=displayName,
                           errors=errors,
                           tab="signup",
                           user=user)
Exemple #7
0
def start(message):
    user = User(message.chat.username)
    #dictUser[message.chat.id] = user

    db.addUser(str(message.chat.id))

    db.createSession(message.chat.id, user.exportSession())

    #print(db.loadSession(message.chat.id))

    # user=User(message.chat.username)
    # dictUser[message.chat.id]=user

    msg = "Приветствую тебя студент, здесь ты можешь задавать вопросы другим студентам или отвечать сам на то, в чём разбираешься."
    msg = "Наш бот довольно понятен, но если боишься не разобраться, пиши /help. "
    msg += "Нажми \"добавить компетенцию\", чтобы указать, чем владеешь или сразу задай вопрос"
    bot.send_message(message.chat.id, msg, reply_markup=drawMainMenu())
Exemple #8
0
def register():
    try:
        email = request.form['email']
        password = request.form['password']
    except:
        return response('', 400)

    if not database.fetchUser(email) is None:
        error = 'Error: Username already exists'
    else:
        database.addUser(email, password)
        session['user'] = email

        flash('Success: Logging in')
        return redirect(url_for('mysite.index')) 

    return render_template('login.html', error=error)
Exemple #9
0
def signup():
    if request.method == "GET":
        return render_template("signup.html")
    else:
        email = request.form['email']
        pword = request.form['pword']

        if email == '' or email.find('@') != -1:
            return render_template("signup.html", msg = 'Please enter your stuy.edu email')
        if len(pword) < 8:
            return render_template("signup.html", msg = 'Please enter a password that is at least 8 characters long')
        m = sha256()
        m.update(pword)
        passwordHash = m.hexdigest()

        print "password hashed"

        message = database.addUser(email, passwordHash)

        print "user added to database"
        if (message == ''):
            user = database.getUser(email)
            data = urlencode({'email': user['email'], '_id': user['_id']})
            activateLink = website_url + '/activate?%s' %(data)

            s = smtplib.SMTP('smtp.gmail.com', 587)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(ourEmail, ourPassword)

            #Sets up the multipart object
            message = MIMEMultipart()
            message['Subject'] = 'Getting started with StuyBooks'
            message['From'] = ourEmail
            message['To'] = email + '@stuy.edu'

            text = '''
            Hello,

            Thanks for signing up with StuyBooks!
            Click on this link to activate your account: %s
            If you did not register for StuyBooks, contact us at %s

            Disclaimer: Stuy-books is a platform to meet and trade with other students. Stuy-books and associates are not liable for any damages, infringements, or other inappropriate usage of our service. Please be respectful of others. Any violation of school regulation can and will be reported to the administration. Thank you.

            Sincerely,
            Team JASH''' %(activateLink , ourEmail)
            #Attaches the message
            message.attach(MIMEText(text, 'plain'))

            s.sendmail(ourEmail, email + '@stuy.edu', message.as_string())
            s.close()

            return render_template("signup.html", msg = "A confirmation email has been sent to " + email + '@stuy.edu')

        return render_template("signup.html", msg = message)
Exemple #10
0
def check2():
    userList = request.form['Submit']
    checkMark = addUser(userList[0], userList[1])
    if checkMark == 1:
        session['ID'] = userList
        return redirect('/dashboard')
    else:
        return render_template(
            "login.html",
            errorMessage='This username already exists. Please try a new one')
Exemple #11
0
async def likeCut(ctx, user: discord.Member):
    if ctx.author.id == user.id:
        await ctx.send(user.mention + ", You can't like your own cut!")
    else:
        if database.userInfo(user.id) is None:
            database.addUser(user.id)
            await ctx.send(
                f"{ctx.author.mention} liked {user.mention}'s cut. They got their first like!"
            )
        else:
            database.addLike(user.id)
            likes = str(database.userInfo(user.id))
            clean = likes.replace("(",
                                  "").replace(")",
                                              "").replace("'",
                                                          "").replace(",", "")
            await ctx.send(
                f"{ctx.author.mention} liked {user.mention}'s cut. They now have {clean} likes."
            )
def signup():
    error = None
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        if not database.addUser(username,password):
            flash("Registered username, too short username, or too short password.")
            return redirect(url_for('signup'))
        flash("Great! You've registered! Now you can log in.")
        return redirect(url_for('login'))
    return render_template("signup.html")
Exemple #13
0
async def setupNewClient(roomId, ws):

    clientId = db.getNewClientId(roomId)
    log(f"Connection established to client {clientId} (Room: {roomId})")
    randomAvatar = randint(0, 27)
    log(f"Selected avatar {randomAvatar} for the new client")

    # add new client to database
    db.addUser(clientId, roomId, randomAvatar)
    # add user to room
    db.cursor.execute("UPDATE users SET room=? WHERE id=?", (roomId, clientId))

    welcomeMessage = {
        "connected": {
            "assignedId": clientId,
            "assignedAvatar": randomAvatar
        }
    }
    await ws.send(json.dumps(welcomeMessage))

    return clientId, randomAvatar
def signup():
    error = None
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        if not database.addUser(username, password):
            flash(
                "Registered username, too short username, or too short password."
            )
            return redirect(url_for('signup'))
        flash("Great! You've registered! Now you can log in.")
        return redirect(url_for('login'))
    return render_template("signup.html")
Exemple #15
0
def signup():
    if 'logged' in session:
        return redirect(url_for('appliances'))
    try:
        form = SignUpForm(request.form)
        if request.method == "POST" and form.validate():
            name = form.name.data
            email = form.email.data
            password = sha256_crypt.encrypt((str(form.password.data)))
            response = addUser(name, email, password)
            if response:
                return redirect(url_for('login'))
    except Exception as e:
        print(e)
    return render_template('signup.html', form=form)
Exemple #16
0
def mobileregistration():
    try:
        if request.method == 'POST':
            rawname = request.form['name']
            rawemail = request.form['email']
            rawpassword = request.form['password']
            password = sha256_crypt.encrypt((str(rawpassword)))
            response = addUser(rawname, rawemail, password)
            if response:
                return jsonify(success="You are registered successfully",
                               status=True)
            else:
                return jsonify(status=False, error="Already exist")
        gc.collect()
    except Exception as e:
        print(e)
        return jsonify(error="Please check later", status=False)
Exemple #17
0
def signUpUser():
    '''
    Handles sign up for new users
    '''
    if not checkConnection("test"):
        print("Sorry - cannot create user without internet connection")
        quit()

    username = getUserInput("Please enter your username")
    pw       = getUserInput("Please enter your password", True)

    if addUser(username, pw):
        setDBUsername(pw, username)
        pullDatabase()
        return True
    else:
        print("Sorry, that username is already taken")
        signUpUser()
Exemple #18
0
def register():
    a = []
    for num in range(0,123):
        a.append(num)
    if request.method=="GET":
        return render_template("register.html", a=a)
    else:
        button = request.form["b"]
        if button == "Login":
            return redirect(url_for('login'))
        username = request.form["username"]
        password = request.form["password"]
        emailaddress = request.form["emailaddress"]
        if not database.addUser(username, password, emailaddress, gender, age):
            flash("There was a problem with what you submitted.")
            return redirect(url_for('signup'))
        flash("Great! You're registered! Now you can log in.")
        return redirect(url_for('login'))
Exemple #19
0
def register(name='register'):
    if request.method == 'GET':
        return render_template('register.j2')
    else:
        #todo server side validation

        email = str(request.form['email'])
        password = str(request.form['password'])
        next_page = str(request.form['next'])
        remember = 'remember' in request.form

        if database.getUserByEmail(email) is not None:  #user already exists
            print("User already exists!")
            flash("User already exists!")
            return redirect(url_for('register'))
        else:
            # add user
            user = database.addUser(email, password)
            pprint(user)
            # log the user in
            login_user(user, remember)
            return redirect(next_page or url_for('/'))
Exemple #20
0
def addUsers(chat_id):
    return addUser(chat_id)
Exemple #21
0
def signup():
    if request.method == 'POST':
        database.addUser(request.form['id'],request.form['psw'],request.form['name'],8)
        return render_template("hello.html", msg="Sign Up Succeed!")
Exemple #22
0
def receive_messages():
    """Handle inbound messages and send responses through the Chat Engine API"""

    # ensure that the signature on the request is valid
    if not verify_signature(request):
        return Response(status=403, response='invalid signature')

    messages = request.json['messages']
    responses = []

    for message in messages:
        if message['type'] == 'scan-data':
            if database.lookUpUser(message['from']) == False:
                responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body':
                    'Welcome to SMS Bot. I can help you send an SMS message to any number in the United States or Canada for only 10 Kik Points! What would you like to do?',
                    'suggestedResponses': ['Send a new message']
                })
                database.addUser('false', 'false', message['from'], '0', '0',
                                 'false')
        #Other responses
        elif message['type'] == 'text':
            if database.lookUpUser(message['from']) == False:
                responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body':
                    'Welcome to SMS Bot. I can help you send an SMS message to any number in the United States or Canada for only 10 Kik Points! What would you like to do?',
                    'suggestedResponses': ['Send a new message']
                })
                database.addUser('false', 'false', message['from'], '0', '0',
                                 'false')

            elif ((message['body'] == 'Send a new message'
                   or message['body'] == 'Send another message')
                  and database.hasPaid(
                      message['from']) == False):  #TODO:Regex this
                chargePoints(message['from'])

            elif message['body'] == 'Change my message' and database.hasPaid(
                    message['from']) == True:
                responses.append({
                    'type':
                    'text',
                    'to':
                    message['from'],
                    'body':
                    'Enter the phone number you\'d like to send a message to.'
                })
                database.setGivenNum(message['from'], 'true')

            elif database.hasGivenNum(
                    message['from']) == True and database.hasGivenMessage(
                        message['from']) == False:
                phone_number_check = re.search(
                    '^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$',
                    message['body']
                )  #Use Regex to check for proper phone-number format

                if (phone_number_check):
                    responses.append({
                        'type':
                        'text',
                        'to':
                        message['from'],
                        'body':
                        'Please enter the message you\'d like to send to ' +
                        message['body']
                    })
                    database.setGivenMessage(message['from'], 'true')
                    database.storePhoneNum(message['from'], message['body'])
                else:
                    responses.append({
                        'type':
                        'text',
                        'to':
                        message['from'],
                        'body':
                        message['body'] +
                        ' is not a valid US or Canada number. Please enter a valid number! Tip: Do NOT add +1 to the number!'
                    })

            elif ((database.hasGivenNum(message['from']) == True
                   and database.hasGivenMessage(message['from']) == True)
                  or (message['body'] == 'Retry'
                      and database.hasPaid(message['from']) == True)):
                if twilio_api.sendsms(database.getPhoneNumber(message['from']),
                                      message['body']):
                    responses.append({
                        'type':
                        'text',
                        'to':
                        message['from'],
                        'body':
                        'SMS Sent: \n To: ' +
                        database.getPhoneNumber(message['from']) +
                        '\n Message: ' + message['body'] +
                        '\n What would you like to do next?',
                        'suggestedResponses': ['Send another message']
                    })
                    database.setGivenMessage(message['from'], 'false')
                    database.setGivenNum(message['from'], 'false')
                    database.setHasPaid(message['from'], 'false')
                else:
                    responses.append({
                        'type':
                        'text',
                        'to':
                        message['from'],
                        'body':
                        'I could not send your message for some reason. What would you like to do?',
                        'suggestedResponses': ['Change my message', 'Retry']
                    })
                    database.setGivenMessage(message['from'], 'false')
                    database.setGivenNum(message['from'], 'false')

            else:
                responses.append({
                    'type':
                    'text',
                    'to':
                    message['from'],
                    'body':
                    'I\'m not sure what you\'re trying to tell me. Please provide a valid command such as \'Send a new message\'.'
                })
        elif message['type'] == 'picture':
            responses.append({
                'type':
                'text',
                'to':
                message['from'],
                'body':
                'There\'s not much I can do with this picture...'
            })

    if responses:
        # send the responses through the Chat Engine API
        requests.post('https://engine.apikik.com/api/v1/message',
                      auth=(os.environ['USERNAME'], os.environ['API_KEY']),
                      json={'messages': responses})

    return Response(status=200)
Exemple #23
0
def receive_messages():
    """Handle inbound messages and send responses through the Chat Engine API"""

    # ensure that the signature on the request is valid
    if not verify_signature(request):
        return Response(status=403, response='invalid signature')

    messages = request.json['messages']
    responses = []

    for message in messages:
        if message['type'] == 'scan-data':
            if database.lookUpUser(message['from']) == False:
                responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body': 'Welcome to SMS Bot. I can help you send an SMS message to any number in the United States or Canada for only 10 Kik Points! What would you like to do?',
                    'suggestedResponses': ['Send a new message']
                })
                database.addUser('false','false', message['from'],'0','0','false')
        #Other responses    
        elif message['type'] == 'text':
            if database.lookUpUser(message['from']) == False:
                responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body': 'Welcome to SMS Bot. I can help you send an SMS message to any number in the United States or Canada for only 10 Kik Points! What would you like to do?',
                    'suggestedResponses': ['Send a new message']
                })
                database.addUser('false','false', message['from'],'0','0','false')

            elif ((message['body'] == 'Send a new message' or message['body'] == 'Send another message') and database.hasPaid(message['from']) == False): #TODO:Regex this
                chargePoints(message['from'])


            elif message['body'] == 'Change my message' and database.hasPaid(message['from']) == True:
                responses.append({
                'type': 'text',
                'to': message['from'],
                'body': 'Enter the phone number you\'d like to send a message to.'
                })
                database.setGivenNum(message['from'],'true')

            elif database.hasGivenNum(message['from']) == True and database.hasGivenMessage(message['from']) == False:
                phone_number_check = re.search('^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$',message['body']) #Use Regex to check for proper phone-number format

                if (phone_number_check):
                    responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body': 'Please enter the message you\'d like to send to ' + message['body']
                    })
                    database.setGivenMessage(message['from'],'true')
                    database.storePhoneNum(message['from'], message['body'])
                else:
                    responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body': message['body'] + ' is not a valid US or Canada number. Please enter a valid number! Tip: Do NOT add +1 to the number!'
                    })

            elif ((database.hasGivenNum(message['from']) == True and database.hasGivenMessage(message['from']) == True) or (message['body'] == 'Retry' and database.hasPaid(message['from']) == True)):
                if twilio_api.sendsms(database.getPhoneNumber(message['from']), message['body']):
                    responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body': 'SMS Sent: \n To: ' + database.getPhoneNumber(message['from']) + '\n Message: ' + message['body'] + '\n What would you like to do next?',
                    'suggestedResponses': ['Send another message']
                    })
                    database.setGivenMessage(message['from'], 'false')
                    database.setGivenNum(message['from'], 'false')
                    database.setHasPaid(message['from'],'false')
                else:
                    responses.append({
                    'type': 'text',
                    'to': message['from'],
                    'body': 'I could not send your message for some reason. What would you like to do?',
                    'suggestedResponses': ['Change my message','Retry']
                    })
                    database.setGivenMessage(message['from'], 'false')
                    database.setGivenNum(message['from'], 'false')

            else:
                responses.append({
                'type': 'text',
                'to': message['from'],
                'body': 'I\'m not sure what you\'re trying to tell me. Please provide a valid command such as \'Send a new message\'.' 
                })
        elif message['type'] == 'picture':
            responses.append({
                'type': 'text',
                'to': message['from'],
                'body': 'There\'s not much I can do with this picture...'
                })


    if responses:
        # send the responses through the Chat Engine API
        requests.post(
            'https://engine.apikik.com/api/v1/message',
            auth=(os.environ['USERNAME'], os.environ['API_KEY']),
            json={'messages': responses}
        )

    return Response(status=200)
        database.listAllAvailableItems()
    if userin == 2:
        database.borrow(userid)
    if userin == 3:
        database.borrowReturn(userid)
    if userin == 4:
        clear_screen()
        database.listBorrowedItems(userid)
    if userin == 5:
        clear_screen()
        print("Welcome to the admin area:")
        print("You can...")
        while (1):
            userin = dialogs.adminWelcomeDialog(userid)
            if userin == 1:
                database.addUser()

            elif userin == 2:
                database.delUser()

            elif userin == 3:
                clear_screen()
                database.printAllUsers()

            elif userin == 4:
                item.addItem()

            elif userin == 5:
                item.delItem()

            elif userin == 6:
Exemple #25
0
        flash("Yikes! Bad username")
        return redirect(url_for('authentication'))


# Signs user up for the website (from form)
def signup():
    users = database.getUsers()
    # checks if credentials for flash message
    print(request.form.get('email') + "===================")
    if request.form.get('username') in users:
        flash("Yikes! Username already taken")
        return redirect(url_for('crt_acct'))
    elif request.form.get('email') in users:
        flash("Yikes! Email already taken")
        return redirect(url_for('crt_acct'))
    elif request.form.get('password0') != request.form.get('password1'):
        flash("Yikes! Passwords do not match")
        return redirect(url_for('crt_acct'))
    else:
        flash("Yay! Please log in with your new credentials!")
        hash_object = hashlib.sha224(request.form.get('password0'))
        hashed_pass = hash_object.hexdigest()
        database.addUser(request.form.get('username'), hashed_pass,
                         request.form.get('email'))
        return redirect(url_for('authentication'))


if __name__ == '__main__':
    database.addUser("elmo", "goldfish")
print database.getUsers()
	def devGo(self):

		#this boolean is used to restrict guests from using certain features
		cantUse = False
		if self.ww.name == None:
			cantUse = True

		self.label.setText('')

		#lists the different commands
		if self.textbox.text() == 'help':
			self.textbox.setText('')
			self.label.setText('Commands: addSite, addUser(name), clearData, deleteUser, clear')

		#Adds site to the current user's list of sites
		elif self.textbox.text() == 'addSite':
			if cantUse:
				self.textbox.setText('')
				self.label.setText('You must be logged in to use this function.')
				return
			self.textbox.setText('')
			self.ww.addSite()

		#clears user preferences 
		elif self.textbox.text() == 'clearData':
			if cantUse:
				self.textbox.setText('')
				self.label.setText('You must be logged in to use this function.')
				return
			self.textbox.setText('')
			database.deleteUser(self.ww.name)
			database.addUser(self.ww.name)
			self.ww.websites = ['google https://www.google.com/']
			self.ww.websitesDictionary = {'google': 'https://www.google.com/'}
			self.ww.homeScreen()

		#adds a new user to the database and takes images to use for recognition
		elif self.textbox.text()[0:7] == 'addUser':
			name = self.textbox.text()[8:-1]
			_thread.start_new_thread(face_recognize.addUser, (name, ))
			self.ww.name = name.title()
			database.addUser(name.title())
			self.textbox.setText('')
			self.ww.homeScreen()

		#removes user from image database and websites database
		elif self.textbox.text() == 'deleteUser':
			if cantUse:
				self.textbox.setText('')
				self.label.setText('You must be logged in to use this function.')
				return
			self.textbox.setText('')
			database.deleteUser(self.ww.name)
			self.ww.websites = ['google https://www.google.com/']
			self.ww.websitesDictionary = {'google': 'https://www.google.com/'}
			create_database.deleteUser(self.ww.name)
			self.ww.name = None
			self.ww.homeScreen()

		#tool used for debuggin in development
		elif self.textbox.text()[0:15] == 'deleteUserAdmin':
			tempName = self.textbox.text()[16:-1]
			database.deleteUser(tempName)
			create_database.deleteUser(tempName)
			self.ww.homeScreen()

		#clears the label
		elif self.textbox.text() == 'clear':
			self.textbox.setText('')
			self.label.setText('')
Exemple #27
0
def handler(c, a):
    global loginData
    global ohdData
    global connections
    userid = 0

    # c.send(loginData)
    # c.send(ohdData)

    while True:
        data = c.recv(1024)

        #print(data)
        if data != b'':

            if extract.byteToInt(data) == 10101:
                tf, userid, token, major, minor = extract.extractLogin(
                    data, '16.167')

                if tf == True:
                    if userid != 0:
                        print('Logging in: ', userid, token, ' on version ',
                              major, '.', minor)
                        # print('sending:',extract.sendLogin(userid,token,major,minor))
                        userid = userid
                        c.send(extract.sendLogin(userid, token, major, minor))
                        c.send(extract.genOHDMSG(userid))
                        c.send(lwarbThing)
                    else:
                        print('Creating new account.')

                        genID = extract.generateID()
                        genToken = extract.randomStringDigits()
                        userid = genID
                        c.send(extract.sendLogin(genID, genToken, 16, 167))

                        database.addUser(genID, genToken)

                        time.sleep(0.2)
                        #ownhomedata V
                        c.send(ohdData)
                        c.send(lwarbThing)

                elif tf == False:
                    print('Refused connection.')
                    c.send(
                        extract.sendUpdateAvailable(
                            "You don't have the latest version of Garlfin Stars! Click to download the update.",
                            'https://github.com/garlfin/dae2scw'))
            elif extract.byteToInt(data) == 10108:
                print('Keeping alive', userid, '.')
                c.send(extract.keepAlive())
            elif extract.byteToInt(data) == 14102:
                print('End client turn from ', userid)
                #if extract.extractCommandID(data) == 35075:

                # print(data)

                #else:
                print('Unknown command id', extract.extractCommandID(data),
                      '. ', data)
            elif extract.byteToInt(data) == 23591:
                print('Weird info coming in from', userid)
            elif data == clientBox:
                c.send(serverBox)
            elif extract.byteToInt(data) == 14366:
                print('14366 incoming: ', data)
            elif extract.byteToInt(data) == 10107:
                print('Client capabilities (10107) incoming: ', data)
            elif extract.byteToInt(data) == 14600:
                print('Changing name for', userid, '.')
                c.send(
                    extract.returnNameChange(extract.extractNameChange(data)))
                database.changeUserName(userid,
                                        extract.extractNameChange(data))
            else:
                print(data)

        # for connection in connections:
        # connection.send()

        # connection.send(bytes(data))

        if not data:
            print(c, " left")
            connections.remove(c)
            c.close()

            break
Exemple #28
0
 def add(user, conn, args, raw):
     if args.get(0) == 'user' and len(args) >= 3:
         addUser(args[1], args[2], bool(args.get(3)))
     else:
         conn.respond(CommandError)
         return True