def loadUsersIntoDatabase(self, reported_users):
        error = 0
        online_users = []
        for user in reported_users:
            username = user.get("username", None)
            status = user.get("status", None)
            online_users.append(user.get("username"))

            if not status:
                status = "online"
            er = database.updateUsersInfo(
                username, user.get("connection_address", None),
                user.get("connection_location", None),
                user.get("incoming_pubkey", None),
                user.get("connection_updated_at", None), status)
            if er.get("response", None) == "error":
                error = 1
        all_users = database.getAllUsers()

        for user in all_users:
            username = user.get("username", None)
            if username is None:
                continue
            if username not in online_users:
                database.makeUserOffline(username)
        return error
Example #2
0
    def pingCheckUsers(self):
        headers = self.createAuthorisedHeader(False)
        ts = str(time.time())

        all_users = database.getAllUsers()

        payload = {
            "my_time": ts,
            "connection_address": self.logserv.connection_address,
            "connection_location": self.logserv.connection_location
        }

        for user in all_users:
            username = user.get("username", None)
            user_address = user.get("address", None)
            user_status = user.get("status", None)
            if user_address is None or user_status != "online":
                continue
            url = "http://" + user_address + "/api/ping_check"
            try:
                JSON_object = helper.postJson(payload, headers, url)
                response = JSON_object.get("response", None)
                if response == "ok":
                    print("ping check successful")
                else:
                    print("ping check not ok")
                    database.makeUserOffline(username)
            except:
                print("cannot ping this user!!!!")
                database.makeUserOffline(username)
Example #3
0
def manage():
    order = request.args.get("order")

    if request.method == "POST":
        x = request.form.get("username")
        y = request.form.get("displayName")
        z = request.form.get("password")
        w = request.form.get("rank")
        with database.connect() as conn:
            database.updateUser(conn, x, y, z, w)
        return jsonify((x, y, z, w))

    with database.connect() as conn:
        users = database.getAllUsers(conn, order)

    if order == "username":
        order = "Username"
    elif order == "displayName":
        order = "Display name"
    elif order == "password":
        order == "Password"
    elif order == "rank":
        order = "Rank"

    global user
    global ranks
    return render_template("manage.html",
                           users=users,
                           order=order,
                           ranks=ranks,
                           tab="manage",
                           user=user)
Example #4
0
def outputUsers(dbCursor):
    f = open("MyCollege_users.txt", "w+")
    users = db.getAllUsers(dbCursor)
    for user in users:
        f.write(f"{user[0]} {'plus' if user[4] == 1 else 'standard'}\n"
                )  # Username AccType
    f.close()
Example #5
0
    def settings(self,
                 blockWord=None,
                 unblockWord=None,
                 blockUser=None,
                 unblockUser=None):
        print("called settings")
        allusers = database.getAllUsers()

        logserv = cherrypy.session.get("logserv", None)
        username = cherrypy.session.get("username", None)
        if logserv is None or not username:
            raise cherrypy.HTTPRedirect('/login')
        else:

            if blockWord:
                database.addBlockedWord(username, blockWord)
            elif unblockWord:
                database.deleteBlockedWord(username, unblockWord)
            elif blockUser:
                database.addBlockedUser(username, blockUser)
            elif unblockUser:
                database.deleteBlockedUser(username, unblockUser)

            blockedUsers = database.getBlockedUser(username)
            blockedWords = database.getBlockedWords(username)

            template = j2_env.get_template('web/settings.html')
            output = template.render(blocked_words=blockedWords,
                                     blocked_users=blockedUsers,
                                     allusers=allusers)

        return output
