Skip to content

Commit

Permalink
Made a few fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
StarNumber12046 committed Sep 12, 2024
1 parent c3a1b3b commit f697634
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 101 deletions.
60 changes: 5 additions & 55 deletions app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import Home from ".";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import AsyncStorage from "@react-native-async-storage/async-storage";
import getHeaders from "happy-headers";
import { Friends, FullUser, User } from "@/sdk";
import { checkToken, Friends, FullUser, User } from "@/sdk";

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();
Expand All @@ -43,64 +43,11 @@ export const ProfileContext = createContext<ProfileContextType>({
setFriends: (friends: Friends | null) => {},
});

async function checkToken() {
const authToken = await AsyncStorage.getItem("authToken");
const refreshToken = await AsyncStorage.getItem("refreshToken");
const userResponse = await fetch(
"https://mobile.bereal.com/api/feeds/friends-v1",
{
headers: {
...getHeaders(),
Authorization: `Bearer ${authToken}`,
},
}
);
if (!userResponse.ok || (await userResponse.json())["_h"] == 0) {
console.log("User seems broken");
const data = await fetch(
"https://auth.bereal.team/token?grant_type=refresh_token",
{
method: "POST",
headers: {
...getHeaders(),
"content-type": "application/json",
accept: "*/*",
"x-client-version": "iOS/FirebaseSDK/8.15.0/FirebaseCore-iOS",
"x-firebase-client-log-type": "0",
"x-ios-bundle-identifier": "AlexisBarreyat.BeReal",
"accept-language": "en",
"user-agent":
"FirebaseAuth.iOS/8.15.0 AlexisBarreyat.BeReal/0.22.4 iPhone/14.7.1 hw/iPhone9_1",
},
body: JSON.stringify({
client_id: "ios",
client_secret: "962D357B-B134-4AB6-8F53-BEA2B7255420",
refresh_token: refreshToken,
grant_type: "refresh_token",
}),
}
);
const tokenResponse = await data.json();
console.log(data);
if (!data.ok) {
console.log("Token seems broken");
return null;
}
console.log("Token has been refreshed successfully");
await AsyncStorage.setItem("authToken", tokenResponse.access_token);
await AsyncStorage.setItem("refreshToken", tokenResponse.refresh_token);
router.navigate("/profile");
return [tokenResponse.access_token, tokenResponse.refresh_token];
}
return [authToken, refreshToken];
}

