예제 #1
0
 def build(self):
     print("BEFORE")
     self.my_firebase = MyFirebase()
     print(self.my_firebase)
     print("AFTER")
     if platform == 'ios':
         self.refresh_token_file = App.get_running_app().user_data_dir + self.refresh_token_file
     return Builder.load_file("main.kv")#GUI
예제 #2
0
 def __init__(self):
     super().__init__()
     self.myfirebase = MyFirebase()
     self.dialog = MDDialog()
     self.report = ""
     self.theme_cls.primary_palette = 'Red'
     self.start_screen = StartScreen(self)
     self.menu_screen = MenuScreen(self)
     self.screen_manager = ScreenManager()
예제 #3
0
class Myapp(MDApp):
    my_id = 1

    def __init__(self, **kwargs):
        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "Blue"
        self.sm = ScreenManager()
        super().__init__(**kwargs)

    def show_popup(self, mssg):
        toast("" + mssg)

    def change_screen(self, screen_name):
        screen_manager = self.root.ids['screen_manager']
        screen_manager.current = screen_name

    def animate_card(self, widget):
        anim = Animation(pos_hint={"center_y": 0.6}, duration=0.8)
        anim.start(widget)

    def animate_background(self, widget):
        anim = Animation(size_hint_y=1, duration=0.4) + Animation(
            size_hint_y=0.5, duration=0.4)
        anim.start(widget.ids.bx)

    def build(self):
        Gui = Builder.load_file("main.kv")
        self.sm.add_widget(Factory.SigninScreen(name="signin_screen"))
        self.my_firebase = MyFirebase()
        return Gui

    def on_start(self):
        try:
            with open("refresh_token.txt", "r") as f:
                refresh_token = f.read()
                id_token, local_id = self.my_firebase.exchange_refresh_token(
                    refresh_token)
            result = requests.get("https://bestbuydb-40d9e.firebaseio.com/" +
                                  local_id + ".json?auth=" + id_token)
            data = json.loads(result.content.decode())
            self.root.ids['screen_manager'].transition = NoTransition()
            self.change_screen("search_screen")
            self.root.ids['screen_manager'].transition = CardTransition()
        except Exception as e:
            pass
예제 #4
0
class MainApp(App):
    def build(self):
        self.my_firebase = MyFirebase()
        return GUI

    def on_start(self):

        try:
            with open("refresh_token.txt", 'r') as f:
                refresh_token = f.read()
            id_token, local_id = self.my_firebase.exchange_refresh_token(
                refresh_token)
            self.local_id = local_id
            self.id_token = id_token
            # Get database data
            result = requests.get(
                "https://expensetracker-d3a98.firebaseio.com/" + local_id +
                ".json?auth=" + id_token)
            data = json.loads(result.content.decode())

            self.change_screen("connected")

        except Exception:
            print("EXCEPTION")
            traceback.print_exc()
            print("EXCEPTION")
            pass

    def change_screen(self, screen_name):
        screen_manager = self.root.ids['screen_manager']
        screen_manager.current = screen_name

    def connected_change_screen(self, screen_name):
        screen_manager = self.root.ids['connected'].ids[
            'connected_screen_manager']
        screen_manager.current = screen_name
예제 #5
0
 def build(self):
     self.my_firebase = MyFirebase()
     return GUI
예제 #6
0
class MainApp(App):
    my_friend_id = 1
    workout_image = None
    option_choice = None

    def build(self):
        self.my_firebase = MyFirebase()
        return GUI

    def update_workout_image(self, filename, widget_id):
        self.workout_image = filename

    def on_start(self):
        # Populate avatar grid
        avatar_grid = self.root.ids['change_avatar_screen'].ids['avatar_grid']
        for root_dir, folders, files in walk("icons/avatars"):
            for f in files:
                img = ImageButton(source="icons/avatars/" + f,
                                  on_release=partial(self.change_avatar, f))
                avatar_grid.add_widget(img)

        # Populate workout image grid
        workout_image_grid = self.root.ids['add_workout_screen'].ids[
            'workout_image_grid']
        for root_dir, folders, files in walk("icons/workouts"):
            for f in files:
                if '.png' in f:
                    img = ImageButton(source="icons/workouts/" + f,
                                      on_release=partial(
                                          self.update_workout_image, f))
                    workout_image_grid.add_widget(img)

        try:
            # Try to read the persisten signin credentials (refresh token)
            with open("refresh_token.txt", 'r') as f:
                refresh_token = f.read()
            # Use refresh token to get a new idToken
            id_token, local_id = self.my_firebase.exchange_refresh_token(
                refresh_token)
            self.local_id = local_id
            self.id_token = id_token

            # Get database data
            result = requests.get("https://friendly-fitness.firebaseio.com/" +
                                  local_id + ".json?auth=" + id_token)
            print("res ok?", result.ok)
            print(result.json())
            data = json.loads(result.content.decode())

            # Get and update avatar image
            avatar_image = self.root.ids['avatar_image']
            avatar_image.source = "icons/avatars/" + data['avatar']

            # Get friends list
            self.friends_list = data['friends']

            # Get and update streak label
            streak_label = self.root.ids['home_screen'].ids['streak_label']
            streak_label.text = str(data['streak']) + " Day Streak!"

            # Get and update friend id label
            friend_id_label = self.root.ids['settings_screen'].ids[
                'friend_id_label']
            friend_id_label.text = "Friend ID: " + str(self.my_friend_id)

            banner_grid = self.root.ids['home_screen'].ids['banner_grid']
            print("----")
            print(data['workouts'])
            workouts = data['workouts']
            workout_keys = workouts.keys()
            for workout_key in workout_keys:
                workout = workouts[workout_key]
                # Populate workout grid in home screen
                W = WorkoutBanner(workout_image=workout['workout_image'],
                                  description=workout['description'],
                                  type_image=workout['type_image'],
                                  number=workout['number'],
                                  units=workout['units'],
                                  likes=workout['likes'])
                banner_grid.add_widget(W)

            self.root.ids['screen_manager'].transition = NoTransition()
            self.change_screen("home_screen")
            self.root.ids['screen_manager'].transition = CardTransition()

        except Exception as e:
            print(e)
            pass

    def add_friend(self, friend_id):
        # Query database and make sure friend_id exists
        check_req = requests.get(
            'https://friendly-fitness.firebaseio.com/.json?orderBy="my_friend_id"&equalTo='
            + friend_id)
        data = check_req.json()

        if data == {}:
            # If it doesn't, display it doesn't in the message on the add friend screen
            self.root.ids['add_friend_screen'].ids[
                'add_friend_label'].text = "Invalid friend ID"
        else:
            key = data.keys()[0]
            new_friend_id = data[key]['my_friend_id']
            self.root.ids['add_friend_screen'].ids[
                'add_friend_label'].text = "Friend ID %s added successfully." % friend_id
            # Add friend id to friends list and patch new friends list
            self.friends_list += ", %s" % friend_id
            patch_data = '{"friends": "%s"}' % self.friends_list
            patch_req = requests.patch(
                "https://friendly-fitness.firebaseio.com/%s.json?auth=%s" %
                (self.local_id, self.id_token),
                data=patch_data)
            print(patch_req.ok)
            print(patch_req.json())

        # If it does, display "success"
        # If it does, add to friends list

    def change_avatar(self, image, widget_id):
        # Change avatar in the app
        avatar_image = self.root.ids['avatar_image']
        avatar_image.source = "icons/avatars/" + image

        # Change avatar in firebase database
        my_data = '{"avatar": "%s"}' % image
        requests.patch("https://friendly-fitness.firebaseio.com/" +
                       str(self.my_friend_id) + ".json",
                       data=my_data)

        self.change_screen("settings_screen")

    def add_workout(self):
        # Get data from all fields in add workout screen
        workout_ids = self.root.ids['add_workout_screen'].ids

        # Already have workout image in self.workout_image variable
        description_input = workout_ids['description_input'].text
        # Already have option choice in self.option_choice
        quantity_input = workout_ids['quantity_input'].text
        units_input = workout_ids['units_input'].text
        month_input = workout_ids['month_input'].text
        day_input = workout_ids['day_input'].text
        year_input = workout_ids['year_input'].text

        # Make sure fields aren't garbage
        if self.workout_image == None:
            print("come back to this")
            return
        # They are allowed to leave no description
        if self.option_choice == None:
            workout_ids['time_label'].color = (1, 0, 0, 1)
            workout_ids['distance_label'].color = (1, 0, 0, 1)
            workout_ids['sets_label'].color = (1, 0, 0, 1)
            return
        try:
            int_quantity = float(quantity_input)
        except:
            workout_ids['quantity_input'].background_color = (1, 0, 0, 1)
            return
        if units_input == "":
            workout_ids['units_input'].background_color = (1, 0, 0, 1)
            return
        try:
            int_month = int(month_input)
        except:
            workout_ids['month_input'].background_color = (1, 0, 0, 1)
            return
        try:
            int_day = int(day_input)
        except:
            workout_ids['day_input'].background_color = (1, 0, 0, 1)
            return
        try:
            int_year = int(year_input)
        except:
            workout_ids['year_input'].background_color = (1, 0, 0, 1)
            return

        # If all data is ok, send the data to firebase real-time database
        workout_payload = {
            "workout_image": self.workout_image,
            "description": description_input,
            "likes": 0,
            "number": float(quantity_input),
            "type_image": self.option_choice,
            "units": units_input,
            "date": month_input + "/" + day_input + "/20" + year_input
        }
        workout_request = requests.post(
            "https://friendly-fitness.firebaseio.com/%s/workouts.json?auth=%s"
            % (self.local_id, self.id_token),
            data=json.dumps(workout_payload))
        print(workout_request.json())

    def change_screen(self, screen_name):
        # Get the screen manager from the kv file
        screen_manager = self.root.ids['screen_manager']
        screen_manager.current = screen_name