Example #6
0
def outputProfiles(dbCursor):
    f = open("MyCollege_profiles.txt", "w+")
    users = db.getAllUsers(dbCursor)
    for user in users:
        profile = db.getProfilePage(dbCursor, user[0])
        jobs = db.getProfileJobs(dbCursor, user[0])
        education = db.getProfileEducation(dbCursor, user[0])
        f.write(f"{user[2]} {user[3]}'s Profile Page\n")  # Title
        f.write(f"Major: {profile[1]}\n")  # Major
        f.write(f"University: {profile[2]}\n")  # University Name
        f.write(f"About: {profile[3]}\n")  # About
        f.write("Experience:\n")
        for job in jobs:  # Experience
            f.write(f"{job[2]}\n")  # Title
            f.write(f"\tEmployer: {job[3]}\n")  # Employer
            f.write(f"\tDate: {job[4]} - {job[5]}\n")  # Start Date - End Date
            f.write(f"\tLocation: {job[6]}\n")  # Location
            f.write(f"\tDescription: {job[7]}\n")  # Job Description
        f.write("Education:\n")
        for edu in education:  # Education
            f.write(f"University: {edu[2]}\n")  # University Name
            f.write(f"\tDegree: {edu[3]}\n")  # Degree
            f.write(f"\tYear: {edu[4]} - {edu[5]}\n")  # Start Year - End Year
        f.write("=====\n")
    f.close()
Example #7
0
def calculate_mood():
  """Calculates mood based on the amount of users 
  who have messaged the chatbot in the past day."""
  print("Updating happiness points, current points:", os.environ['BOT_HAPPINESS'])
  currentTime = time()
  users = db.getAllUsers()
  num_users = len(users)
  spoken_to_recently = 0
  for user in users:
    if user['LastMessage'] - currentTime < 86400:
      spoken_to_recently += 1
    
  active_users = spoken_to_recently / num_users
  happiness = int(os.environ.get('BOT_HAPPINESS', 0))
  if active_users >= 0.75:
    print("75 percent or more users spoke to chatbot, increasing points by 1")
    happiness += 1
  elif active_users >= 0.25 and active_users < 0.5:
    print("between 25 percent and 50 percent of users spoke to chatbot, decreasing points by 1")
    happiness -= 1
  elif active_users < 0.25:
    print("Fewer than 25 percent of users spoke to chatbot, setting points to 0")
    happiness = 0

  print("New happiness points:", happiness)
  os.environ['BOT_HAPPINESS'] = str(happiness)
Example #8
0
    def profile(self, name=None, filterVal=None):
        allusers = database.getAllUsers()
        logserv = cherrypy.session.get("logserv", None)
        if logserv is None:
            raise cherrypy.HTTPRedirect('/login')
        else:
            template = j2_env.get_template('web/profile.html')
            username = cherrypy.session.get("username")

            if name == username or name is None:
                broadcasts = database.getAllBroadcastsUser(username)
                profile = database.getUserData(username)
                isOwn = True
            else:
                profile = database.getUserData(name)
                validUser = helper.checkValidUser(username, name)
                if not validUser:
                    profile["username"] = "******"
                if filterVal == "favourite":
                    broadcasts = database.getFavBroadcasts(name)
                elif filterVal == "blocked":
                    broadcasts = database.getFavBroadcasts(name)
                else:
                    broadcasts = database.getAllBroadcastsUser(name)
                    filterVal = "recent"

                isOwn = False

            if not broadcasts:
                broadcasts = []

            for broadcast in broadcasts:
                message = broadcast.get("message")
                broadcastUser = broadcast.get("username")
                time = broadcast.get("sender_created_at")
                sig = broadcast.get("signature")

                validMessage = helper.checkValidMessage(username, message)
                validBroadcast = helper.checkValidBroadcast(username, sig)

                if not validBroadcast:
                    broadcast[
                        "username"] = '******'  #dont display at all

                if not validMessage:
                    broadcast["message"] = 'invalid message'

                time = broadcast.get("sender_created_at")
                broadcast["time"] = helper.formatTime(time)
                broadcast["likes"] = database.getNumberLikesBroadcasts(
                    broadcast.get("signature", None))

            output = template.render(profile=profile,
                                     broadcasts=broadcasts,
                                     isOwn=isOwn,
                                     allusers=allusers)
        return output
Example #9
0
def outputUserTrainings(dbCursor):
    f = open("MyCollege_training.txt", "w+")
    users = db.getAllUsers(dbCursor)
    for user in users:
        completed_trainings = db.getAllUserCompletedTrainings(
            dbCursor, user[0])
        f.write(f"{user[0]}\n")
        for t in completed_trainings:
            f.write(f"{t[0]}\n")
        f.write("=====\n")
    f.close()
