示例#1
0
    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 = 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/" + 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
        if friend_id in self.nicknames.keys():
            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 = workouts.keys()
        workout_keys.sort(key=lambda value: datetime.strptime(workouts[value.encode()]['date'].encode('utf-8'), "%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")
示例#2
0
    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")
示例#3
0
    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 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 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