Exemplo n.º 1
0
def analyseUsers(usersDict):
    '''
    分析所有用户的行为构建用户字典,判断其活跃与否
    key=用户ID:value=用户对象
    '''
    dict = {}
    for userId, userWithSongsList in usersDict.items():
        user = User(userId)
        user.makeSongsTried(userWithSongsList)
        dict[userId] = user
    return dict
Exemplo n.º 2
0
def analyseUsers(usersDict):
    '''
    分析所有用户的行为构建用户字典,判断其活跃与否
    key=用户ID:value=用户对象
    '''
    dict = {}
    for userId, userWithSongsList in usersDict.items():
        user = User(userId)
        user.makeSongsTried(userWithSongsList)
        dict[userId] = user
    return dict
Exemplo n.º 3
0
def register_user(form):
    username = form['Username']
    password = form['Password']
    user = User.get_user(username)
    if user == None:
        t = time()
        password = unicode(hashpw(password, gensalt(8)))
        e = time()
        print 'Hashpw Time Elapsed %s' % str(e - t)
        new = User(username, password)
        new.save_to_db()
        login_user(new, remember=True)
        return flask.redirect("/")
    flask.flash("Username already chosen")
    return flask.redirect("/login")
Exemplo n.º 4
0
def register_user(form):
    username = form['Username']
    password = form['Password']
    user = User.get_user(username)
    if user == None:
        t = time()
        password = unicode(hashpw(password, gensalt(8)))
        e = time()
        print 'Hashpw Time Elapsed %s' % str(e-t)
        new = User(username, password)
        new.save_to_db()
        login_user(new, remember=True) 
        return flask.redirect("/")
    flask.flash("Username already chosen")
    return flask.redirect("/login")
Exemplo n.º 5
0
def handleTeacherVideos():
    if (request.method == 'POST'):
        try:
            questionID = request.args.get('userID')
            # check if the post request has the file part
            if 'file' not in request.files:
                for i in request.files:
                    print(i)
            file = request.files['file']
            print('teletabi')
            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == '':
                print('no selected file')
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                return 't'
            else:
                return 'k'
        except Exception as ex:
            print(str(ex))
            return 'k'
    else:
        try:
            userID = request.args.get('userID')
            user = User.getUserByID(userID)
            videos = user.videos
            titleList = []
            for video in videos:
                titleList.append({'title': video})
            print('a')
            return json.dumps(titleList)
        except Exception as error:
            return str(error)
Exemplo n.º 6
0
 def LoadUsers(self):
     """Returns list of 'User' objects from DB"""
     USERS = self.DB.retrieveTable("USERS")
     Users = []
     for user in USERS:
         Users.append(
             User(user[0], user[1], user[2], user[3], user[4], user[5]))
     return Users
    def open_json(self, main_folder):
        #main_folder: folder containing folder of user containing all the years
        aldready_processed = os.listdir(
            Path('../DATA/data_timeline_processed/'))
        for folder in os.listdir(main_folder):
            user = folder
            user = User(user)
            user.process()
            if folder not in aldready_processed:
                #folder: name of timeline_folder, name of user
                print(folder)
                subfolders_path = os.path.join(main_folder, folder)
                subfolders = os.listdir(subfolders_path)
                for subfolder in subfolders:
                    #subfolder: year of timeline
                    if subfolder != 'config.txt':
                        subsubfolder_path = os.path.join(
                            subfolders_path, subfolder)
                        user_id = f"{user}_{subfolder}"
                        out_path = Path(
                            f'../DATA/data_timeline_processed/{user}/{subfolder}'
                        )
                        try:
                            out_path.mkdir(parents=True, )
                        except:
                            pass
                        for filename in os.listdir(subsubfolder_path):
                            print(f'--> {filename}')
                            file_path = os.path.join(subsubfolder_path,
                                                     filename)
                            with open(file_path, encoding="utf8") as f:
                                obj = json.loads(f.read())
                            f.close()

                            out_obj = self.process_json(obj, user_id)
                            self.process(out_obj)
                            out_open = f'{out_path}/{filename}'
                            if len(out_obj) > 0:
                                with open(out_open, 'w+') as f_out:
                                    f_out.write(json.dumps(out_obj, indent=4))
                                f_out.close()
                    else:
                        pass
            else:
                print(f'{folder} Aldready Processed')