예제 #7
0
class MyApp(App):
    refresh_token_file = "refresh_token.txt"
    wapik = "AIzaSyBvGJKPt0u1NGMku6SqBQwKCcD87QSG23w"

    def build(self):
        self.my_firebase = MyFirebase()
        return sm

    def on_start(self):
        try:
            with open(self.refresh_token_file, 'r') as f:
                refresh_Token = f.read()
            id_Token, local_Id = self.my_firebase.exchange_refresh_token(
                refresh_Token)
            self.local_id = local_Id
            self.id_token = id_Token

            result = requests.get(
                'https://recyclingapp-44e68.firebaseio.com/' + self.local_id +
                '.json?auth=' + self.id_token)
            data = json.loads(result.content.decode())

            cashMoney = data['recycled']
            self.cashMoney = cashMoney

            cashMoney = float(cashMoney)
            cashMoney = '${:,.2f}'.format(cashMoney)

            status = data['status']
            self.status = status
            n = data['nickname']
            self.username = n
            self.root.ids["soul_screen"].ids["recycle_label"].text = str(
                cashMoney)
            self.root.ids['soul_screen'].ids['status'].text = status

            self.updateDetails()
            self.root.current = "soul_screen"
        except:
            pass

    def opensite(self):
        webbrowser.open(
            'https://www.calrecycle.ca.gov/BevContainer/Consumers/Facts/')

    def check_popup(self, title, text):
        show = P2()
        popupWindow = Popup(title=title, content=show, size_hint=(.8, .4))
        popupWindow.open()

    def status_popup(self, title, text):
        #have two different popups, 1 for stats, 1 for making sure if you wanna resetbin
        show = P1()
        popupWindow = Popup(title=title, content=show, size_hint=(.8, .4))
        popupWindow.open()

    def init_status(self, stats):
        self.root.ids["soul_screen"].ids['status'].text = stats

    def check_status(self, cashMoney, stats):
        if (cashMoney > 10.0 and cashMoney < 20.0 and stats != "Lancer"):
            newStatus = "Lancer"
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            statsPatch = '{"status": "%s"}' % newStatus
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 20.0 and cashMoney < 40.0 and stats != "Gallant"):
            newStatus = "Gallant"
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            statsPatch = '{"status": "%s"}' % newStatus
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 40.0 and cashMoney < 60.0):
            if (stats != "Keeper"):
                newStatus = "Keeper"
                text = "Your status has updated!"
                self.status_popup(newStatus, text)
                statsPatch = '{"status": "%s"}' % newStatus
                requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                               self.local_id + '.json?auth=' + self.id_token,
                               data=statsPatch)
                self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 60.0 and cashMoney < 80.0):
            if (stats != "Protector"):
                newStatus = "Protector"
                text = "Your status has updated!"
                self.status_popup(newStatus, text)
                statsPatch = '{"status": "%s"}' % newStatus
                requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                               self.local_id + '.json?auth=' + self.id_token,
                               data=statsPatch)
                self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 80.0 and cashMoney < 100.0 and stats != "Defender"):
            newStatus = "Defender"
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            statsPatch = '{"status": "%s"}' % newStatus
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 100.0 and cashMoney < 140.0 and stats != "Warder"):
            newStatus = "Warder"
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            statsPatch = '{"status": "%s"}' % newStatus
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 140.0 and cashMoney < 200.0 and stats != "Guardian"):
            newStatus = "Guardian"
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            statsPatch = '{"status": "%s"}' % newStatus
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 200.0 and cashMoney < 300.0 and stats != "Chevaliar"):
            newStatus = "Chevaliar"
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            statsPatch = '{"status": "%s"}' % newStatus
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 300.0 and cashMoney < 500.0 and stats != "Justiciar"):
            newStatus = "Justiciar"
            statsPatch = '{"status": "%s"}' % newStatus
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus
        if (cashMoney > 500.0 and stats != "Paladin"):
            newStatus = "Paladin"
            text = "Your status has updated!"
            self.status_popup(newStatus, text)
            statsPatch = '{"status": "%s"}' % newStatus
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=statsPatch)
            self.root.ids["soul_screen"].ids["status"].text = newStatus

    def smallCount(self, num):
        result = requests.get('https://recyclingapp-44e68.firebaseio.com/' +
                              self.local_id + '.json?auth=' + self.id_token)
        data = json.loads(result.content.decode())
        cash_M = data["recycled"]
        total_recycled = data["total_recycled"]

        stats = data["status"]
        smallB = data["smallBottles"]
        csmallB = data["csmallBottles"]

        small_B = int(smallB) + int(num)
        csmall_B = int(csmallB) + int(num)
        num = int(num)
        cM = float(cash_M) + (num * .05)
        t_cM = float(total_recycled) + (num * .05)

        cashMoney_arg = t_cM

        cashMoneyPatch = '{"recycled": "%s"}' % str(cM)
        t_cashMoneyPatch = '{"total_recycled": "%s"}' % str(t_cM)
        smallB_Patch = '{"smallBottles": "%s"}' % str(small_B)
        csmallB_Patch = '{"csmallBottles": "%s"}' % str(csmall_B)

        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=cashMoneyPatch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=t_cashMoneyPatch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=smallB_Patch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=csmallB_Patch)

        cM = float(cM)
        cM = '${:,.2f}'.format(cM)

        self.check_status(cashMoney_arg, stats)

        self.updateDetails()

        sHintText = self.root.ids["entry_screen"].ids["small_input"].text
        if (sHintText != ""):
            self.root.ids["entry_screen"].ids["small_input"].text = ''
            self.root.current = "soul_screen"

    def bigCount(self, num):
        result = requests.get('https://recyclingapp-44e68.firebaseio.com/' +
                              self.local_id + '.json?auth=' + self.id_token)
        data = json.loads(result.content.decode())
        cash_M = data["recycled"]
        total_recycled = data["total_recycled"]
        stats = data["status"]
        bigB = data["bigBottles"]
        cbigB = data["cbigBottles"]

        #increment # of big bottles, and curr money, total money
        big_B = int(bigB) + int(num)
        cbig_B = int(cbigB) + int(num)
        num = int(num)

        cM = float(cash_M) + (num * .10)
        t_cM = float(total_recycled) + (num * .10)

        #check total recycled for leveling
        cashMoney_arg = t_cM

        cashMoneyPatch = '{"recycled": "%s"}' % str(cM)
        t_cashMoneyPatch = '{"total_recycled": "%s"}' % str(t_cM)
        bigB_Patch = '{"bigBottles": "%s"}' % str(big_B)
        cbigB_Patch = '{"cbigBottles": "%s"}' % str(cbig_B)

        #update total money, current bin money, and # of big bottles
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=cashMoneyPatch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=t_cashMoneyPatch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=bigB_Patch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=cbigB_Patch)

        #convert to dollar format
        cM = float(cM)
        cM = '${:,.2f}'.format(cM)

        #check if user has levelled up
        self.check_status(cashMoney_arg, stats)

        #update details_screen
        self.updateDetails()

        #clear entry screen, return home
        bHintText = self.root.ids["entry_screen"].ids["big_input"].text
        if (bHintText != ""):
            self.root.ids["entry_screen"].ids["big_input"].text = ''
            self.root.current = "soul_screen"

    def subSmallCount(self, num):
        result = requests.get('https://recyclingapp-44e68.firebaseio.com/' +
                              self.local_id + '.json?auth=' + self.id_token)
        data = json.loads(result.content.decode())
        cash_M = data["recycled"]
        total_recycled = data["total_recycled"]

        stats = data["status"]
        smallB = data["smallBottles"]
        csmallB = data["csmallBottles"]

        small_B = int(smallB) - int(num)
        csmall_B = int(csmallB) - int(num)
        num = int(num)
        cM = float(cash_M) - (num * .05)
        t_cM = float(total_recycled) - (num * .05)

        if (cM < 0):
            print(cM)
            msg = "Invalid Submission"
            self.root.ids["undo_screen"].ids["errormsg"].text = msg

        else:
            cashMoney_arg = t_cM

            cashMoneyPatch = '{"recycled": "%s"}' % str(cM)
            t_cashMoneyPatch = '{"total_recycled": "%s"}' % str(t_cM)
            smallB_Patch = '{"smallBottles": "%s"}' % str(small_B)
            csmallB_Patch = '{"csmallBottles": "%s"}' % str(csmall_B)

            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=cashMoneyPatch)
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=t_cashMoneyPatch)
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=smallB_Patch)
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=csmallB_Patch)

            cM = float(cM)
            cM = '${:,.2f}'.format(cM)
            print(cM)
            self.check_status(cashMoney_arg, stats)
            #updates money/recycling labels
            self.updateDetails()

            sHintText = self.root.ids["undo_screen"].ids["small_input"].text
            if (sHintText != ""):
                self.root.ids["undo_screen"].ids["small_input"].text = ''
                self.root.current = "soul_screen"

    def subBigCount(self, num):
        result = requests.get('https://recyclingapp-44e68.firebaseio.com/' +
                              self.local_id + '.json?auth=' + self.id_token)
        data = json.loads(result.content.decode())
        cash_M = data["recycled"]
        total_recycled = data["total_recycled"]
        stats = data["status"]
        bigB = data["bigBottles"]
        cbigB = data["cbigBottles"]

        #increment # of big bottles, and curr money, total money
        big_B = int(bigB) - int(num)
        cbig_B = int(cbigB) - int(num)
        num = int(num)

        cM = float(cash_M) - (num * .10)
        t_cM = float(total_recycled) - (num * .10)

        if (cM < 0):
            msg = "Invalid Submission"
            self.root.ids["undo_screen"].ids["errormsg"].text = msg

        else:
            #check total recycled for leveling
            cashMoney_arg = t_cM

            cashMoneyPatch = '{"recycled": "%s"}' % str(cM)
            t_cashMoneyPatch = '{"total_recycled": "%s"}' % str(t_cM)
            bigB_Patch = '{"bigBottles": "%s"}' % str(big_B)
            cbigB_Patch = '{"cbigBottles": "%s"}' % str(cbig_B)

            #update total money, current bin money, and # of big bottles
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=cashMoneyPatch)
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=t_cashMoneyPatch)
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=bigB_Patch)
            requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                           self.local_id + '.json?auth=' + self.id_token,
                           data=cbigB_Patch)

            cM = float(cM)
            cM = '${:,.2f}'.format(cM)

            #check and update user status
            self.check_status(cashMoney_arg, stats)

            #update score/money
            self.updateDetails()

            #clear entry screen, return home
            bHintText = self.root.ids["undo_screen"].ids["big_input"].text
            if (bHintText != ""):
                self.root.ids["undo_screen"].ids["big_input"].text = ''
                self.root.current = "soul_screen"

    def resetBin(self):
        res = 0
        put = '$0.00'
        binResetPatch = '{"recycled": "%s"}' % str(res)
        c_sb_Patch = '{"csmallBottles": "%s"}' % str(res)
        c_bb_Patch = '{"cbigBottles": "%s"}' % str(res)

        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=binResetPatch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=c_sb_Patch)
        requests.patch('https://recyclingapp-44e68.firebaseio.com/' +
                       self.local_id + '.json?auth=' + self.id_token,
                       data=c_bb_Patch)

        self.root.ids["soul_screen"].ids["recycle_label"].text = put
        self.root.ids["details_screen"].ids["currentsmallBottles"].text = str(
            res)
        self.root.ids["details_screen"].ids["currentbigBottles"].text = str(
            res)
        self.root.ids["details_screen"].ids["currentMoney"].text = put
        pass

    def enterAmount(self, amount):
        pass

    def updateDetails(self):
        result = requests.get('https://recyclingapp-44e68.firebaseio.com/' +
                              self.local_id + '.json?auth=' + self.id_token)
        data = json.loads(result.content.decode())
        sB = data["smallBottles"]
        bB = data["bigBottles"]
        cSB = data["csmallBottles"]
        cBB = data["cbigBottles"]
        totalCash = data["total_recycled"]
        currentCash = data["recycled"]

        totalCash = float(totalCash)
        cM = '${:,.2f}'.format(totalCash)
        currentCash = float(currentCash)
        cCM = '${:,.2f}'.format(currentCash)

        self.root.ids["details_screen"].ids["currentsmallBottles"].text = str(
            cSB)
        self.root.ids["details_screen"].ids["currentbigBottles"].text = str(
            cBB)
        self.root.ids["details_screen"].ids["currentMoney"].text = str(cCM)
        self.root.ids["details_screen"].ids["smallBottles"].text = str(sB)
        self.root.ids["details_screen"].ids["bigBottles"].text = str(bB)
        self.root.ids["details_screen"].ids["totalMoney"].text = str(cM)
        self.root.ids["soul_screen"].ids["recycle_label"].text = str(cCM)
        self.root.ids["undo_screen"].ids["errormsg"].text = ""
        pass

    def setNickname(self, u_name):
        they_name = str(u_name)
        print(they_name)
        result = requests.get('https://recyclingapp-44e68.firebaseio.com/' +
                              self.local_id + '.json?auth=' + self.id_token)
        data = json.loads(result.content.decode())
        nam = data["nickname"]
        print(nam, " is the current nickname")
        namePatch = '{"nickname": "%s"}' % they_name
        print(namePatch)
        name_req = requests.patch(
            'https://recyclingapp-44e68.firebaseio.com/' + self.local_id +
            '.json?auth=' + self.id_token,
            data=namePatch)
        print(name_req.ok)
        print(json.loads(name_req.content.decode()))

    def sign_out(self):

        with open(self.refresh_token_file, 'w') as f:
            f.write("")

        self.root.current = "login_screen"

        self.root.ids.login_screen.ids.username.text = ""
        self.root.ids.login_screen.ids.pwd.text = ""
        self.root.ids.soul_screen.ids.recycle_label.text = ""
        self.root.ids.soul_screen.ids.status.text = ""
        self.root.ids.details_screen.ids.bigBottles.text = ""
        self.root.ids.details_screen.ids.smallBottles.text = ""
        self.root.ids.details_screen.ids.totalMoney.text = ""
