def recieve_files(reciever, pwd, server, token,auto=False):
    files = network_operations.check_for_files(reciever, server,token)
    if(len(files)):
        if auto == True:
            return "There are files shared with you waiting to be downloaded..."
        shared_with_me = {}
        for x in files:
            try:
                shared_with_me[x["sender"]].append(x["path"])
            except:
                shared_with_me.update({x["sender"]: [x["path"]]})
        
        for x in shared_with_me:
            print("User ", x, " has sent you", len(shared_with_me[x]), " file(s)")
            choice = input("Do you want to download them? (Make sure you have the key...)")
            if(choice.lower() == "y" or choice.lower() == "yes"):
                key_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp_key.dat")
                en_de.get_schema(path=key_path)
                for file in shared_with_me[x]:
                    print("Downloading ", file)
                    status = create_file(file, pwd, reciever, server, token, key_path, sender=x,shared=True)
                    if status == True:
                        network_operations.recieved_shared(reciever,x, file, server,token)
                        print("Backing file up...")
                        # reciever_uploader = network_operations.get_user_id(reciever,server)
                        # if (file in [x["path"] for x in get_paths(server,data["sender"])]):
                        # print("There is a conflict in ",file,". \nResolve and resync with the server")
                        # else:
                        rec_id = network_operations.get_user_id(reciever,server,token)
                        network_operations.upload_file(file, pwd,rec_id, server, token,reciever,KEY_PATH)
                    else:
                        print("The key that",x,"gave you was probably incorrect... You may want to review your friendship.")
def send_file(user, reciever, path, pwd, server, token):
    '''
    '''
    if(network_operations.get_user_id(reciever, server, token) != -1):
        
        # network_operations.send_sharing_file(server, data)
        create_file(path, pwd, user, server, token)
        print("Generating a shared key for ", path)
        temp_key_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp_key.dat")
        en_de.get_schema(path=temp_key_path)
        reciever_uploader = network_operations.get_user_id(reciever, server, token)
        d = network_operations.upload_file(path, pwd, reciever_uploader, server, token,reciever, temp_key_path, shared=True)
        data = {"sender": user, "reciever": reciever, "path": path,'md5sum':d["md5sum"],'data':d["data"]}
        network_operations.send_sharing_file(server,data,token)
        print("The key for the file can be found in your home folder under the name 'temp_key.dat', if you wish to share it")

    else:
        print("Enter a valid user")
def login(username, password, server, first=False):
    '''
    Authenticates user
    '''
    url_login = server + "login/"
    print(url_login)
    client = requests.session()
    client.get(url_login)
    csrftoken = client.cookies['csrftoken']
    login_data = {
        'username': username,
        'password': password,
        'csrfmiddlewaretoken': csrftoken
    }
    # val=client.post(url_login, data=login_data)
    # client.close()

    login_data2 = {'username': username, 'password': password}
    first_response = client.post(url_login,
                                 data=login_data,
                                 headers={'csrfmiddlewaretoken': csrftoken})
    print(first_response)
    client.close()

    get_token = {'username': username, 'password': password}
    TOKEN = ""

    # print(val)
    if (str(first_response.url) != url_login):  # Exploiting redirection
        main.USER = username

        if (first):
            second_call = requests.post(server + "token-auth/", json=get_token)
            tok = second_call.json()
            TOKEN = tok['token']

            client2 = requests.session()
            client2.get(server + "spc/token")
            csrftoken2 = client2.cookies['csrftoken']
            payload = {
                'user': username,
                'token': TOKEN,
                'csrfmiddlewaretoken': csrftoken2
            }
            client2.post(server + "spc/token", data=payload)
            client = requests.session()
            APIurl = server + "encAPI/" + username + "/"
            headers = {
                "Authorization": "Token " + TOKEN,
                'Content-type': 'application/json'
            }
            l = client.get(APIurl, headers=headers)

            if (len(l.json())):
                en_de.get_schema()
            else:
                en_de.generate_schema()
            client = requests.session()
            APIurl = server + "encAPI/" + username + "/"
            j = {
                "locked": "N",
                "last_enc_update": time.time(),
                "dead_time_check": time.time()
            }
            post_data = json.dumps(j)
            headers = {
                "Authorization": "Token " + TOKEN,
                'Content-type': 'application/json'
            }
            l = client.post(APIurl, data=post_data, headers=headers)
        return True, TOKEN
    else:
        return False, TOKEN
                    if(allowed):
                        network_operations.send_lock_signal(USER,SERVER,TOKEN,"Y")
                        print("Authenticated")
                        a, d = utils.get_paths_of_uploads_and_downloads(pwd=PWD, server=SERVER, username=USER, update=True, token=TOKEN)
                        # print(a)
                        pwd = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp")
                        try:
                            shutil.rmtree(pwd)
                        except:
                            os.mkdir(pwd)
                        utils.create_files(a, pwd, USER, SERVER, TOKEN)
                        '''
                        TODO - proper UX here
                        '''
                        # utils.resolve_conflicts(c, PWD, USER, d, SERVER)
                        en_de.get_schema()
                        for file in a:
                            network_operations.update_file(file[2:], pwd, USER, SERVER, TOKEN)
                        # utils.update_files(a, pwd, d, SERVER)
                        rmtree(pwd)
                        network_operations.send_lock_signal(USER,SERVER,TOKEN,"N")
                        # utils.upload_files(c, PWD, d, SERVER)

            elif sys.argv[2] == "dump":
                choice = input("The details of the scheme will soon appear on the screen. Do you really want that?\n")
                choice = choice.lower()
                if choice == "y" or choice == "yes":
                    en_de.disp_schema()
                else:
                    print("Well okay then")
            elif sys.argv[2] == "list":