Exemplo n.º 8
0
def get_chatlog_stream(message):
    print('Got Something', message)
    sleep(2)
    if message['path'] == '/':
        print('Everything')
        dataobject = message['data']
        for sess in dataobject:
            session_dic[sess] = User(dataobject[sess], sess)
            if session_dic[sess].usertype == "":
                aggregateData(session_dic[sess])
                db.child("logs").child(sess).set(
                    session_dic[sess].firebase_save_format())
    else:
        print('Something')
        sessid = message['path'].split('/')[1]
        new_log = dict(db.child("logs").child(sessid).get().val())
        session_dic[sessid] = User(new_log, sessid)
        aggregateData(session_dic[sessid])
        db.child("logs").child(sessid).set(
            session_dic[sessid].firebase_save_format())
Exemplo n.º 9
0
def main():
    logger.info("... Initializing MatchFinder ...")

    userList, userListSuccess = fetchActiveUsers()
    if userListSuccess:
        logger.info("Found users...")
        for user in userList:
            #Changing connection into dictionary
            user = user.to_dict()

            logger.info("Initializing run for user: {}".format(user))

            #Creating User Class out of data received
            user = User(user['region'], user['summoner_id'],
                        user['account_id'])

            logger.info("Converted user into User class: {}".format(
                user.toDict()))

            matchList, matchListSuccess = fetchMatchEntries(user.toDict())
            if matchListSuccess:
                logger.info("Found matches...")
                for match in matchList:
                    match = Match(match['gameId'], match['timestamp'],
                                  user.getRegion())

                    logger.info("Initializing run for match: {}".format(
                        match.toDict()))

                    insertMatchMessage = insertSingleMatch(
                        match.toDict(), user.getAccountId())
                    if insertMatchMessage is 'Success':
                        usersInMatch = fetchUsersInMatch(
                            match.getRegion(), match.getMatchId())
                        for participant in usersInMatch:
                            logger.info("Initializing participant: {}".format(
                                participant['player']['accountId']))

                            insertParticipant(
                                participant['player']['accountId'],
                                match.getMatchId(), user.getAccountId())
                    elif insertMatchMessage is 'Exists':
                        logger.info(
                            "Match found that currently exists. Skipping user..."
                        )
                        break
                    elif insertMatchMessage is 'Error':
                        logger.info(
                            "Error has occured when inserting match. Skipping singular match..."
                        )
            else:
                logger.info("Failed to retrieve any active runs")
    else:
        logger.info("Failed to retrieve any active users")
Exemplo n.º 10
0
def google_signIn():
    content = request.json
    name = content['firstName']
    mail = content['mail']
    token = content['id_token']
    googleID = google_authenticate(token)
    if (googleID == 'error'):
        return 'error'
    else:
        user = User.getUserByGoogleID(googleID)
        if (user != None):
            userID = user._id
            response = user.updateUserlastLogin()
            if (response == 'Worked'):
                signInDict = {
                    'isSuccessful': 'true',
                    '_id': str(userID),
                    'mail': user.mail,
                    'isTeacher': user.isTeacher
                }
                return json.dumps(signInDict)
            else:
                signInDict = {'isSuccessful': 'false'}
                return json.dumps(signInDict)
        else:
            newUser = User(name, mail, googleID)
            response = newUser.insertUser()
            if (response == 'Worked'):
                user = User.getUserByGoogleID(googleID)
                signInDict = {
                    'isSuccessful': 'true',
                    '_id': str(user._id),
                    'mail': user.mail,
                    'isTeacher': user.isTeacher
                }
                return json.dumps(signInDict)
            else:
                signInDict = {'isSuccessful': 'false'}
                return json.dumps(signInDict)
Exemplo n.º 11
0
def hello():
    stats = dict(db.child("stats").get().val())
    data = dict(db.child("logs").get().val())
    for sess in data:
        session_dic[sess] = User(data[sess], sess)
        if session_dic[sess].usertype == "":
            aggregateData(session_dic[sess])
            db.child("logs").child(sess).set(
                session_dic[sess].firebase_save_format())
    resp = {}
    resp = get_products_shops_user_type(resp, stats)
    resp_json = json.dumps(resp)
    return resp_json
Exemplo n.º 12
0
def verify_login_user(form):
    username = form['Username']
    password = form['Password']
    user = User.get_user(username) 
    if user == None:
        flask.flash("Incorrect Credentials")
        return flask.redirect("/login")
        
    if unicode(hashpw(password, user.hashpass)) == user.hashpass:
        login_user(user)
        return flask.redirect("/")
    else:
        flask.flash("Incorrect Credentials")
        return flask.redirect("/login") 
Exemplo n.º 13
0
def verify_login_user(form):
    username = form['Username']
    password = form['Password']
    user = User.get_user(username)
    if user == None:
        flask.flash("Incorrect Credentials")
        return flask.redirect("/login")

    if unicode(hashpw(password, user.hashpass)) == user.hashpass:
        login_user(user)
        return flask.redirect("/")
    else:
        flask.flash("Incorrect Credentials")
        return flask.redirect("/login")