Example #10
0
    def sendBroadcastMessage(self, message):
        headers = self.createAuthorisedHeader(False)
  
        ud = database.getUserHashes(self.username)
        loginserver_record = ud.get("loginrecord")
        ts = str(time.time())
        message_bytes = bytes(loginserver_record+message+ts, encoding='utf-8')
        signed = self.signing_key.sign(message_bytes, encoder=nacl.encoding.HexEncoder)
        signature_hex_str = signed.signature.decode('utf-8')
        
        payload = {
            "loginserver_record": loginserver_record,
            "message": message,
            "sender_created_at": ts,
            "signature": signature_hex_str
        }
        try: 
            username, pubkey, server_time, signature_str = helper.breakLoginRecord(loginserver_record)
        except Exception as e:
            print(e)
            return 1

        isMeta =re.search("^!(M|m)eta:", message)
        if not isMeta:
            database.addBroadCast(loginserver_record, message, ts, signature_hex_str, username, 'false')
        else:
            database.addBroadCast(loginserver_record, message, ts, signature_hex_str, username, 'true')

        all_users = database.getAllUsers()

        for user in all_users:
            user_address = user.get("address", None)
            user_status = user.get("status", None)
            if user_address is None or user_status != "online":
                continue
            url = "http://" + user_address + "/api/rx_broadcast"
            
            if user.get("username") == 'admin':
                url = "http://cs302.kiwi.land/api/rx_broadcast"

            try:
                JSON_object = helper.postJson(payload, headers, url)
                print(JSON_object)
                response = JSON_object.get("response", None)
                if response == "ok":
                    print("broadcast successfully sent")
                else:
                    print("response not OK")
            except:
                print("FAILED TO BROADCAST to url " + str(url))
Example #11
0
def outputSavedJobsByUser(dbCursor):
    f = open("MyCollege_savedJobs.txt", "w+")

    # create list of users
    users = db.getAllUsers(dbCursor)

    for user in users:
        jobs = db.getFavoriteJobsByUser(dbCursor,
                                        user[0])  # get "saved" jobs for user

        if len(jobs) > 0:  # should only output users who have saved jobs
            f.write(f"{user[0]}\n")  # username
            for job in jobs:
                f.write(f"{job[1]}\n")  # job title
            f.write("=====\n")  # output user separator
Example #12
0
    def retrieveOfflineData(self, since):
        headers = self.createAuthorisedHeader(False)

        all_users = database.getAllUsers()
        for user in all_users:
            user_address = user.get("address", None)
            user_status = user.get("status", None)
            if user_address is None or user_status != "online":
                continue
            url = "http://" + user_address + "/api/rx_checkmessages?since=" + since
            print(url)

            try:
                JSON_object = helper.postJson(None, headers, url)
            except Exception as e:
                print("cannot retrieveOfflineData from " + str(url))
                print(e)
            else:
                response = JSON_object.get("response", None)
                if response == "ok":
                    broadcasts = JSON_object.get("broadcasts", [])
                    private_messages = JSON_object.get("private_messages", [])
                    for broadcast in broadcasts:
                        loginserver_record = broadcast.get("loginserver_record", None)
                        if not loginserver_record:
                            continue
                        message = broadcast.get("message", None)
                        username, pubkey, server_time, signature_str = helper.breakLoginRecord(loginserver_record)
                        isMeta = re.search("^!Meta:(\w+):(\w+)", message)
                        if not isMeta:
                            database.addBroadCast(broadcast.get("loginserver_record", None), broadcast.get("message", None), broadcast.get("sender_created_at", None), broadcast.get("signature", None), username, 'false')
                        else:
                            database.addBroadCast(broadcast.get("loginserver_record", None), broadcast.get("message", None), broadcast.get("sender_created_at", None), broadcast.get("signature", None), username, 'true')
                            key = isMeta.group(1)
                            val = isMeta.group(2)
                            helper.addMetaData(key,val,username)
                    
                    for pm in private_messages:
                        loginserver_record = broadcast.get("loginserver_record", None)
                        if not loginserver_record:
                            continue
                        username, pubkey, server_time, signature_str = helper.breakLoginRecord(loginserver_record)
                        database.addReceivedMessage(pm.get("target_username", None), pm.get("target_pubkey", None), pm.get("encrypted_message", None), pm.get("sender_created_at", None), pm.get("signature", None), username, loginserver_record, 'false')
                else:
                    print("response not OK")