예제 #8
0
 def build(self):
     Gui = Builder.load_file("main.kv")
     self.sm.add_widget(Factory.SigninScreen(name="signin_screen"))
     self.my_firebase = MyFirebase()
     return Gui
예제 #9
0
class MainApp(App):
    my_friend_id = ""
    workout_image = None
    option_choice = None
    workout_image_widget = ""
    previous_workout_image_widget = None
    friends_list = ""
    refresh_token_file = "refresh_token.txt"
    nicknames = DictProperty(
    )  # Dictionary of nicknames for each friend id in friends list
    their_friend_id = ""  # Make it so we know which friend's workout screen has been loaded for app.set_friend_nickname
    my_firebase = None  # Reference to class in myfirebase.py

    def build(self):
        print("BEFORE")
        self.my_firebase = MyFirebase()
        print(self.my_firebase)
        print("AFTER")
        if platform == 'ios':
            self.refresh_token_file = App.get_running_app(
            ).user_data_dir + self.refresh_token_file
        return Builder.load_file("main.kv")  #GUI

    def set_friend_nickname(self, nickname, *args):
        # Make sure they entered something
        if nickname == "":
            return
        # Set the nickname
        print("YO", self.their_friend_id, type(self.their_friend_id))
        print(self.nicknames)
        self.nicknames[int(self.their_friend_id)] = nickname

        # Update firebase
        print(self.nicknames)
        print(json.dumps(self.nicknames))
        workout_request = requests.patch(
            "https://friendly-fitness.firebaseio.com/%s/nicknames.json?auth=%s"
            % (self.local_id, self.id_token),
            data=json.dumps(self.nicknames))
        print(workout_request.content)
        # Update the nickname in the friend_workout_screen
        their_friend_id_label = self.root.ids.friend_workout_screen.ids.friend_workout_screen_friend_id
        their_friend_id_label.text = "[u]" + nickname + "[/u]"

        # Update the nickname in the friend workout banner
        # Go through each widget in the friends list grid
        for w in self.root.ids['friends_list_screen'].ids[
                'friends_list_grid'].walk():
            if w.__class__ == FriendBanner:
                if w.friend_id == self.their_friend_id:
                    w.update_friend_label_text(their_friend_id_label.text)

    def update_workout_image(self, filename, widget_id):
        self.previous_workout_image_widget = self.workout_image_widget
        self.workout_image = filename
        self.workout_image_widget = widget_id
        # Clear the indication that the previous image was selected
        if self.previous_workout_image_widget:
            self.previous_workout_image_widget.canvas.before.clear()
        # Make sure the text color of the label above the scrollview is white (incase it was red from them earlier)
        select_workout_image_label = self.root.ids.add_workout_screen.ids.select_workout_image_label
        select_workout_image_label.color = (1, 1, 1, 1)

        # Indicate which image has been selected
        with self.workout_image_widget.canvas.before:
            Color(rgb=(kivy.utils.get_color_from_hex("#6C5B7B")))
            RoundedRectangle(size=self.workout_image_widget.size,
                             pos=self.workout_image_widget.pos,
                             radius=[
                                 5,
                             ])

    def on_start(self):
        # Display the ads
        if platform == 'ios':
            from pyobjus import autoclass
            self.banner_ad = autoclass('adSwitch').alloc().init()

        # Choose the correct time icon to show based on the current hour of day
        now = datetime.now()
        hour = now.hour
        if hour <= 6:
            self.root.ids['time_indicator1'].opacity = 1
        elif hour <= 12:
            self.root.ids['time_indicator2'].opacity = 1
        elif hour <= 18:
            self.root.ids['time_indicator3'].opacity = 1
        else:
            self.root.ids['time_indicator4'].opacity = 1

        # Set the current day, month, and year in the add workout section
        day, month, year = now.day, now.month, now.year
        self.root.ids.add_workout_screen.ids.month_input.text = str(month)
        self.root.ids.add_workout_screen.ids.day_input.text = str(day)
        self.root.ids.add_workout_screen.ids.year_input.text = str(year)

        # Populate avatar grid
        avatar_grid = self.root.ids['change_avatar_screen'].ids['avatar_grid']
        for root_dir, folders, files in walk("icons/avatars"):
            for f in files:
                img = ImageButtonSelectable(source="icons/avatars/" + f,
                                            on_release=partial(
                                                self.change_avatar, f))
                avatar_grid.add_widget(img)

        # Populate workout image grid
        workout_image_grid = self.root.ids['add_workout_screen'].ids[
            'workout_image_grid']
        for root_dir, folders, files in walk("icons/workouts"):
            for f in files:
                if '.png' in f:
                    img = ImageButton(source="icons/workouts/" + f,
                                      on_release=partial(
                                          self.update_workout_image, f))
                    workout_image_grid.add_widget(img)

        try:
            # Try to read the persistent signin credentials (refresh token)
            with open(self.refresh_token_file, 'r') as f:
                refresh_token = f.read()
            # Use refresh token to get a new idToken
            id_token, local_id = self.my_firebase.exchange_refresh_token(
                refresh_token)
            self.local_id = local_id
            self.id_token = id_token

            # Get database data
            print("LOCAL ID IS", local_id)
            print("https://friendly-fitness.firebaseio.com/" + local_id +
                  ".json?auth=" + id_token)
            result = requests.get("https://friendly-fitness.firebaseio.com/" +
                                  local_id + ".json?auth=" + id_token)
            data = json.loads(result.content.decode())
            print("id token is", id_token)
            print(result.ok)
            print("DATA IS", data)
            self.my_friend_id = data['my_friend_id']
            friend_id_label = self.root.ids['settings_screen'].ids[
                'friend_id_label']
            friend_id_label.text = "Friend ID: " + str(self.my_friend_id)

            # Get and update avatar image
            avatar_image = self.root.ids['avatar_image']
            avatar_image.source = "icons/avatars/" + data['avatar']

            # Get friends list
            self.friends_list = data['friends']

            # Get nicknames
            try:
                print(data['nicknames'])
                for i, friend_id in enumerate(self.friends_list.split(",")):
                    if friend_id:
                        print(i, friend_id)
                        self.nicknames[friend_id] = data['nicknames'][i]
            except:
                self.nicknames = data.get('nicknames', {})
            # Populate friends list grid
            friends_list_array = self.friends_list.split(",")
            for friend_id in friends_list_array:
                friend_id = friend_id.replace(" ", "")
                if friend_id == "":
                    continue
                try:
                    nicknames = list(self.friends_list.keys())
                except:
                    nicknames = self.nicknames
                if friend_id in nicknames:
                    friend_id_text = "[u]" + self.nicknames[friend_id] + "[/u]"
                else:
                    friend_id_text = "[u]Friend ID: " + friend_id + "[/u]"
                friend_banner = FriendBanner(friend_id=friend_id,
                                             friend_id_text=friend_id_text)
                self.root.ids['friends_list_screen'].ids[
                    'friends_list_grid'].add_widget(friend_banner)

            # Get and update streak label
            streak_label = self.root.ids['home_screen'].ids['streak_label']
            #streak_label.text = str(data['streak']) + " Day Streak" # Thisis updated if there are workouts

            # Set the images in the add_workout_screen
            banner_grid = self.root.ids['home_screen'].ids['banner_grid']
            workouts = data['workouts']
            if workouts != "":
                workout_keys = list(workouts.keys())
                streak = helperfunctions.count_workout_streak(workouts)
                if str(streak) == 0:
                    streak_label.text = "0 Day Streak. Go workout!"
                else:
                    streak_label.text = str(streak) + " Day Streak!"
                # Sort workouts by date then reverse (we want youngest dates at the start)
                workout_keys.sort(key=lambda value: datetime.strptime(
                    workouts[value]['date'], "%m/%d/%Y"))
                workout_keys = workout_keys[::-1]
                for workout_key in workout_keys:
                    workout = workouts[workout_key]
                    # Populate workout grid in home screen
                    W = WorkoutBanner(workout_image=workout['workout_image'],
                                      description=workout['description'],
                                      type_image=workout['type_image'],
                                      number=workout['number'],
                                      units=workout['units'],
                                      likes=workout['likes'],
                                      date=workout['date'])
                    banner_grid.add_widget(W)

            self.change_screen("home_screen", "None")

        except Exception as e:
            traceback.print_exc()
            pass

    def set_friend_id(self, my_friend_id):
        self.my_friend_id = my_friend_id
        friend_id_label = self.root.ids['settings_screen'].ids[
            'friend_id_label']
        friend_id_label.text = "Friend ID: " + str(self.my_friend_id)

    def add_friend(self, friend_id):
        friend_id = friend_id.replace("\n", "")
        # Make sure friend id was a number otherwise it's invalid
        try:
            int_friend_id = int(friend_id)
        except:
            # Friend id had some letters in it when it should just be a number
            self.root.ids['add_friend_screen'].ids[
                'add_friend_label'].text = "Friend ID should be a number."
            return
        # Make sure they aren't adding themselves
        if friend_id == self.my_friend_id:
            self.root.ids['add_friend_screen'].ids[
                'add_friend_label'].text = "You can't add yourself as a friend."
            return

        # Make sure this is not someone already in their friends list
        if friend_id in self.friends_list.split(","):
            self.root.ids['add_friend_screen'].ids[
                'add_friend_label'].text = "This user is already in your friend's list."
            return

        # Query database and make sure friend_id exists
        check_req = requests.get(
            'https://friendly-fitness.firebaseio.com/.json?orderBy="my_friend_id"&equalTo='
            + friend_id)
        data = check_req.json()

        if data == {}:
            # If it doesn't, display it doesn't in the message on the add friend screen
            self.root.ids['add_friend_screen'].ids[
                'add_friend_label'].text = "Invalid friend ID"
        else:
            # Requested friend ID exists
            key = list(data.keys())[0]
            #new_friend_id = data[key]['my_friend_id']

            # Add friend id to friends list and patch new friends list
            self.friends_list += ",%s" % friend_id
            patch_data = '{"friends": "%s"}' % self.friends_list
            patch_req = requests.patch(
                "https://friendly-fitness.firebaseio.com/%s.json?auth=%s" %
                (self.local_id, self.id_token),
                data=patch_data)

            # Add new friend banner in friends list screen
            if friend_id in self.nicknames.keys():
                friend_id_text = "[u]" + self.nicknames[friend_id] + "[/u]"
            else:
                friend_id_text = "[u]Friend ID: " + friend_id + "[/u]"
            friend_banner = FriendBanner(friend_id=friend_id,
                                         friend_id_text=friend_id_text)
            self.root.ids['friends_list_screen'].ids[
                'friends_list_grid'].add_widget(friend_banner)
            # Inform them they added a friend successfully
            self.root.ids['add_friend_screen'].ids[
                'add_friend_label'].text = "Friend ID %s added successfully." % friend_id
        print(self.nicknames)

    def sign_out_user(self):
        # User wants to log out
        with open(self.refresh_token_file, 'w') as f:
            f.write("")
        self.change_screen("login_screen", direction='down', mode='push')
        # Need to set the avatar to the default image
        avatar_image = self.root.ids['avatar_image']
        avatar_image.source = "icons/avatars/man.png"

        add_friend_screen = self.root.ids.add_friend_screen
        add_friend_screen.ids.add_friend_label.text = ""
        add_friend_screen.ids.add_friend_input.text = ""

        # Clear home screen
        self.root.ids.home_screen.ids.streak_label.text = "0 Day Streak. Go workout!"

        # Clear login screen
        self.root.ids.login_screen.ids.login_email.text = ""
        self.root.ids.login_screen.ids.login_password.text = ""

        # Clear workout screen
        workout_screen = self.root.ids.add_workout_screen
        workout_screen.ids.description_input.text = ""
        workout_screen.ids.time_label.color = (0, 0, 0, 1)
        workout_screen.ids.distance_label.color = (0, 0, 0, 1)
        workout_screen.ids.sets_label.color = (0, 0, 0, 1)
        workout_screen.ids.quantity_input.text = ""
        workout_screen.ids.quantity_input.background_color = (1, 1, 1, 1)
        workout_screen.ids.units_input.text = ""
        workout_screen.ids.units_input.background_color = (1, 1, 1, 1)
        now = datetime.now()
        day, month, year = now.day, now.month, now.year
        workout_screen.ids.month_input.text = str(month)
        workout_screen.ids.month_input.background_color = (1, 1, 1, 1)
        workout_screen.ids.day_input.text = str(day)
        workout_screen.ids.day_input.background_color = (1, 1, 1, 1)
        workout_screen.ids.year_input.text = str(year)
        workout_screen.ids.year_input.background_color = (1, 1, 1, 1)

        self.workout_image = None
        self.option_choice = None
        # Clear the indication that the previous image was selected
        if self.workout_image_widget:
            self.workout_image_widget.canvas.before.clear()
        # Make sure the text color of the label above the scrollview is white (incase it was red from them earlier)
        select_workout_image_label = workout_screen.ids.select_workout_image_label
        select_workout_image_label.color = (1, 1, 1, 1)

        # Need to clear widgets from previous user's friends list
        friends_list_grid = self.root.ids['friends_list_screen'].ids[
            'friends_list_grid']
        for w in friends_list_grid.walk():
            if w.__class__ == FriendBanner:
                friends_list_grid.remove_widget(w)

        # Need to clear widgets from previous user's workout grid
        workout_banner = self.root.ids['home_screen'].ids['banner_grid']
        for w in workout_banner.walk():
            if w.__class__ == WorkoutBanner:
                workout_banner.remove_widget(w)

        # Need to clear widgets from previous user's friend's workout grid
        friend_banner_grid = self.root.ids['friend_workout_screen'].ids[
            'friend_banner_grid']
        for w in friend_banner_grid.walk():
            if w.__class__ == WorkoutBanner:
                friend_banner_grid.remove_widget(w)

    def change_avatar(self, image, widget_id):
        # Change avatar in the app
        avatar_image = self.root.ids['avatar_image']
        avatar_image.source = "icons/avatars/" + image

        # Change avatar in firebase database
        my_data = '{"avatar": "%s"}' % image
        requests.patch(
            "https://friendly-fitness.firebaseio.com/%s.json?auth=%s" %
            (self.local_id, self.id_token),
            data=my_data)

        self.change_screen("settings_screen", direction='left', mode='pop')

    def add_workout(self):
        # Get data from all fields in add workout screen
        workout_ids = self.root.ids['add_workout_screen'].ids

        workout_image_grid = self.root.ids['add_workout_screen'].ids[
            'workout_image_grid']
        select_workout_image_label = self.root.ids.add_workout_screen.ids.select_workout_image_label

        # Already have workout image in self.workout_image variable
        description_input = workout_ids['description_input'].text.replace(
            "\n", "")
        # Already have option choice in self.option_choice
        quantity_input = workout_ids['quantity_input'].text.replace("\n", "")
        units_input = workout_ids['units_input'].text.replace("\n", "")
        month_input = workout_ids['month_input'].text.replace("\n", "")
        day_input = workout_ids['day_input'].text.replace("\n", "")
        year_input = workout_ids['year_input'].text.replace("\n", "")

        # Make sure fields aren't garbage
        if self.workout_image == None:
            select_workout_image_label.color = (1, 0, 0, 1)
            return
        # They are allowed to leave no description
        if self.option_choice == None:
            workout_ids['time_label'].color = (1, 0, 0, 1)
            workout_ids['distance_label'].color = (1, 0, 0, 1)
            workout_ids['sets_label'].color = (1, 0, 0, 1)
            return
        try:
            int_quantity = float(quantity_input)
        except:
            workout_ids['quantity_input'].background_color = (1, 0, 0, 1)
            return
        if units_input == "":
            workout_ids['units_input'].background_color = (1, 0, 0, 1)
            return
        try:
            int_month = int(month_input)
            if int_month > 12:
                workout_ids['month_input'].background_color = (1, 0, 0, 1)
                return
        except:
            workout_ids['month_input'].background_color = (1, 0, 0, 1)
            return
        try:
            int_day = int(day_input)
            if int_day > 31:
                workout_ids['day_input'].background_color = (1, 0, 0, 1)
                return
        except:
            workout_ids['day_input'].background_color = (1, 0, 0, 1)
            return
        try:
            if len(year_input) == 2:
                year_input = '20' + year_input
            int_year = int(year_input)
        except:
            workout_ids['year_input'].background_color = (1, 0, 0, 1)
            return

        # If all data is ok, send the data to firebase real-time database
        workout_payload = {
            "workout_image": self.workout_image,
            "description": description_input,
            "likes": 0,
            "number": float(quantity_input),
            "type_image": self.option_choice,
            "units": units_input,
            "date": month_input + "/" + day_input + "/" + year_input
        }
        workout_request = requests.post(
            "https://friendly-fitness.firebaseio.com/%s/workouts.json?auth=%s"
            % (self.local_id, self.id_token),
            data=json.dumps(workout_payload))
        # Add the workout to the banner grid in the home screen
        banner_grid = self.root.ids['home_screen'].ids['banner_grid']
        W = WorkoutBanner(workout_image=self.workout_image,
                          description=description_input,
                          type_image=self.option_choice,
                          number=float(quantity_input),
                          units=units_input,
                          likes="0",
                          date=month_input + "/" + day_input + "/" +
                          year_input)
        banner_grid.add_widget(W, index=len(banner_grid.children))

        # Check if the new workout has made their streak increase
        streak_label = self.root.ids['home_screen'].ids['streak_label']
        result = requests.get("https://friendly-fitness.firebaseio.com/" +
                              self.local_id + ".json?auth=" + self.id_token)
        data = json.loads(result.content.decode())
        workouts = data['workouts']
        streak = helperfunctions.count_workout_streak(workouts)
        if str(streak) == "0":
            streak_label.text = str(streak) + " Day Streak. Go workout!"
        else:
            streak_label.text = str(streak) + " Day Streak!"

        # Go back to the home screen
        self.change_screen("home_screen", direction="backwards")

    def remove_friend(self, friend_id_to_remove, *args):
        # Remove the friend id from the friends list variable
        self.friends_list = self.friends_list.replace(
            ",%s" % friend_id_to_remove, "")

        # Update the firebase database with the new (truncated) friends list
        patch_data = '{"friends": "%s"}' % self.friends_list
        patch_req = requests.patch(
            "https://friendly-fitness.firebaseio.com/%s.json?auth=%s" %
            (self.local_id, self.id_token),
            data=patch_data)

        # Remove the friend banner
        friends_list_grid = self.root.ids['friends_list_screen'].ids[
            'friends_list_grid']
        for w in friends_list_grid.walk():
            if w.__class__ == FriendBanner:
                if w.friend_id == friend_id_to_remove:
                    friends_list_grid.remove_widget(w)

        # Reload the friends list screen

    def load_friend_workout_screen(self, friend_id, widget):
        # Initialize friend streak label to 0
        friend_streak_label = self.root.ids['friend_workout_screen'].ids[
            'friend_streak_label']
        friend_streak_label.text = "0 Day Streak"

        # Make it so we know which friend's workout screen has been loaded for app.set_friend_nickname
        self.their_friend_id = friend_id

        # Get their workouts by using their friend id to query the database
        friend_data_req = requests.get(
            'https://friendly-fitness.firebaseio.com/.json?orderBy="my_friend_id"&equalTo='
            + friend_id)

        friend_data = friend_data_req.json()
        workouts = list(friend_data.values())[0]['workouts']

        friend_banner_grid = self.root.ids['friend_workout_screen'].ids[
            'friend_banner_grid']

        # Remove each widget in the friend_banner_grid
        for w in friend_banner_grid.walk():
            if w.__class__ == WorkoutBanner:
                friend_banner_grid.remove_widget(w)

        # Populate their avatar image
        friend_avatar_image = self.root.ids.friend_workout_screen.ids.friend_workout_screen_image
        friend_avatar_image.source = "icons/avatars/" + list(
            friend_data.values())[0]['avatar']

        # Populate their friend ID and nickname
        print("Need to populate nickname")
        their_friend_id_label = self.root.ids.friend_workout_screen.ids.friend_workout_screen_friend_id
        try:
            nicknames = list(self.nicknames.keys())
        except:
            nicknames = self.nicknames
        if friend_id in nicknames:
            their_friend_id_label.text = "[u]" + self.nicknames[
                friend_id] + "[/u]"
        else:
            their_friend_id_label.text = "[u]Nickname[/u]"

        # Populate the friend_workout_screen
        # Loop through each key in the workouts dictionary
        #    for the value for that key, create a workout banner
        #    add the workout banner to the scrollview
        if workouts == {} or workouts == "":
            # Change to the friend_workout_screen
            self.change_screen("friend_workout_screen")
            return
        workout_keys = list(workouts.keys())
        workout_keys.sort(key=lambda value: datetime.strptime(
            workouts[value]['date'], "%m/%d/%Y"))
        workout_keys = workout_keys[::-1]
        for workout_key in workout_keys:
            workout = workouts[workout_key]
            W = WorkoutBanner(workout_image=workout['workout_image'],
                              description=workout['description'],
                              type_image=workout['type_image'],
                              number=workout['number'],
                              units=workout['units'],
                              likes=workout['likes'],
                              date=workout['date'],
                              likeable=True,
                              workout_key=workout_key)
            friend_banner_grid.add_widget(W)

        # Populate the streak label
        friend_streak_label.text = helperfunctions.count_workout_streak(
            workouts) + " Day Streak"

        # Change to the friend_workout_screen
        self.change_screen("friend_workout_screen")

    def change_screen(self, screen_name, direction='forward', mode=""):
        # Get the screen manager from the kv file
        screen_manager = self.root.ids['screen_manager']
        #print(direction, mode)
        # If going backward, change the transition. Else make it the default
        # Forward/backward between pages made more sense to me than left/right
        if direction == 'forward':
            mode = "push"
            direction = 'left'
        elif direction == 'backwards':
            direction = 'right'
            mode = 'pop'
        elif direction == "None":
            screen_manager.transition = NoTransition()
            screen_manager.current = screen_name
            return

        screen_manager.transition = CardTransition(direction=direction,
                                                   mode=mode)

        screen_manager.current = screen_name