export default function RootLayout() {
const [user, setUser] = useState<FullUser | null>(null);
const [sessionInfo, setSessionInfo] = useState<string | null>(null);
const [suggestedFriends, setSuggestedFriends] = useState<User[] | null>(null);
const [friends, setFriends] = useState<Friends | null>(null);

const [loaded] = useFonts({
Inter_400Regular,
Inter_500Medium,
Expand All @@ -110,7 +57,10 @@ export default function RootLayout() {

useEffect(() => {
if (loaded) {
checkToken().then(() => SplashScreen.hideAsync());
checkToken().then((out) => {
SplashScreen.hideAsync();
if (out && out[0]) router.push("/");
});
}
}, [loaded]);

Expand Down
4 changes: 3 additions & 1 deletion app/camera.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,20 @@ import {
useCameraPermissions,
CameraPictureOptions,
} from "expo-camera";
import { useRef, useState } from "react";
import { useContext, useRef, useState } from "react";
import { CaptureButton } from "@/components/CameraButton";
import { finalizeUpload, generateUploadUrl } from "@/sdk";
import getHeaders from "happy-headers";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { router } from "expo-router";
import { ProfileContext } from "./_layout";

export default function Camera() {
const [facing, setFacing] = useState<CameraType>("back");
const [permission, requestPermission] = useCameraPermissions();
const ref = useRef<CameraView>(null);
const [cameraReady, setCameraReady] = useState(false);
const userContext = useContext(ProfileContext);
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Expand Down
99 changes: 61 additions & 38 deletions app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,27 @@ import { CameraButton } from "@/components/CameraButton";
import { router } from "expo-router";
import AsyncStorage from "@react-native-async-storage/async-storage";
import getHeaders from "happy-headers";
import { getFriendsPosts, getMyPosts, UserPost } from "@/sdk";
import {
checkToken,
FullUser,
getFriendsPosts,
getMyPosts,
getMyProfile,
UserPost,
} from "@/sdk";
import { ScrollView } from "react-native-gesture-handler";
import { ProfileContext } from "./_layout";

export default function App() {
const [visibleItems, setVisibleItems] = useState<{ [key: string]: boolean }>(
{}
);
// State to check if the component is mounted
const [isMounted, setIsMounted] = useState(false);
const [isUsable, setIsUsable] = useState(false);
const [friendsPosts, setFriendsPosts] = useState<any[]>([]);
const [myPosts, setMyPosts] = useState<UserPost[]>([]);

const [me, setMe] = useState<FullUser | null>(null);
const userContext = useContext(ProfileContext);
async function checkAuth() {
if (
!(await AsyncStorage.getItem("authToken")) ||
Expand All @@ -30,14 +39,22 @@ export default function App() {
}

// Use useEffect to check if the component is mounted
checkToken().then(() => {
setIsUsable(true);
});
useEffect(() => {
setIsMounted(true);
if (isMounted) {
checkAuth();
getFriendsPosts().then((p) => setFriendsPosts(p));
getMyPosts().then((p) => setMyPosts(p));
if (isUsable) {
setMyPosts([]);
setFriendsPosts([]);
setMe(null);
if (isUsable) {
checkAuth();
getFriendsPosts().then((p) => setFriendsPosts(p));
getMyPosts().then((p) => setMyPosts(p));
getMyProfile(userContext).then((p) => setMe(p));
}
}
}, [isMounted]);
}, [isUsable]);

const handleVisibilityChange = (id: string, isVisible: boolean) => {
setVisibleItems((prevState) => ({
Expand All @@ -48,7 +65,13 @@ export default function App() {

return (
<View>
<TopBar />
<TopBar
action={() => {
getFriendsPosts().then((p) => setFriendsPosts(p));
getMyPosts().then((p) => setMyPosts(p));
getMyProfile(userContext).then((p) => setMe(p));
}}
/>
<IOScrollView style={styles.scrollView}>
<ScrollView
horizontal
Expand Down Expand Up @@ -83,32 +106,34 @@ export default function App() {
</InView>
))}
</ScrollView>
{friendsPosts.map((value) => (
<InView
key={value.id}
onChange={(inView) => handleVisibilityChange(value.id, inView)}
>
<ReBeal
primaryHeight={value.primary.height}
primaryWidth={value.primary.width}
primaryUrl={value.primary.url}
secondaryHeight={value.secondary.height}
secondaryWidth={value.secondary.width}
secondaryUrl={value.secondary.url}
userName={value.user.username}
userUrl={value.user.profilePicture.url}
isLate={value.isLate}
postedAt={value.postedAt}
lateInSeconds={value.lateInSeconds}
isMain={value.isMain}
visible={visibleItems[value.id]} // Pass visibility state here
blurred={myPosts.length <= 0}
/>
</InView>
))}
<View style={{ width: "100%", height: 75 }}></View>
<View style={{ width: "100%", top: -80 }}>
{friendsPosts.map((value) => (
<InView
key={value.id}
onChange={(inView) => handleVisibilityChange(value.id, inView)}
>
<ReBeal
primaryHeight={value.primary.height}
primaryWidth={value.primary.width}
primaryUrl={value.primary.url}
secondaryHeight={value.secondary.height}
secondaryWidth={value.secondary.width}
secondaryUrl={value.secondary.url}
userName={value.user.username}
userUrl={value.user.profilePicture.url}
isLate={value.isLate}
postedAt={value.postedAt}
lateInSeconds={value.lateInSeconds}
isMain={value.isMain}
visible={visibleItems[value.id]} // Pass visibility state here
blurred={myPosts.length <= 0}
/>
</InView>
))}
<View style={{ width: "100%", height: 0 }}></View>
</View>
</IOScrollView>
<CameraButton />
<CameraButton shown={me?.canPost ?? true} />
</View>
);
}
Expand All @@ -123,11 +148,9 @@ const styles = StyleSheet.create({
},
scrollView: {
position: "static",
top: -80,
paddingTop: 80,
top: 0,
left: 0,
width: "100%",
marginBottom: 10,
},
container: {
flex: 1, // Fill the available space
Expand Down
4 changes: 2 additions & 2 deletions components/CameraButton.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Link } from "expo-router";
import { Pressable, View, StyleSheet, TouchableOpacity } from "react-native";

export function CameraButton() {
export function CameraButton({ shown }: { shown: boolean }) {
return (
<View style={styles.container}>
<View style={[styles.container, { opacity: shown ? 1 : 0 }]}>
<Link href="/camera">
<View style={styles.cameraButton} />
</Link>
Expand Down
16 changes: 12 additions & 4 deletions components/TopBar.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import { ProfileContext, ProfileContextType } from "@/app/_layout";
import { getMyProfile } from "@/sdk";
import { MaterialIcons } from "@expo/vector-icons";
import { Link } from "expo-router";
import { Link, router } from "expo-router";
import getHeaders from "happy-headers";
import { useContext, useEffect, useState } from "react";
import { View, Pressable, Text, Image, StyleSheet } from "react-native";

export const TopBar = ({ small = false }: { small?: boolean }) => {
export const TopBar = ({
small = false,
action = () => {
router.navigate("/");
},
}: {
small?: boolean;
action?: () => void;
}) => {
const userContext = useContext(ProfileContext);
const [profilePicture, setProfilePicture] =
useState<string>("rebeal://profile");
Expand All @@ -28,9 +36,9 @@ export const TopBar = ({ small = false }: { small?: boolean }) => {
<MaterialIcons name="people" size={24} color="white" />
</Link>
)}
<Link href="/">
<Pressable onPress={() => action()}>
<Text style={styles.text}>ReBeal.</Text>
</Link>
</Pressable>
{!small && (
<Link href="/profile" asChild>
<Pressable>
Expand Down
54 changes: 53 additions & 1 deletion sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import getHeaders from "happy-headers";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useContext } from "react";
import { ProfileContext, ProfileContextType } from "./app/_layout";
import { router } from "expo-router";

// Generated by https://quicktype.io

Expand Down Expand Up @@ -518,4 +519,55 @@ export async function finalizeUpload(data: any) {
} else {
throw new Error("Error uploading image");
}
}
}

export async function checkToken() {
const authToken = await AsyncStorage.getItem("authToken");
const refreshToken = await AsyncStorage.getItem("refreshToken");
const userResponse = await fetch(
"https://mobile.bereal.com/api/feeds/friends-v1",
{
headers: {
...getHeaders(),
Authorization: `Bearer ${authToken}`,
},
}
);
if (!userResponse.ok || (await userResponse.json())["_h"] == 0) {
console.log("User seems broken");
const data = await fetch(
"https://auth.bereal.team/token?grant_type=refresh_token",
{
method: "POST",
headers: {
...getHeaders(),
"content-type": "application/json",
accept: "*/*",
"x-client-version": "iOS/FirebaseSDK/8.15.0/FirebaseCore-iOS",
"x-firebase-client-log-type": "0",
"x-ios-bundle-identifier": "AlexisBarreyat.BeReal",
"accept-language": "en",
"user-agent":
"FirebaseAuth.iOS/8.15.0 AlexisBarreyat.BeReal/0.22.4 iPhone/14.7.1 hw/iPhone9_1",
},
body: JSON.stringify({
client_id: "ios",
client_secret: "962D357B-B134-4AB6-8F53-BEA2B7255420",
refresh_token: refreshToken,
grant_type: "refresh_token",
}),
}
);
const tokenResponse = await data.json();
console.log(data);
if (!data.ok) {
console.log("Token seems broken");
return null;
}
console.log("Token has been refreshed successfully");
await AsyncStorage.setItem("authToken", tokenResponse.access_token);
await AsyncStorage.setItem("refreshToken", tokenResponse.refresh_token);
return [true, tokenResponse.access_token, tokenResponse.refresh_token];
}
return [false, authToken, refreshToken];
}

0 comments on commit f697634

Please sign in to comment.