Example #13
0
    def sendPrivateMessage(self, message, send_user):
        headers = self.createAuthorisedHeader(False)

        user = database.getUserData(send_user)
        user_address = user.get("address", None)
        user_pubkey = user.get("pubkey", None)
        user_status = user.get("status", None)
        try: 
            encr_message = helper.encryptMessage(message, user_pubkey)
        except Exception as e:
            print(e)
            print("failed to encrypt message")
            return 1
        ud = database.getUserHashes(self.username)
        loginserver_record = ud.get("loginrecord")        
        ts = str(time.time())
        message_bytes = bytes(loginserver_record+user_pubkey+send_user+encr_message+ts, encoding='utf-8')
        signed = self.signing_key.sign(message_bytes, encoder=nacl.encoding.HexEncoder)
        signature_hex_str = signed.signature.decode('utf-8')

        pubkey_hex = self.signing_key.verify_key.encode(encoder=nacl.encoding.HexEncoder)
        try:
            self_encrypted_message = helper.encryptMessage(message, pubkey_hex)
        except Exception as e: 
            print("failed to encrypt sent message.")
            print(e)
            return 1
        msg = database.addsentMessages(self.username, send_user, self_encrypted_message, ts, "user")
        if msg["response"] == "error":
            return 1
        
        payload = {
            "loginserver_record": loginserver_record,
            "target_pubkey": user_pubkey,
            "encrypted_message": encr_message,
            "target_username": send_user,
            "sender_created_at": ts,
            "signature": signature_hex_str
        }
        
        if user_status == "online":
            user = database.getUserData(send_user)
            user_address = user.get("address", None)
            user_status = user.get("status", None)
            url = "http://" + user_address + "/api/rx_privatemessage"
            
            try:
                JSON_object = helper.postJson(payload, headers, url)
                response = JSON_object.get("response", None)
                if response == "ok":
                    print("pm sent successfully")
                    return 0
                else:
                    raise Exception("error sending private message")
            except Exception as e:
                print("FAILED TO SEND MESAGE")
                print(e)

                all_users = database.getAllUsers()
                #sending offline message.
                for user in all_users:
                    user_address = user.get("address", None)
                    user_status = user.get("status", None)
                    if user_address is None or user_status != "online":
                        continue
                    url = "http://" + user_address + "/api/rx_privatemessage"                    
                    try:
                        JSON_object = helper.postJson(payload, headers, url)
                        response = JSON_object.get("response", None)
                        if response == "ok":
                            print("pm sent successfully sent")
                        else:
                            raise Exception("error sending private message")
                    except Exception as e:
                        print(e)
Example #14
0
    def index(self, filterVal=None, status=None):
        allusers = database.getAllUsers()

        logserv = cherrypy.session.get("logserv", None)
        if logserv is None:
            raise cherrypy.HTTPRedirect('/login')
        else:
            username = cherrypy.session["username"]

            if status == 'online':
                logserv.status = 'online'
            elif status == 'busy':
                logserv.status = 'busy'
            elif status == 'away':
                logserv.status = 'away'

            if status:
                logserv.reportUser()

            if filterVal == "favourite":
                all_broadcasts = database.getFavBroadcasts(username)
            elif filterVal == "safe":
                all_broadcasts = database.getAllBroadcasts()
            else:
                all_broadcasts = database.getAllBroadcasts()
                filterVal = "recent"

            if not all_broadcasts:
                all_broadcasts = []
            data = []
            for broadcast in all_broadcasts:
                tup = {}
                message = broadcast.get("message")
                broadcastUser = broadcast.get("username")
                time = broadcast.get("sender_created_at")
                sig = broadcast.get("signature")

                validMessage = helper.checkValidMessage(username, message)
                validUser = helper.checkValidUser(username, broadcastUser)

                if filterVal == "safe":  #if block, then block ALL broadcasts that are blocked by EVERYONE
                    validBroadcast = helper.checkValidBroadcastAll(sig)
                else:
                    validBroadcast = helper.checkValidBroadcast(username, sig)

                if not validUser or not validBroadcast:
                    tup["username"] = '******'  #dont display at all
                else:
                    tup["username"] = broadcastUser

                if not validMessage:
                    tup["message"] = 'invalid message'
                else:
                    tup["message"] = message

                tup["time"] = helper.formatTime(time)
                tup["signature"] = sig
                tup["likes"] = database.getNumberLikesBroadcasts(
                    broadcast.get("signature", None))
                data.append(tup)
            template = j2_env.get_template('web/index.html')
            output = template.render(broadcasts=data,
                                     filter=filterVal,
                                     allusers=allusers)
        return output