예제 #10
0
class MainApp(App):
    user_id = 1
    category_image = None
    category_image_widget = ''
    previous_category_image_widget = None
    refresh_token_file = "refresh_token.txt"

    def build(self):
        self.my_firebase = MyFirebase()
        return GUI

    def on_start(self):
        try:
            self.get_data()
            # populate add expense category srollview
            self.add_expense_icons()
            # initial screen load of expenses by month on startup
            self.expense_by_month()
            #logged in
            self.on_log_in("connected", NoTransition())

        except Exception:
            print("EXCEPTION")
            traceback.print_exc()
            print("EXCEPTION")
            pass

    def get_data(self):
        with open("refresh_token.txt", 'r') as f:
            refresh_token = f.read()
        id_token, local_id = self.my_firebase.exchange_refresh_token(
            refresh_token)
        self.local_id = local_id
        self.id_token = id_token
        # Get database data
        result = requests.get("https://expensetracker-d3a98.firebaseio.com/" +
                              local_id + ".json?auth=" + id_token)
        self.data = json.loads(result.content.decode())
        # get expenses
        self.expenses = self.data['expenses']
        # get and update user name
        # add budget to settings screen
        user_name = self.root.ids['connected'].ids['main_header']
        user_name.text = self.data[
            'displayname'] + '\'s Expenses'  # for adding user name to banner
        self.root.ids['connected'].ids['settings_screen'].ids[
            'display_id'].hint_text = self.data['displayname']
        self.root.ids['connected'].ids['settings_screen'].ids[
            'budget_id'].hint_text = '$' + str(self.data['budget'])
        # get color scheme
        self.back_col = self.data['colorscheme']['background_color']
        self.bann_col = self.data['colorscheme']['banner_color']
        self.dock_col = self.data['colorscheme']['dock_color']
        self.util_col = self.data['colorscheme']['utility_color']
        # set color scheme
        self.root.ids['connected'].ids['settings_screen'].ids[
            'background_color_id'].col = self.back_col
        self.root.ids['connected'].ids['expense_screen'].ids[
            'background_color_id'].col = self.back_col
        self.root.ids['connected'].ids['category_screen'].ids[
            'background_color_id'].col = self.back_col
        self.root.ids['connected'].ids['add_expense_screen'].ids[
            'background_color_id'].col = self.back_col
        self.root.ids['connected'].ids['banner_color_id'].col = self.bann_col
        self.root.ids['connected'].ids['dock_color_id'].col = self.dock_col
        # set color scheme in settings screen
        self.root.ids['connected'].ids['settings_screen'].ids[
            'background_color_hint_id'].hint_text = self.back_col
        self.root.ids['connected'].ids['settings_screen'].ids[
            'dock_color_hint_id'].hint_text = self.dock_col
        self.root.ids['connected'].ids['settings_screen'].ids[
            'banner_color_hint_id'].hint_text = self.bann_col
        self.root.ids['connected'].ids['settings_screen'].ids[
            'utility_color_hint_id'].hint_text = self.util_col

    def update_color_scheme(self):
        back_col = self.root.ids['connected'].ids['settings_screen'].ids[
            'background_color_hint_id']
        dock_col = self.root.ids['connected'].ids['settings_screen'].ids[
            'dock_color_hint_id']
        bann_col = self.root.ids['connected'].ids['settings_screen'].ids[
            'banner_color_hint_id']
        util_col = self.root.ids['connected'].ids['settings_screen'].ids[
            'utility_color_hint_id']

        background_color = back_col.hint_text
        dock_color = dock_col.hint_text
        banner_color = bann_col.hint_text
        utility_color = util_col.hint_text

        if len(back_col.text) == 6:
            background_color = back_col.text.upper()

        if len(dock_col.text) == 6:
            dock_color = dock_col.text.upper()

        if len(bann_col.text) == 6:
            banner_color = bann_col.text.upper()

        if len(util_col.text) == 6:
            utility_color = util_col.text.upper()

        patch_data = '{"colorscheme": {"background_color": "%s", "banner_color": "%s", "dock_color": "%s", "utility_color": "%s"}}' % (
            background_color, banner_color, dock_color, utility_color)
        patch_req = requests.patch(
            "https://expensetracker-d3a98.firebaseio.com/%s.json?auth=%s" %
            (self.local_id, self.id_token),
            data=patch_data)

        back_col.hint_text = background_color
        dock_col.hint_text = dock_color
        bann_col.hint_text = banner_color
        util_col.hint_text = utility_color

        back_col.text = ''
        dock_col.text = ''
        bann_col.text = ''
        util_col.text = ''

        self.on_start()

    def update_budget(self, *args):
        targetbudget = self.root.ids['connected'].ids['settings_screen'].ids[
            'budget_id']
        if targetbudget.text != "":
            patch_data = '{"budget": %s}' % int(targetbudget.text)
            patch_req = requests.patch(
                "https://expensetracker-d3a98.firebaseio.com/%s.json?auth=%s" %
                (self.local_id, self.id_token),
                data=patch_data)
            targetbudget.hint_text = '$' + targetbudget.text
        else:
            targetbudget.text = '0'
            patch_data = '{"budget": %s}' % int(targetbudget.text)
            patch_req = requests.patch(
                "https://expensetracker-d3a98.firebaseio.com/%s.json?auth=%s" %
                (self.local_id, self.id_token),
                data=patch_data)
            targetbudget.hint_text = '$0'
        targetbudget.text = ''

    def update_display_name(self, *args):
        change_name = self.root.ids['connected'].ids['settings_screen'].ids[
            'display_id']
        if change_name.text != "":
            patch_data = '{"displayname": "%s"}' % change_name.text
            patch_req = requests.patch(
                "https://expensetracker-d3a98.firebaseio.com/%s.json?auth=%s" %
                (self.local_id, self.id_token),
                data=patch_data)
            user_name = self.root.ids['connected'].ids['main_header']
            user_name.text = change_name.text + '\'s Expenses'
            change_name.hint_text = change_name.text
            change_name.text = ''

    def expense_by_month(self):
        result = requests.get("https://expensetracker-d3a98.firebaseio.com/" +
                              self.local_id + ".json?auth=" + self.id_token)
        data = json.loads(result.content.decode())
        expense_months = self.root.ids['connected'].ids['expense_screen'].ids[
            'expense_months']

        if len(expense_months.slides):
            expense_months.index = 0
            expense_months.clear_widgets()

        months = data['expenses']
        if months != "":
            for month in months:
                N = ExpenseByMonth(month, data)
                expense_months.add_widget(N)
            expense_months.load_slide(N)

    def expense_by_category(self):
        result = requests.get("https://expensetracker-d3a98.firebaseio.com/" +
                              self.local_id + ".json?auth=" + self.id_token)
        data = json.loads(result.content.decode())
        expense_category = self.root.ids['connected'].ids[
            'category_screen'].ids['expense_categories']

        if len(expense_category.slides):
            expense_category.index = 0
            expense_category.clear_widgets()

        months = data['expenses']
        if months != "":
            for month in months:
                N = ExpenseByCategory(month, data)
                expense_category.add_widget(N)
            expense_category.load_slide(N)

    def add_expense_icons(self):
        category_image_grid = self.root.ids['connected'].ids[
            'add_expense_screen'].ids['add_category_grid']
        for root_dir, folders, files in walk("icons/expenses"):
            for f in files:
                if 'dark' not in f:
                    img = ImageButton(source="icons/expenses/" + f,
                                      id=f[:-4] + '_id',
                                      on_release=partial(
                                          self.button_pressed, f))
                    category_image_grid.add_widget(img)

    def add_expense(self):
        today = datetime.today()
        months = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
        days = [
            1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
            19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
        ]
        years = [
            20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
            37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
            54, 55, 56, 57, 58, 59, 60
        ]
        # get date of expense occurance
        expense_ids = self.root.ids['connected'].ids['add_expense_screen'].ids
        price_input = expense_ids['add_price_id'].text
        month_input = expense_ids['month_input_id'].text
        day_input = expense_ids['day_input_id'].text
        year_input = expense_ids['year_input_id'].text

        if self.category_image == None:
            select_category_image_label = self.root.ids[
                'connected'].ids.add_expense_screen.ids.select_category_image_label
            select_category_image_label.color = (1, 0, 0, 1)
            return
        # if price not integer return error
        if price_input == "":
            expense_ids['add_price_id'].background_color = (.8, 0, 0, 1)
            return
        try:
            float_price = float(price_input)
        except:
            expense_ids['add_price_id'].background_color = (.8, 0, 0, 1)
            return
        if month_input != '':
            try:
                int_month = int(month_input)
            except:
                expense_ids['month_input_id'].background_color = (.8, 0, 0, 1)
                return
        else:
            month_input = str(today.month).zfill(2)

        if day_input != '':
            try:
                int_day = int(day_input)
            except:
                expense_ids['day_input_id'].background_color = (.8, 0, 0, 1)
                return
        else:
            day_input = str(today.day).zfill(2)

        if year_input != '':
            try:
                int_year = int(year_input)
            except:
                expense_ids['year_input_id'].background_color = (.8, 0, 0, 1)
                return
        else:
            year_input = str(today.year)[2:]

        #check if valid month/date/year and zill(2)
        if int(month_input) not in months:
            expense_ids['month_input_id'].background_color = (.8, 0, 0, 1)
            return
        else:
            month_input = month_input.zfill(2)

        if int(day_input) not in days:
            expense_ids['day_input_id'].background_color = (.8, 0, 0, 1)
            return
        else:
            day_input = day_input.zfill(2)

        if int(year_input) not in years:
            expense_ids['year_input_id'].background_color = (.8, 0, 0, 1)
            return

        month = '20' + year_input + '-' + month_input

        # add expense to firebase
        price_post = float(price_input)
        date_post = int('20' + year_input + month_input + day_input)
        expense_payload = {
            "category": self.category_image,
            "price": price_post,
            "date": date_post
        }
        expense_request = requests.post(
            "https://expensetracker-d3a98.firebaseio.com/%s/expenses/%s.json?auth=%s"
            % (self.local_id, month, self.id_token),
            data=json.dumps(expense_payload))

        #clear data
        self.root.ids['connected'].ids['add_expense_screen'].ids[
            'add_price_id'].text = ''
        self.root.ids['connected'].ids['add_expense_screen'].ids[
            'month_input_id'].text = ''
        self.root.ids['connected'].ids['add_expense_screen'].ids[
            'day_input_id'].text = ''
        self.root.ids['connected'].ids['add_expense_screen'].ids[
            'year_input_id'].text = ''
        self.root.ids['connected'].ids['add_expense_screen'].ids[
            'add_expense_id'].text = 'Expense Added'
        self.category_image_widget.canvas.before.clear()
        self.category_image = None

    def change_screen(self, screen_name, screen_transition):
        # Get the screen manager from the kv file
        screen_manager = self.root.ids['connected'].ids['screen_manager']
        screen_manager.transition = screen_transition
        screen_manager.current = screen_name

    def on_log_in(self, screen_name, screen_transition):
        screen_manager = self.root.ids['screen_manager']
        screen_manager.transition = screen_transition
        screen_manager.current = screen_name

    def clear_expense(self):
        self.root.ids['connected'].ids['add_expense_screen'].ids[
            'add_expense_id'].text = ''

    def button_pressed(self, button_name, widget_id):
        self.previous_category_image_widget = self.category_image_widget
        self.category_image = button_name[:-4].title()
        self.category_image_widget = widget_id

        if self.previous_category_image_widget:
            self.previous_category_image_widget.canvas.before.clear()

        select_category_image_label = self.root.ids.connected.ids.add_expense_screen.ids.select_category_image_label
        select_category_image_label.color = (1, 1, 1, 1)

        with self.category_image_widget.canvas.before:
            Color(rgb=(kivy.utils.get_color_from_hex("#6C5B7B")))
            RoundedRectangle(size=self.category_image_widget.size,
                             pos=self.category_image_widget.pos,
                             radius=[
                                 15,
                             ])

    def log_out(self):
        with open(self.refresh_token_file, 'w') as f:
            f.write("")
        self.on_log_in("login_screen",
                       SlideTransition(direction='down', duration=.15))
        self.root.ids.login_screen.ids.login_email.text = ""
        self.root.ids.login_screen.ids.login_password.text = ""