Exemplo n.º 14
0
def handleQuestionLike():
    try:
        content=request.json
        userID=content['userID']
        if(User.checkUserByID(userID)==True):
            questionID=content['questionID']
            like=Like(True,userID)
            response=like.insertLikeToQuestionByQuestionID(questionID)
            print(response)
            return response
        else:
            return 'There is no User with this ID'
    except Exception as error:
        return str(error)
Exemplo n.º 15
0
def user_login():
    """
    login process - verifying the user - username & password.
    :return: if the login was successful
    :rtype: boolean
    """
    global curr_user, user_database
    curr_user = ""
    username_input = input("\nenter your username: "******"enter your password: ", stream=None)
    if (not user_database.user_in_DB(username_input)
        ):  # checking if the user in the databse
        user_database.register_user(username_input, password_input)
    curr_user = User(
        username_input, password_input, user_database.getID(
            username_input))  # creating a User object with its credentials
    return user_database.confirm_User(username_input, password_input)
Exemplo n.º 16
0
def handleQuestion():
    if(request.method=='POST'):
        try:
            content=request.json
            userID=content['userID']
            if(User.checkUserByID(userID)==True):
                userMail=content['userMail']
                title=content['title']
                detail=content['detail']
                videoLink=content['videoLink']
                videoTime=content['videoTime']
                question=Question(userID,userMail,title,detail,videoLink,videoTime)
                response=question.insertQuestion()
                print(response)
                return response
            else:
                print('testere')
                return 'There is no User with this ID'
        except Exception as error:
            return str(error)
    
    else:
        try:
            videoLink=request.args.get('videoLink')
            videoTime=request.args.get('videoTime')
            questions=Question.getQuestionsByVideoAndTime(videoLink,videoTime)
            questionList=[]
            for question in questions:
                likes=question.likes
                likeList=[]
                for like in likes:
                    likeList.append(like.__dict__)
                questionDict={'_id':str(question._id),'userID':str(question.userID),'userMail':question.userMail,'title':question.title,\
                    'detail':question.detail,'videoTime':question.videoTime,'likes':likeList,'point':question.point,'answerCount':len(question.answers)}
                questionList.append(questionDict)
            return json.dumps(questionList)
        except Exception as error:
            return str(error)
Exemplo n.º 17
0
def handleAnswer():
    if(request.method=='POST'):
        try:
            content=request.json
            userID=content['userID']
            if(User.checkUserByID(userID)==True):
                userMail=content['userMail']
                questionID=content['questionID']
                detail=content['detail']
                isTeacher=content['isTeacher']
                answer=Answer(userID,userMail,detail,isTeacher)
                response=answer.insertAnswerByQuestionID(questionID)
                print(response)
                return response
            else:
                return 'There is no User with this ID'
        except Exception as error:
            return str(error)
    
    else:
        try:
            questionID=request.args.get('questionID')
            question=Question.getQuestionsByQuestionID(questionID)
            answerList=[]
            answers=question.answers
            for answer in answers:
                print(answer.__dict__)
                likes=answer.likes
                likeList=[]
                for like in likes:
                    likeList.append(like.__dict__)
                answerDict={'_id':str(answer._id),'userID':str(answer.userID),'userMail':answer.userMail,\
                    'detail':answer.detail,'point':answer.point,'likes':likeList,'isTeacher':answer.isTeacher}
                answerList.append(answerDict)
            return json.dumps(answerList)
            
        except Exception as error:
            return str(error)
Exemplo n.º 18
0
        self._wb.save('UserData.xls')
        return register_check

    def database_update(self):
        #Not yet implemented
        return

    def user_update(self):
        #Not yet implemented
        return


if __name__ == "__main__":
    test_id = int(input('ID to test: '))
    from UserClass import User
    test = User(test_id)
    print('1. Recall User. | 2. Register User.')
    test_choice = int(input('Choice: '))
    if test_choice == 1:
        recall_result = test.user_recall()
        if recall_result == True:
            print('First Name: ' + test._first_name)
            print('Last Name: ' + test._last_name)
            print('Email: ' + test._email)
            print('Status: ' + str(test._status))
            print('Stored Strength: ' + str(test._strength))
            print('Stored Volume: ' + str(test._volume))
        else:
            print('ID not registered')
    elif test_choice == 2:
        test.user_register('*****@*****.**')
Exemplo n.º 19
0
def new_user():
    name = input('What is your name?\n')
    user = User(name=name)
    user.save_user_data()
    print('Switched ' + user.name + ' to current user')
    return user