Example #15
0
    def message(self, name=None, groupname=None):

        logserv = cherrypy.session.get("logserv", None)

        if logserv is None:
            raise cherrypy.HTTPRedirect('/login')
        else:
            myUsername = cherrypy.session["username"]
            messages = []
            data = {}
            template = j2_env.get_template('web/message.html')
            users = database.getAllUsers()
            groupchats = database.getAllGroupChats(myUsername)
            online_users = []
            if not users:
                users = []

            for user in users:
                username = user.get("username", None)
                status = user.get("status", None)
                validUser = helper.checkValidUser(myUsername, username)
                if not username or not status or not validUser:
                    continue
                data[username] = status
                if status == 'online':
                    online_users.append(username)

            if name is not None or groupname is not None:
                signing_key = logserv.signing_key
                username = cherrypy.session.get("username")
                isGroup = False
                if name is not None:
                    messages = database.getUserConversation(username, name)
                else:
                    groupkeys = database.checkGroupKey(username)
                    for groupkey in groupkeys:
                        encr_groupkey = groupkey.get("groupkey_encr", None)
                        try:
                            decrypted_groupkey = helper.decryptMessage(
                                encr_groupkey, logserv.signing_key)
                            groupkey_str = decrypted_groupkey.hex()
                        except Exception as e:
                            print("ERROR in decrypting group key.")
                            print(e)
                        else:
                            helper.addToPrivateData(
                                logserv, "prikeys",
                                groupkey_str)  #add group key to private data
                            database.deleteGroupKey(username, encr_groupkey)

                    messages = database.getGroupConversation(
                        username, groupname)
                    isGroup = True

                if messages is None:
                    messages = []

                for message in messages:
                    time = message["sender_created_at"]
                    time = helper.formatTime(time)
                    message["time"] = time

                    encr_message = message["message"]
                    status = message["sent"]
                    decr_message = None

                    if status == "received" and isGroup:

                        validUser = helper.checkValidUser(
                            cherrypy.session["username"], message["username"])
                        if not validUser:
                            message["username"] == 'invalid user'

                        target_group_bytes = bytes(groupname, encoding='utf-8')
                        try:
                            key = helper.getEncryptionKey(
                                logserv, target_group_bytes)
                        except Exception as e:
                            print(e)
                            key = None

                        #dex hexing message
                        try:
                            bytes_message = bytes.fromhex(encr_message)
                            decr_message = helper.decryptStringKey(
                                key, bytes_message)
                        except Exception as e:
                            print(e)
                            decr_message = None

                    else:
                        try:
                            decr_message = helper.decryptMessage(
                                encr_message, signing_key)
                            decr_message = decr_message.decode('utf-8')
                        except Exception as e:
                            print(e)
                            print("error decrypting message")
                            decr_message = None
                    if not decr_message:
                        print("ERROR")
                        decr_message = "ERROR DECRYPTING"

                    validMessage = helper.checkValidMessage(
                        username, decr_message)
                    if not validMessage:
                        decr_message = "invalid message"

                    message["message"] = decr_message
        output = template.render(username=name,
                                 messages=messages,
                                 onlineusers=data,
                                 groupchats=groupchats,
                                 groupname=groupname,
                                 allusers=users)
        return output