예제 #11
0
class MainApp(App):
    refresh_token_file = "refresh_token.txt"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def build(self):
        self.my_firebase = MyFirebase()
        return GUI

    def on_start(self):
        # Populate change avatar grid
        avatar_grid = self.root.ids['change_avatar_screen'].ids['avatar_grid']
        for root_dir, folders, png in walk("resources/avatars"):
            for p in png:
                img = ImageButton(source="resources/avatars/" + p,
                                  on_release=partial(self.change_avatar, p))
                avatar_grid.add_widget(img)

        # Get available drivers database
        all_data_request = requests.get(
            f'https://sube-y-baja-app.firebaseio.com/available_drivers.json')
        drivers = json.loads(all_data_request.content.decode())
        # Available Drivers
        # Get and update available drivers banner
        available_driver_banner = self.root.ids["main_passenger"].ids[
            "banner_grid"]
        for driver in drivers:
            current = drivers[driver]
            banner = DriversBanner(name=current['name'],
                                   last_name=current['last_name'],
                                   leave_hour=current['leave_hour'],
                                   desde=current['from'],
                                   to=current['to'],
                                   cel=current['cel'],
                                   plate=current['plate'],
                                   avatar=current['avatar'])
            available_driver_banner.add_widget(banner)

        # Get available passenger database
        available_passenger_request = requests.get(
            f'https://sube-y-baja-app.firebaseio.com/available_passenger.json')
        passengers = json.loads(available_passenger_request.content.decode())
        # Available Passenger
        # Get and update available passenger banner
        available_passenger_banner = self.root.ids["driver_screen"].ids[
            "passenger_available_grid"]
        for passenger in passengers:
            current = passengers[passenger]
            banner = PassengerBanner(name=current['name'],
                                     last_name=current['last_name'],
                                     leave_hour=current['hour'],
                                     desde=current['from'],
                                     to=current['to'],
                                     cel=current['cel'],
                                     avatar=current['avatar'])
            available_passenger_banner.add_widget(banner)

        try:
            # Try to read the persisten signing credentials (refresh token)
            with open("refresh_token.txt", 'r') as f:
                refresh_token = f.read()
            # Use refresh token to get a new idToken
            self.id_token, self.local_id = self.my_firebase.exchange_refresh_token(
                refresh_token)

            # Get database data
            result = requests.get(
                f'https://sube-y-baja-app.firebaseio.com/Users/{self.local_id}.json?auth={self.id_token}'
            )
            data = json.loads(result.content.decode())
            # Feature of User
            self.user_name = data["name"]
            self.last_name = data["last_name"]
            self.email = data["email"]
            self.cel = data["cel"]
            self.avatar = data["avatar"]
            self.plate = data["plate"]
            # Get and update account settings
            account_settings_id = self.root.ids["account_settings"].ids
            avatar_setting = account_settings_id["avatar_setting"]
            avatar_setting.source = f'resources/avatars/{self.avatar}'
            name_setting = account_settings_id["name"]
            name_setting.text = f'{self.user_name} {self.last_name}\n' \
                                f'{self.email}'
            cel_settings = account_settings_id["cel"]
            cel_settings.text = str(self.cel)
            # pass_settings = self.root.ids["account_settings"].ids["password"]

            self.root.ids["screen_manager"].transition = NoTransition()
            self.change_screen("main_passenger")
            self.root.ids["screen_manager"].transition = CardTransition()

        except:
            pass

    def change_avatar(self, image, widget_id):
        # Change avatar in the app
        avatar_setting = self.root.ids["account_settings"].ids[
            "avatar_setting"]
        avatar_setting.source = f'resources/avatars/{image}'
        # Change avatar in firebase database
        my_data = '{"avatar": "%s" }' % image
        requests.patch(
            f'https://sube-y-baja-app.firebaseio.com/Users/{self.local_id}.json?auth={self.id_token}',
            data=my_data)
        self.change_screen("account_settings")

    def add_request(self):
        # Get all data of fields of add_request Screen
        requests_ids = self.root.ids["add_request"].ids
        desde_input = requests_ids["desde"].text
        para_input = requests_ids["para"].text
        hora_input = requests_ids["hora"].text
        n_passenger_input = requests_ids["n_passenger"].text
        # Make sure fields aren't garbage
        if desde_input == "":
            requests_ids["desde"].background_color = (1, 0, 0, 1)
            return
        if para_input == "":
            requests_ids["para"].background_color = (1, 0, 0, 1)
            return
        if hora_input == "":
            requests_ids["hora"].background_color = (1, 0, 0, 1)
            return
        try:
            int_n_passenger = int(n_passenger_input)
        except:
            requests_ids["n_passenger"].background_color = (1, 0, 0, 1)
            return

        # If all data is ok, send data to firebase real-time database
        request_payload = {
            "n_pasajeros": n_passenger_input,
            "avatar": self.avatar,
            "cel": self.cel,
            "from": desde_input,
            "last_name": self.last_name,
            "hour": hora_input,
            "name": self.user_name,
            "to": para_input
        }
        request_request = requests.post(
            "https://sube-y-baja-app.firebaseio.com/available_passenger.json",
            data=json.dumps(request_payload))

    def add_available_driver(self):
        # Get all data of fields of add_request Screen
        requests_ids = self.root.ids["add_available_driver"].ids
        desde_input = requests_ids["desde"].text
        para_input = requests_ids["para"].text
        hora_input = requests_ids["hora"].text
        available_seats = requests_ids["available_seats"].text
        # Make sure fields aren't garbage
        if desde_input == "":
            requests_ids["desde"].background_color = (1, 0, 0, 1)
            return
        if para_input == "":
            requests_ids["para"].background_color = (1, 0, 0, 1)
            return
        if hora_input == "":
            requests_ids["hora"].background_color = (1, 0, 0, 1)
            return
        try:
            int_available_seats = int(available_seats)
        except:
            requests_ids["available_seats"].background_color = (1, 0, 0, 1)
            return

        # If all data is ok, send data to firebase real-time database
        request_payload = {
            "available_seats": available_seats,
            "avatar": self.avatar,
            "cel": self.cel,
            "from": desde_input,
            "last_name": self.last_name,
            "leave_hour": hora_input,
            "name": self.user_name,
            "to": para_input,
            "plate": self.plate
        }
        request_request = requests.post(
            "https://sube-y-baja-app.firebaseio.com/available_drivers.json",
            data=json.dumps(request_payload))

    def sign_out_user(self):
        # User wants to log out
        with open(self.refresh_token_file, "w") as f:
            f.write("")
        self.change_screen("login_screen", direction='down', mode='push')
        # Need to set the avatar to the default image
        avatar_setting = self.root.ids["account_settings"].ids[
            "avatar_setting"]
        avatar_setting.source = "resources/avatars/man.png"

        # Need to clear widgets from previous user's drivers available
        driver_available_banner = self.root.ids['main_passenger'].ids[
            'banner_grid']
        passenger_available_banner = self.root.ids['driver_screen'].ids[
            'passenger_available_grid']
        for w in driver_available_banner.walk():
            if w.__class__ == DriversBanner:
                driver_available_banner.remove_widget(w)

        # Need to clear widgets from previous user's friend's passenger available
        passenger_available_banner = self.root.ids['driver_screen'].ids[
            'passenger_available_grid']
        for w in passenger_available_banner.walk():
            if w.__class__ == PassengerBanner:
                passenger_available_banner.remove_widget(w)

    def load_info_driver_available(self, widget):
        # Get available drivers database
        info_driver_request = requests.get(
            f'https://sube-y-baja-app.firebaseio.com/available_drivers/shano.json'
        )
        info_driver = json.loads(info_driver_request.content.decode())
        # Available Drivers
        # Get and update available drivers banner
        available_driver_banner = self.root.ids["info_trip"].ids[
            "driver_banner"]
        banner = InfoDriversBanner(name=info_driver['name'],
                                   last_name=info_driver['last_name'],
                                   leave_hour=info_driver['leave_hour'],
                                   desde=info_driver['from'],
                                   to=info_driver['to'],
                                   cel=info_driver['cel'],
                                   plate=info_driver['plate'],
                                   avatar=info_driver['avatar'])
        available_driver_banner.add_widget(banner)

        self.change_screen("info_trip")

    def change_screen(self, screen_name, direction='forward', mode=""):
        # Get the screen manager from the kv file
        screen_manager = self.root.ids['screen_manager']
        # print(direction, mode)
        # If going backward, change the transition. Else make it the default
        # Forward/backward between pages made more sense to me than left/right
        if direction == 'forward':
            mode = "push"
            direction = 'left'
        elif direction == 'backwards':
            direction = 'right'
            mode = 'pop'
        elif direction == "None":
            screen_manager.transition = NoTransition()
            screen_manager.current = screen_name
            return

        screen_manager.transition = CardTransition(direction=direction,
                                                   mode=mode)

        screen_manager.current = screen_name
class MainApp(App):
    my_friend_id = ""
    popupWindow = Popup()
    popup_message = ""
    status_popup = ""
    workout_image = None
    workout_image_widget = ""
    option_choice = None
    nicknames = DictProperty()
    their_friend_id = ""

    def build(self):
        self.my_firebase = MyFirebase()
        return GUI

    def set_friend_nickname(self, nickname, *args):
        # Make sure they entered something
        if nickname == "":
            return
        # Set the nickname
        print("YO", self.their_friend_id, type(self.their_friend_id))
        print(self.nicknames)
        self.nicknames[int(self.their_friend_id)] = nickname

        # Update firebase
        print(self.nicknames)
        print(json.dumps(self.nicknames))
        workout_request = requests.patch(
            "https://fitnessapp-kivy.firebaseio.com/%s/nicknames.json?auth=%s"
            % (self.local_id, self.id_token),
            data=json.dumps(self.nicknames))
        print(workout_request.content)
        # Update the nickname in the friend_workout_screen
        their_friend_id_label = self.root.ids.friend_workout_screen.ids.friend_workout_screen_friend_id
        their_friend_id_label.text = "[u]" + nickname + "[/u]"

        # Update the nickname in the friend workout banner
        # Go through each widget in the friends list grid
        for w in self.root.ids['friends_list_screen'].ids[
                'friends_list_grid'].walk():
            if w.__class__ == FriendBanner:
                if w.friend_id == self.their_friend_id:
                    w.update_friend_label_text(their_friend_id_label.text)

    def on_start(self):
        # Choose the correct time icon to show based on the current hour of day
        now = datetime.now()
        hour = now.hour
        if hour <= 6:
            self.root.ids['time_indicator1'].opacity = 1
        elif hour <= 12:
            self.root.ids['time_indicator2'].opacity = 1
        elif hour <= 18:
            self.root.ids['time_indicator3'].opacity = 1
        else:
            self.root.ids['time_indicator4'].opacity = 1

        # Set the current day, month, and year in the add workout section
        day, month, year = now.day, now.month, now.year
        self.root.ids.add_workout_screen.ids.month_input.text = str(month)
        self.root.ids.add_workout_screen.ids.day_input.text = str(day)
        self.root.ids.add_workout_screen.ids.year_input.text = str(year)

        # Populate avatar grid
        avatar_grid = self.root.ids['change_avatar_screen'].ids['avatar_grid']
        for root_dir, folders, files in walk("icons/avatars"):
            for f in files:
                img = ImageButton(source="icons/avatars/" + f,
                                  on_release=partial(self.change_avatar, f))
                avatar_grid.add_widget(img)

        # Populate workout image grid
        workout_image_grid = self.root.ids['add_workout_screen'].ids[
            'workout_image_grid']
        for root_dir, folders, files in walk("icons/workouts"):
            for f in files:
                img = ImageButton(source="icons/workouts/" + f,
                                  on_release=partial(self.update_workout_image,
                                                     f))
                workout_image_grid.add_widget(img)

        try:
            # Try to read the persisten signin credentials (refresh token)
            with open("refresh_token.txt", "r") as f:
                refresh_token = f.read()

            # use refresh_token to get a new idToken
            self.id_token, self.local_id = self.my_firebase.exchange_refresh_token(
                refresh_token)

            # Get database data
            result = requests.get("https://fitnessapp-kivy.firebaseio.com/" +
                                  self.local_id + ".json?auth=" +
                                  self.id_token)
            data = json.loads(result.content.decode())

            # Update avatar image
            avatar_image = self.root.ids['avatar_image']
            avatar_image.source = "icons/avatars/" + data['avatar']

            # Update streak label
            label_streak = self.root.ids['home_screen'].ids['streak_label']

            # Friend List
            self.friends_list = data['friends']

            # Get nicknames
            try:
                print(data['nicknames'])
                for i, friend_id in enumerate(self.friends_list.split(",")):
                    if friend_id:
                        print(i, friend_id)
                        self.nicknames[friend_id] = data['nicknames'][i]
            except:
                self.nicknames = data.get('nicknames', {})

            # Populate friends list grid
            friends_list_array = self.friends_list.split(",")
            for friend_id in friends_list_array:
                friend_id = friend_id.replace(" ", "")
                if friend_id == "":
                    continue
                try:
                    nicknames = list(self.friends_list.keys())
                except:
                    nicknames = self.nicknames
                if friend_id in nicknames:
                    friend_id_text = "[u]" + self.nicknames[friend_id] + "[/u]"
                else:
                    friend_id_text = "[u]Friend ID: " + friend_id + "[/u]"
                friend_banner = FriendBanner(friend_id=friend_id,
                                             friend_id_text=friend_id_text)
                self.root.ids['friends_list_screen'].ids[
                    'friends_list_grid'].add_widget(friend_banner)

            # Update id label
            self.my_friend_id = data['my_friend_id']
            friend_id_label = self.root.ids['settings_screen'].ids[
                'friend_id_label']
            friend_id_label.text = "ID: " + str(data['my_friend_id'])

            # Get data workouts
            banner_grid = self.root.ids['home_screen'].ids['banner_grid']
            workouts = data['workouts']
            if workouts != "":
                workout_keys = list(workouts.keys())
                streak = helperfunctions.count_workout_streak(workouts)
                if str(streak) == "0":
                    label_streak.text = "[b]0 Hari berturut-turut, latihan sekarang![/b]"
                else:
                    label_streak.text = "[b]" + str(
                        streak) + " Hari berturut-turut[/b]"
                # Sort workouts by date then reverse (we want youngest dates at the start)
                workout_keys.sort(key=lambda value: datetime.strptime(
                    workouts[value]['date'], "%m/%d/%Y"))
                workout_keys = workout_keys[::-1]
                for workout_key in workout_keys:
                    workout = workouts[workout_key]
                    # Populate workout grid in home screen
                    W = WorkoutsBanner(workout_image=workout['workout_image'],
                                       description=workout['description'],
                                       type_image=workout['type_image'],
                                       number=float(workout['number']),
                                       units=workout['units'],
                                       likes=workout['likes'],
                                       date=workout['date'])
                    banner_grid.add_widget(W)

            self.change_screen("home_screen", "none")
        except Exception as e:
            print(e)
            pass

    def add_friend(self, friend_id):
        friend_id = friend_id.replace("\n", "")
        # Make sure friend id was a number otherwise it's invalid
        try:
            int_friend_id = int(friend_id)
        except:
            # Friend id had some letters in it when it should just be a number
            self.show_popup("ID harus berupa angka", "number_only")
            return
        # Make sure they aren't adding themselves
        if friend_id == self.my_friend_id:
            self.show_popup(
                "Maaf, anda tidak dapat menambahkan ID anda sendiri", "own_id")
            return

        # Make sure this is not someone already in their friends list
        if friend_id in self.friends_list.split(","):
            self.show_popup("Teman dengan ID " + friend_id + " sudah ada",
                            "duplicated")
            return

        # Query database and make sure friend_id exists
        check_req = requests.get(
            'https://fitnessapp-kivy.firebaseio.com/.json?orderBy="my_friend_id"&equalTo="'
            + friend_id + '"')
        data = check_req.json()

        if data == {}:
            # If it doesn't, display it doesn't in the message on the add friend screen
            self.show_popup("ID teman tidak ditemukan", "not_found")
        else:
            # Requested friend ID exists
            key = list(data.keys())[0]
            # new_friend_id = data[key]['my_friend_id']

            # Add friend id to friends list and patch new friends list
            self.friends_list += ",%s" % friend_id
            patch_data = '{"friends": "%s"}' % self.friends_list
            patch_req = requests.patch(
                "https://fitnessapp-kivy.firebaseio.com/" + self.local_id +
                ".json?auth=" + self.id_token,
                data=patch_data)
            if patch_req.ok == True:
                self.show_popup(
                    "Teman dengan ID " + friend_id + " berhasil ditambahkan",
                    "friend_added")
                self.root.ids['add_friend_screen'].ids[
                    'add_friend_input'].text = ""
            else:
                self.show_popup("Maaf, ada kesalahan pada sistem",
                                "error_adding")

            # Add new friend banner in friends list screen
            if friend_id in self.nicknames.keys():
                friend_id_text = "[u]" + self.nicknames[friend_id] + "[/u]"
            else:
                friend_id_text = "[u]Friend ID: " + friend_id + "[/u]"
            friend_banner = FriendBanner(friend_id=friend_id,
                                         friend_id_text=friend_id_text)
            self.root.ids['friends_list_screen'].ids[
                'friends_list_grid'].add_widget(friend_banner)

    def change_avatar(self, image, widget_id):
        # Change avatar in app
        avatar_image = self.root.ids['avatar_image']
        avatar_image.source = "icons/avatars/" + image

        # Change avatar in firebase
        my_avatar = '{"avatar": "%s"}' % image
        change_avatar_req = requests.patch(
            "https://fitnessapp-kivy.firebaseio.com/" + self.local_id +
            ".json?auth=" + self.id_token,
            data=my_avatar)
        if change_avatar_req.ok == True:
            self.show_popup("Foto profil berhasil di ganti", "avatar_changed")
        else:
            self.show_popup("Maaf, ada kesalahan pada sistem",
                            "error_change_avatar")

    def update_workout_image(self, filename, widget_id):
        self.workout_image = filename

    def add_workout(self):
        # Get data from all fields in add workout screen
        workout_ids = self.root.ids['add_workout_screen'].ids
        description_input = workout_ids['description_input'].text
        quantity_input = workout_ids['quantity_input'].text
        units_input = workout_ids['units_input'].text
        day_input = workout_ids['day_input'].text
        month_input = workout_ids['month_input'].text
        year_input = workout_ids['year_input'].text
        if self.workout_image == None:
            self.show_popup("Silahkan pilih gambar latihan!",
                            "workout_image_none")
        elif self.option_choice == None:
            self.show_popup("Silahkan pilih jenis perhitungan!",
                            "no_option_choice")
            workout_ids['time_label'].color = (1, 0, 0, 1)
            workout_ids['distance_label'].color = (1, 0, 0, 1)
            workout_ids['sets_label'].color = (1, 0, 0, 1)
        elif quantity_input == "":
            self.show_popup("Silahkan isi jumlah!", "quantity_none")
            workout_ids['quantity_input'].background_color = (1, 0, 0, 1)
        elif quantity_input != "":
            try:
                int_quantity = float(quantity_input)
                if units_input == "":
                    self.show_popup("Silahkan isi satuan!", "units_none")
                    workout_ids['units_input'].background_color = (1, 0, 0, 1)
                elif day_input == "":
                    self.show_popup("Silahkan isi hari!", "day_none")
                    workout_ids['day_input'].background_color = (1, 0, 0, 1)
                elif day_input != "":
                    try:
                        int_day = int(day_input)
                        if month_input == "":
                            self.show_popup("Silahkan isi bulan!",
                                            "month_none")
                            workout_ids['month_input'].background_color = (1,
                                                                           0,
                                                                           0,
                                                                           1)
                        elif month_input != "":
                            try:
                                int_month = int(month_input)
                                if year_input == "":
                                    self.show_popup("Silahkan isi tahun!",
                                                    "year_none")
                                    workout_ids[
                                        'year_input'].background_color = (1, 0,
                                                                          0, 1)
                                elif year_input != "":
                                    try:
                                        int_year = int(year_input)
                                        workout_payload = {
                                            "workout_image":
                                            self.workout_image,
                                            "description":
                                            description_input,
                                            "likes":
                                            0,
                                            "number":
                                            int_quantity,
                                            "type_image":
                                            self.option_choice,
                                            "units":
                                            units_input,
                                            "date":
                                            month_input + "/" + day_input +
                                            "/" + year_input
                                        }
                                        workout_request = requests.post(
                                            "https://fitnessapp-kivy.firebaseio.com/"
                                            + self.local_id +
                                            "/workouts.json?auth=" +
                                            self.id_token,
                                            data=json.dumps(workout_payload))
                                        # Add the workout to the banner grid in the home screen
                                        banner_grid = self.root.ids[
                                            'home_screen'].ids['banner_grid']
                                        W = WorkoutsBanner(
                                            workout_image=self.workout_image,
                                            description=description_input,
                                            type_image=self.option_choice,
                                            number=float(quantity_input),
                                            units=units_input,
                                            likes="0",
                                            date=month_input + "/" +
                                            day_input + "/" + year_input)
                                        banner_grid.add_widget(
                                            W, index=len(banner_grid.children))

                                        # Check if the new workout has made their streak increase
                                        streak_label = self.root.ids[
                                            'home_screen'].ids['streak_label']
                                        result = requests.get(
                                            "https://fitnessapp-kivy.firebaseio.com/"
                                            + self.local_id + ".json?auth=" +
                                            self.id_token)
                                        data = json.loads(
                                            result.content.decode())
                                        workouts = data['workouts']
                                        streak = helperfunctions.count_workout_streak(
                                            workouts)
                                        if str(streak) == "0":
                                            streak_label.text = "[b]0 Hari berturut-turut, latihan sekarang![/b]"
                                        else:
                                            streak_label.text = "[b]" + str(
                                                streak
                                            ) + " Hari berturut-turut[/b]"

                                        self.show_popup(
                                            "Berhasil menambah data latihan",
                                            "workout_added")
                                    except:
                                        self.show_popup(
                                            "Tahun harus berupa angka!",
                                            "year_not_int")
                                        workout_ids[
                                            'year_input'].background_color = (
                                                1, 0, 0, 1)
                                        return
                            except:
                                self.show_popup("Bulan harus berupa angka!",
                                                "month_not_int")
                                workout_ids['month_input'].background_color = (
                                    1, 0, 0, 1)
                                return
                    except:
                        self.show_popup("Hari harus berupa angka!",
                                        "day_not_int")
                        workout_ids['day_input'].background_color = (1, 0, 0,
                                                                     1)
                        return
            except:
                self.show_popup("Jumlah harus berupa angka!",
                                "quantity_not_int")
                workout_ids['quantity_input'].background_color = (1, 0, 0, 1)
                return

    def remove_friend(self, friend_id_to_remove, *args):
        # Remove the friend id from the friends list variable
        self.friends_list = self.friends_list.replace(
            ",%s" % friend_id_to_remove, "")

        # Update the firebase database with the new (truncated) friends list
        patch_data = '{"friends": "%s"}' % self.friends_list
        patch_req = requests.patch(
            "https://fitnessapp-kivy.firebaseio.com/%s.json?auth=%s" %
            (self.local_id, self.id_token),
            data=patch_data)

        # Remove the friend banner
        friends_list_grid = self.root.ids['friends_list_screen'].ids[
            'friends_list_grid']
        for w in friends_list_grid.walk():
            if w.__class__ == FriendBanner:
                if w.friend_id == friend_id_to_remove:
                    friends_list_grid.remove_widget(w)

        # Reload the friends list screen
        self.show_popup("Teman berhasil di hapus", "deleted_friend")

    def load_friend_workout_screen(self, friend_id, widget):
        # Initialize friend streak label to 0
        friend_streak_label = self.root.ids['friend_workout_screen'].ids[
            'friend_streak_label']
        friend_streak_label.text = "0 Hari Berturut-turut"

        # Make it so we know which friend's workout screen has been loaded for app.set_friend_nickname
        self.their_friend_id = friend_id

        # Get their workouts by using their friend id to query the database
        friend_data_req = requests.get(
            'https://fitnessapp-kivy.firebaseio.com/.json?orderBy="my_friend_id"&equalTo="'
            + friend_id + '"')

        friend_data = friend_data_req.json()
        workouts = list(friend_data.values())[0]['workouts']

        friend_banner_grid = self.root.ids['friend_workout_screen'].ids[
            'friend_banner_grid']

        # Remove each widget in the friend_banner_grid
        for w in friend_banner_grid.walk():
            if w.__class__ == WorkoutsBanner:
                friend_banner_grid.remove_widget(w)

        # Populate their avatar image
        friend_avatar_image = self.root.ids.friend_workout_screen.ids.friend_workout_screen_image
        friend_avatar_image.source = "icons/avatars/" + list(
            friend_data.values())[0]['avatar']

        # Populate their friend ID and nickname
        print("Need to populate nickname")
        their_friend_id_label = self.root.ids.friend_workout_screen.ids.friend_workout_screen_friend_id
        try:
            nicknames = list(self.nicknames.keys())
        except:
            nicknames = self.nicknames
        if friend_id in nicknames:
            their_friend_id_label.text = "[u]" + self.nicknames[
                friend_id] + "[/u]"
        else:
            their_friend_id_label.text = "[u]Nama Panggilan[/u]"

        # Populate the friend_workout_screen
        # Loop through each key in the workouts dictionary
        #    for the value for that key, create a workout banner
        #    add the workout banner to the scrollview
        if workouts == {} or workouts == "":
            # Change to the friend_workout_screen
            self.change_screen("friend_workout_screen", "slide")
            return
        workout_keys = list(workouts.keys())
        workout_keys.sort(key=lambda value: datetime.strptime(
            workouts[value]['date'], "%m/%d/%Y"))
        workout_keys = workout_keys[::-1]
        for workout_key in workout_keys:
            workout = workouts[workout_key]
            W = WorkoutsBanner(workout_image=workout['workout_image'],
                               description=workout['description'],
                               type_image=workout['type_image'],
                               number=workout['number'],
                               units=workout['units'],
                               likes=workout['likes'],
                               date=workout['date'],
                               likeable=True,
                               workout_key=workout_key)
            friend_banner_grid.add_widget(W)

        # Populate the streak label
        friend_streak_label.text = helperfunctions.count_workout_streak(
            workouts) + " Hari Berturut-turut"

        # Change to the friend_workout_screen
        self.change_screen("friend_workout_screen", "slide")

    def change_screen(self, screen_name, transition):
        screen_manager = self.root.ids['screen_manager']

        # Transition
        if transition == "wipe":
            screen_manager.transition = WipeTransition()
        elif transition == "swap":
            screen_manager.transition = SwapTransition()
        elif transition == "slide":
            screen_manager.transition = SlideTransition()
        elif transition == "none":
            screen_manager.transition = NoTransition()
        elif transition == "card":
            screen_manager.transition = CardTransition()

        screen_manager.current = screen_name

    def show_popup(self, message, status):
        self.popup_message = message

        show = Popups()

        self.status_popup = status

        self.popupWindow = Popup(title="Perhatian !",
                                 content=show,
                                 size_hint=(None, None),
                                 size=(200, 200),
                                 auto_dismiss=False)
        self.popupWindow.open()

        self.popup_message = ""

    def dismiss_popup(self):
        if self.status_popup == "registered":
            self.popupWindow.dismiss()
            self.change_screen("login_screen", "wipe")

            self.root.ids["login_screen"].ids["login_email"].text = ""
            self.root.ids["login_screen"].ids["login_password"].text = ""
            self.root.ids["register_screen"].ids["register_email"].text = ""
            self.root.ids["register_screen"].ids["register_password"].text = ""
        elif self.status_popup == "avatar_changed":
            self.popupWindow.dismiss()
            self.change_screen("settings_screen", "swap")

            self.root.ids["login_screen"].ids["login_email"].text = ""
            self.root.ids["login_screen"].ids["login_password"].text = ""
            self.root.ids["register_screen"].ids["register_email"].text = ""
            self.root.ids["register_screen"].ids["register_password"].text = ""
        elif self.status_popup == "workout_added":
            self.popupWindow.dismiss()
            self.change_screen("home_screen", "card")

            self.root.ids["login_screen"].ids["login_email"].text = ""
            self.root.ids["login_screen"].ids["login_password"].text = ""
            self.root.ids["register_screen"].ids["register_email"].text = ""
            self.root.ids["register_screen"].ids["register_password"].text = ""
        else:
            self.popupWindow.dismiss()

        self.status_popup = ""

    def logout(self):
        # User wants to log out
        with open("refresh_token.txt", 'w') as f:
            f.write("")
        self.change_screen("login_screen", "slide")
        # Need to set the avatar to the default image
        avatar_image = self.root.ids['avatar_image']
        avatar_image.source = "icons/avatars/man.png"

        add_friend_screen = self.root.ids.add_friend_screen
        add_friend_screen.ids.add_friend_input.text = ""

        # Clear home screen
        self.root.ids.home_screen.ids.streak_label.text = "0 Hari berturut-turut, latihan sekarang!"

        # Clear login screen
        self.root.ids.login_screen.ids.login_email.text = ""
        self.root.ids.login_screen.ids.login_password.text = ""

        self.workout_image = None
        self.option_choice = None
        # Clear the indication that the previous image was selected
        if self.workout_image_widget:
            self.workout_image_widget.canvas.before.clear()

        # Need to clear widgets from previous user's friends list
        friends_list_grid = self.root.ids['friends_list_screen'].ids[
            'friends_list_grid']
        for w in friends_list_grid.walk():
            if w.__class__ == FriendBanner:
                friends_list_grid.remove_widget(w)

        # Need to clear widgets from previous user's workout grid
        workout_banner = self.root.ids['home_screen'].ids['banner_grid']
        for w in workout_banner.walk():
            if w.__class__ == WorkoutsBanner:
                workout_banner.remove_widget(w)

        # Need to clear widgets from previous user's friend's workout grid
        friend_banner_grid = self.root.ids['friend_workout_screen'].ids[
            'friend_banner_grid']
        for w in friend_banner_grid.walk():
            if w.__class__ == WorkoutsBanner:
                friend_banner_grid.remove_widget(w)
예제 #13
0
파일: main.py 프로젝트: jmcmai/FridgeNotes
 def build(self):
     self.my_firebase = MyFirebase()
     self.theme_cls.primary_palette = "Orange"
     return ScreenManagement()
예제 #14
0
파일: main.py 프로젝트: jmcmai/FridgeNotes
class MainApp(MDApp):
    date = ''

    def build(self):
        self.my_firebase = MyFirebase()
        self.theme_cls.primary_palette = "Orange"
        return ScreenManagement()

    def signed_in(self):
        #get data from database
        data = self.my_firebase.get_database_data(self.local_id)
        print(data)
        #populate fridge data in list screen
        layout = self.root.ids['list_screen'].ids['list_layout']
        for key in data:
            name = data[key]['name']
            exp_date = data[key]['expiration date']
            extra_notes = data[key]['notes']
            quantity = data[key]['quantity']
            I = ItemList(name=name,
                         exp_date=exp_date,
                         extra_notes=extra_notes,
                         quantity=quantity)  # creates card
            layout.add_widget(I)

    # date picker for items
    def show_datepicker(self):
        min_date = date.today()
        picker = MDDatePicker(callback=self.get_date, min_date=min_date)
        picker.open()

    def get_date(self, date):
        self.date = date.strftime('%Y-%m-%d')
        print(self.date)
        self.root.ids['user_input_screen'].ids['expiry_date'].text = self.date

    # gets information from adding items
    def update_database(self):
        self.root.ids['user_input_screen'].ids[
            'expiry_date'].text = "Expiration Date: " + self.date
        grocery_item = self.root.ids['user_input_screen'].ids[
            "grocery_item"].text
        notes = self.root.ids['user_input_screen'].ids["extra_notes"].text
        quantity = self.root.ids['user_input_screen'].ids["quantity"].text
        if grocery_item == '' or notes == '' or quantity == '':
            self.root.ids['user_input_screen'].ids[
                'invalid_items'].text = "Please fill out all fields."
        else:
            update_items = {
                'name': grocery_item,
                'notes': notes,
                'quantity': quantity,
                'expiration date': self.date
            }
            self.my_firebase.db.collection(self.local_id).add(update_items)
            layout = self.root.ids['list_screen'].ids['list_layout']
            I = ItemList(name=grocery_item,
                         exp_date=self.date,
                         extra_notes=notes,
                         quantity=quantity)  # creates card
            layout.add_widget(I)
            self.root.current = 'list_screen'