├── admin
├── src
│ ├── components
│ │ ├── Admin.js
│ │ ├── login.js
│ │ ├── Users.js
│ │ ├── Ride.js
│ │ ├── Post.js
│ │ ├── User.js
│ │ └── Home.js
│ ├── setupTests.js
│ ├── config
│ │ └── config.js
│ ├── App.test.js
│ ├── reportWebVitals.js
│ ├── App.css
│ ├── index.js
│ ├── App.js
│ ├── index.css
│ └── logo.svg
├── public
│ ├── robots.txt
│ ├── favicon.ico
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── index.html
├── .gitignore
├── package.json
└── README.md
├── .vscode
└── settings.json
├── images
├── mockup.png
└── simcoder.png
├── frontend
├── assets
│ ├── icon.png
│ ├── logo.png
│ ├── splash.png
│ ├── favicon.png
│ ├── account.svg
│ └── confirm.svg
├── babel.config.js
├── redux
│ ├── reducers
│ │ ├── index.js
│ │ ├── user.js
│ │ └── users.js
│ ├── constants
│ │ └── index.js
│ └── actions
│ │ └── index.js
├── components
│ ├── main
│ │ ├── random
│ │ │ ├── Blocked.js
│ │ │ └── CachedImage.js
│ │ ├── profile
│ │ │ ├── Search.js
│ │ │ ├── Edit.js
│ │ │ └── Profile.js
│ │ ├── post
│ │ │ ├── Feed.js
│ │ │ ├── Comment.js
│ │ │ └── Post.js
│ │ ├── chat
│ │ │ ├── List.js
│ │ │ └── Chat.js
│ │ └── add
│ │ │ ├── Save.js
│ │ │ └── Camera.js
│ ├── utils.js
│ ├── auth
│ │ ├── Login.js
│ │ └── Register.js
│ ├── styles.js
│ └── Main.js
├── app.json
├── package.json
└── App.js
├── .gitignore
├── storage_rules.txt
├── firestore_rules.txt
├── backend
└── functions
│ └── index.js
├── README.md
└── LICENSE
/admin/src/components/Admin.js:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "git.ignoreLimitWarning": true
3 | }
--------------------------------------------------------------------------------
/admin/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/images/mockup.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/images/mockup.png
--------------------------------------------------------------------------------
/images/simcoder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/images/simcoder.png
--------------------------------------------------------------------------------
/admin/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/admin/public/favicon.ico
--------------------------------------------------------------------------------
/admin/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/admin/public/logo192.png
--------------------------------------------------------------------------------
/admin/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/admin/public/logo512.png
--------------------------------------------------------------------------------
/frontend/assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/frontend/assets/icon.png
--------------------------------------------------------------------------------
/frontend/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/frontend/assets/logo.png
--------------------------------------------------------------------------------
/frontend/assets/splash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/frontend/assets/splash.png
--------------------------------------------------------------------------------
/frontend/assets/favicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SimCoderYoutube/InstagramClone/HEAD/frontend/assets/favicon.png
--------------------------------------------------------------------------------
/frontend/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = function(api) {
2 | api.cache(true);
3 | return {
4 | presets: ['babel-preset-expo'],
5 | };
6 | };
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/**/*
2 | .expo/*
3 | npm-debug.*
4 | *.jks
5 | *.p8
6 | *.p12
7 | *.key
8 | *.mobileprovision
9 | *.orig.*
10 | web-build/
11 |
12 | # macOS
13 | .DS_Store
14 |
--------------------------------------------------------------------------------
/admin/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom';
6 |
--------------------------------------------------------------------------------
/frontend/redux/reducers/index.js:
--------------------------------------------------------------------------------
1 | import { combineReducers } from 'redux'
2 | import { user } from './user'
3 | import { users } from './users'
4 |
5 | const Reducers = combineReducers({
6 | userState: user,
7 | usersState: users
8 | })
9 |
10 | export default Reducers
--------------------------------------------------------------------------------
/admin/src/config/config.js:
--------------------------------------------------------------------------------
1 | export var firebaseConfig = {
2 | apiKey: "****",
3 | authDomain: "****",
4 | databaseURL: "****",
5 | projectId: "****",
6 | storageBucket: "****",
7 | messagingSenderId: "****",
8 | appId: "****",
9 | measurementId: "****"
10 |
11 | };
12 |
--------------------------------------------------------------------------------
/admin/src/App.test.js:
--------------------------------------------------------------------------------
1 | import { render, screen } from '@testing-library/react';
2 | import App from './App';
3 |
4 | test('renders learn react link', () => {
5 | render();
6 | const linkElement = screen.getByText(/learn react/i);
7 | expect(linkElement).toBeInTheDocument();
8 | });
9 |
--------------------------------------------------------------------------------
/storage_rules.txt:
--------------------------------------------------------------------------------
1 | rules_version = '2';
2 | service firebase.storage {
3 | match /b/{bucket}/o {
4 | match /profile/{uid} {
5 | allow read: if true;
6 | allow write: if request.auth.uid == uid;
7 | }
8 | match /post/{uid}/{post=**} {
9 | allow read: if true;
10 | allow write: if request.auth.uid == uid;
11 | }
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/admin/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/admin/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/admin/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/admin/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/admin/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import reportWebVitals from './reportWebVitals';
6 |
7 | import firebase from 'firebase';
8 |
9 | const firebaseConfig = require('./config/config').firebaseConfig;
10 | firebase.initializeApp(firebaseConfig)
11 |
12 |
13 | ReactDOM.render(
14 |
15 |
16 | ,
17 | document.getElementById('root')
18 | );
19 |
20 | // If you want to start measuring performance in your app, pass a function
21 | // to log results (for example: reportWebVitals(console.log))
22 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
23 | reportWebVitals();
24 |
25 |
26 |
--------------------------------------------------------------------------------
/admin/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component, useState, useEffect } from 'react'
2 | import { BrowserRouter as Router, Route } from 'react-router-dom'
3 | import firebase from 'firebase'
4 | import login from './components/login'
5 | import 'bootstrap/dist/css/bootstrap.css';
6 | import Home from './components/Home';
7 |
8 |
9 |
10 | function App() {
11 | const [loggedIn, setLoggedIn] = useState(false)
12 | useEffect(() => {
13 | firebase.auth().onAuthStateChanged(user => {
14 | if (!user) {
15 | setLoggedIn(false);
16 | }
17 | else {
18 | setLoggedIn(true);
19 | }
20 | })
21 | }, [])
22 |
23 | if (loggedIn) {
24 | return (
25 |
26 | )
27 | }
28 | return (
29 |
30 |
31 |
32 | )
33 | }
34 |
35 | export default App
36 |
--------------------------------------------------------------------------------
/frontend/redux/constants/index.js:
--------------------------------------------------------------------------------
1 | export const USER_STATE_CHANGE = 'USER_STATE_CHANGE'
2 | export const USER_POSTS_STATE_CHANGE = 'USER_POSTS_STATE_CHANGE'
3 | export const USER_FOLLOWING_STATE_CHANGE = 'USER_FOLLOWING_STATE_CHANGE'
4 | export const USER_CHATS_STATE_CHANGE = 'USER_CHATS_STATE_CHANGE'
5 |
6 | export const USERS_POSTS_STATE_CHANGE = 'USERS_POSTS_STATE_CHANGE'
7 | export const USERS_LIKES_STATE_CHANGE = 'USERS_LIKES_STATE_CHANGE'
8 | export const USERS_DATA_STATE_CHANGE = 'USERS_DATA_STATE_CHANGE'
9 |
10 | export const USER_FRIENDS_REQUESTS_SENT_STATE_CHANGE = 'USER_FRIDENDS_REQUESTS_SENT_STATE_CHANGE'
11 | export const USER_FRIENDS_REQUESTS_RECEIVED_STATE_CHANGE = 'USER_FRIDENDS_REQUESTS_RECEIVED_STATE_CHANGE'
12 | export const USER_FRIENDS_STATE_CHANGE = 'USER_FRIDENDS_STATE_CHANGE'
13 |
14 | export const USER_CLEAR_FRIENDS = 'USER_CLEAR_FRIENDS'
15 |
16 |
17 | export const CLEAR_DATA = 'CLEAR_DATA'
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/frontend/components/main/random/Blocked.js:
--------------------------------------------------------------------------------
1 | import { Feather } from '@expo/vector-icons';
2 | import React, { useEffect } from 'react';
3 | import { BackHandler, Text, View } from 'react-native';
4 | export default function Blocked() {
5 | useEffect(() => {
6 | BackHandler.addEventListener('hardwareBackPress', () => true)
7 | return () =>
8 | BackHandler.removeEventListener('hardwareBackPress', () => true)
9 | }, [])
10 |
11 | return (
12 |
13 |
14 |
15 |
16 |
17 | Your account has been blocked
18 |
19 |
20 |
21 | )
22 | }
23 |
24 |
25 |
--------------------------------------------------------------------------------
/frontend/components/utils.js:
--------------------------------------------------------------------------------
1 | function timeDifference(current, previous) {
2 |
3 | var msPerMinute = 60 * 1000;
4 | var msPerHour = msPerMinute * 60;
5 | var msPerDay = msPerHour * 24;
6 | var msPerMonth = msPerDay * 30;
7 | var msPerYear = msPerDay * 365;
8 |
9 | var elapsed = current - previous;
10 |
11 | if (elapsed < msPerMinute) {
12 | return 'Now';
13 | }
14 |
15 | else if (elapsed < msPerHour) {
16 | return Math.round(elapsed / msPerMinute) + ' minutes ago';
17 | }
18 |
19 | else if (elapsed < msPerDay) {
20 | return Math.round(elapsed / msPerHour) + ' hours ago';
21 | }
22 |
23 | else if (elapsed < msPerMonth) {
24 | return Math.round(elapsed / msPerDay) + ' days ago';
25 | }
26 |
27 | else if (elapsed < msPerYear) {
28 | return Math.round(elapsed / msPerMonth) + ' months ago';
29 | }
30 |
31 | else {
32 | return Math.round(elapsed / msPerYear) + ' years ago';
33 | }
34 | }
35 |
36 | export { timeDifference };
37 |
--------------------------------------------------------------------------------
/frontend/assets/account.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/frontend/redux/reducers/user.js:
--------------------------------------------------------------------------------
1 | import { CLEAR_DATA, USER_CHATS_STATE_CHANGE, USER_FOLLOWING_STATE_CHANGE, USER_POSTS_STATE_CHANGE, USER_STATE_CHANGE } from "../constants"
2 |
3 | const initialState = {
4 | currentUser: null,
5 | posts: [],
6 | chats: [],
7 | following: [],
8 | }
9 |
10 | export const user = (state = initialState, action) => {
11 | switch (action.type) {
12 | case USER_STATE_CHANGE:
13 | return {
14 | ...state,
15 | currentUser: action.currentUser
16 | }
17 | case USER_POSTS_STATE_CHANGE:
18 | return {
19 | ...state,
20 | posts: action.posts
21 | }
22 |
23 | case USER_FOLLOWING_STATE_CHANGE:
24 | return {
25 | ...state,
26 | following: action.following
27 | }
28 | case USER_CHATS_STATE_CHANGE: {
29 | return {
30 | ...state,
31 | chats: action.chats
32 | }
33 | }
34 | case CLEAR_DATA:
35 | return initialState
36 | default:
37 | return state;
38 | }
39 | }
--------------------------------------------------------------------------------
/frontend/redux/reducers/users.js:
--------------------------------------------------------------------------------
1 | import { CLEAR_DATA, USERS_DATA_STATE_CHANGE, USERS_LIKES_STATE_CHANGE, USERS_POSTS_STATE_CHANGE } from "../constants"
2 |
3 | const initialState = {
4 | users: [],
5 | feed: [],
6 | usersFollowingLoaded: 0,
7 | }
8 |
9 | export const users = (state = initialState, action) => {
10 | switch (action.type) {
11 | case USERS_DATA_STATE_CHANGE:
12 | return {
13 | ...state,
14 | users: [...state.users, action.user]
15 | }
16 | case USERS_POSTS_STATE_CHANGE:
17 | return {
18 | ...state,
19 | usersFollowingLoaded: state.usersFollowingLoaded + 1,
20 | feed: [...state.feed, ...action.posts]
21 | }
22 | case USERS_LIKES_STATE_CHANGE:
23 | return {
24 | ...state,
25 | feed: state.feed.map(post => post.id == action.postId ?
26 | { ...post, currentUserLike: action.currentUserLike } :
27 | post)
28 | }
29 | case CLEAR_DATA:
30 | return initialState
31 | default:
32 | return state;
33 | }
34 | }
--------------------------------------------------------------------------------
/frontend/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "name": "instagram",
4 | "slug": "instagram",
5 | "version": "1.0.0",
6 | "orientation": "portrait",
7 | "icon": "./assets/logo.png",
8 | "splash": {
9 | "image": "./assets/logo.png",
10 | "resizeMode": "contain",
11 | "backgroundColor": "#ffffff"
12 | },
13 | "updates": {
14 | "fallbackToCacheTimeout": 0
15 | },
16 | "assetBundlePatterns": [
17 | "**/*"
18 | ],
19 | "android": {
20 | "useNextNotificationsApi": true,
21 | "package": "com.instagram.simcoder",
22 | "googleServicesFile": "./google-services.json",
23 | "config": {
24 | "googleSignIn": {
25 | "apiKey": "****"
26 | }
27 | }
28 | },
29 | "ios": {
30 | "buildNumber": "1.0.0",
31 | "supportsTablet": true,
32 | "bundleIdentifier": "com.instagram.simcoder",
33 | "config": {
34 | "googleSignIn": {
35 | "reservedClientId": "****"
36 | },
37 | "googleMapsApiKey": "****"
38 | },
39 | "googleServicesFile": "./GoogleService-Info.plist"
40 | },
41 | "web": {
42 | "favicon": "./assets/logo.png"
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/frontend/assets/confirm.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
45 |
--------------------------------------------------------------------------------
/admin/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "admin",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@material-ui/core": "^4.11.3",
7 | "@material-ui/data-grid": "^4.0.0-alpha.18",
8 | "@material-ui/icons": "^4.11.2",
9 | "@material-ui/x-grid": "^4.0.0-alpha.18",
10 | "@testing-library/jest-dom": "^5.11.9",
11 | "@testing-library/react": "^11.2.5",
12 | "@testing-library/user-event": "^12.6.3",
13 | "bootstrap": "^4.6.0",
14 | "expo-device": "^3.1.1",
15 | "firebase": "^8.2.5",
16 | "firebase-admin": "^9.4.2",
17 | "react": "^17.0.1",
18 | "react-dom": "^17.0.1",
19 | "react-icons": "^4.1.0",
20 | "react-router-dom": "^5.2.0",
21 | "react-scripts": "4.0.2",
22 | "web-vitals": "^1.1.0"
23 | },
24 | "scripts": {
25 | "start": "react-scripts start",
26 | "build": "react-scripts build",
27 | "test": "react-scripts test",
28 | "eject": "react-scripts eject"
29 | },
30 | "eslintConfig": {
31 | "extends": [
32 | "react-app",
33 | "react-app/jest"
34 | ]
35 | },
36 | "browserslist": {
37 | "production": [
38 | ">0.2%",
39 | "not dead",
40 | "not op_mini all"
41 | ],
42 | "development": [
43 | "last 1 chrome version",
44 | "last 1 firefox version",
45 | "last 1 safari version"
46 | ]
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/frontend/components/auth/Login.js:
--------------------------------------------------------------------------------
1 | import firebase from 'firebase';
2 | import React, { useState } from 'react';
3 | import { Button, Text, TextInput, View } from 'react-native';
4 | import { container, form } from '../styles';
5 |
6 | export default function Login(props) {
7 | const [email, setEmail] = useState('');
8 | const [password, setPassword] = useState('');
9 |
10 | const onSignUp = () => {
11 | firebase.auth().signInWithEmailAndPassword(email, password)
12 | }
13 |
14 | return (
15 |
16 |
17 | setEmail(email)}
21 | />
22 | setPassword(password)}
27 | />
28 |
29 |
35 |
36 |
37 |
38 | props.navigation.navigate("Register")} >
41 | Don't have an account? SignUp.
42 |
43 |
44 |
45 | )
46 | }
47 |
48 |
--------------------------------------------------------------------------------
/frontend/components/main/random/CachedImage.js:
--------------------------------------------------------------------------------
1 | import * as FileSystem from 'expo-file-system'
2 | import PropTypes from 'prop-types'
3 | import React, { useEffect, useRef, useState } from 'react'
4 | import { Image } from 'react-native'
5 |
6 |
7 |
8 |
9 | const CachedImage = props => {
10 | const { source: { uri }, cacheKey } = props
11 | const filesystemURI = `${FileSystem.cacheDirectory}${cacheKey}`
12 |
13 | const [imgURI, setImgURI] = useState(filesystemURI)
14 |
15 | const componentIsMounted = useRef(true)
16 |
17 | useEffect(() => {
18 | const loadImage = async ({ fileURI }) => {
19 | try {
20 | // Use the cached image if it exists
21 | const metadata = await FileSystem.getInfoAsync(fileURI)
22 | if (!metadata.exists) {
23 | // download to cache
24 | if (componentIsMounted.current) {
25 | setImgURI(null)
26 | await FileSystem.downloadAsync(
27 | uri,
28 | fileURI
29 | )
30 | }
31 | if (componentIsMounted.current) {
32 | setImgURI(fileURI)
33 | }
34 | }
35 | } catch (err) {
36 | setImgURI(uri)
37 | }
38 | }
39 |
40 | loadImage({ fileURI: filesystemURI })
41 |
42 | return () => {
43 | componentIsMounted.current = false
44 | }
45 | }, [])// eslint-disable-line react-hooks/exhaustive-deps
46 |
47 | return (
48 |
55 | )
56 | }
57 |
58 | CachedImage.propTypes = {
59 | source: PropTypes.object.isRequired,
60 | cacheKey: PropTypes.string.isRequired,
61 | }
62 |
63 | export default CachedImage
64 |
--------------------------------------------------------------------------------
/admin/src/components/login.js:
--------------------------------------------------------------------------------
1 |
2 | import React, { Component, useState, useEffect } from 'react'
3 | import { Redirect } from 'react-router-dom'
4 |
5 | import firebase from 'firebase'
6 |
7 |
8 | export default function Login() {
9 | const [email, setEmail] = useState('');
10 | const [password, setPassword] = useState('')
11 |
12 | const onSignIn = () => {
13 | firebase.auth().signInWithEmailAndPassword(email, password).catch(function (error) {
14 | });
15 | }
16 |
17 | if (firebase.auth().currentUser == undefined) {
18 | return (
19 |
20 |
21 |
22 |
23 |
Sign In
24 |
25 |
26 |
27 | setEmail(e.target.value)}
29 | value={email} />
30 |
31 |
32 |
33 |
34 | setPassword(e.target.value)} />
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | )
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/firestore_rules.txt:
--------------------------------------------------------------------------------
1 | service cloud.firestore {
2 | match /databases/{database}/documents {
3 | function isAdmin() {
4 | return exists(/databases/$(database)/documents/admin/$(request.auth.uid))
5 | }
6 | match /users/{user} {
7 | allow read: if true;
8 | allow write, update: if request.auth.uid == user;
9 | allow write, update: if isAdmin();
10 | }
11 | match /posts/{user}/userPosts {
12 | allow read: if true;
13 | allow write: if request.auth.uid == user;
14 | allow write, update: if isAdmin();
15 |
16 | }
17 | match /posts/{user}/userPosts/{postId} {
18 | allow read: if true;
19 | allow write: if request.auth.uid == user;
20 | allow write, update: if isAdmin();
21 |
22 | }
23 | match /posts/{user}/userPosts/{postId}/likes/{likeId} {
24 | allow read: if true;
25 | allow write: if request.auth.uid == likeId;
26 | allow write, update: if isAdmin();
27 | }
28 | match /posts/{user}/userPosts/{postId}/comments/{commentId} {
29 | allow read: if true;
30 | allow write: if request.auth.uid != null;
31 | allow write, update: if isAdmin();
32 | }
33 |
34 | match /feed/{documents=**}{
35 | allow read, write: if request.auth.uid != null;
36 | }
37 | match /following/{user}/userFollowing/{following} {
38 | allow read: if true;
39 | allow write: if user == request.auth.uid;
40 |
41 | }
42 | match /admin/{documents=**}{
43 | allow write, update, read: if false;
44 | }
45 | match /chats/{chatId}{
46 | allow read, update: if request.auth.uid in resource.data.users;
47 | allow write: if request.auth.uid != null;
48 | }
49 | match /chats/{chatId}/messages/{documents=**}{
50 | allow read, write: if true;
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/admin/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/admin/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
15 | @import url('https://fonts.googleapis.com/css?family=Fira+Sans:400,500,600,700,800');
16 |
17 | * {
18 | box-sizing: border-box;
19 | }
20 | body {
21 | min-height: 100vh;
22 | display: flex;
23 | font-weight: 400;
24 | font-family: 'Fira Sans', sans-serif;
25 | }
26 |
27 | h1,h2,h3,h4,h5,h6,label,span {
28 | font-weight: 500;
29 | font-family: 'Fira Sans', sans-serif;
30 | }
31 |
32 | body, html, .App, #root, .auth-wrapper {
33 | width: 100%;
34 | height: 100%;
35 | }
36 |
37 | .navbar-light {
38 | background-color: #ffffff;
39 | box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2);
40 | }
41 |
42 | .auth-wrapper {
43 | display: flex;
44 | justify-content: center;
45 | flex-direction: column;
46 | text-align: left;
47 | }
48 |
49 | .auth-inner {
50 | width: 450px;
51 | margin: auto;
52 | background: #ffffff;
53 | box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2);
54 | padding: 40px 55px 45px 55px;
55 | border-radius: 15px;
56 | transition: all .3s;
57 | }
58 |
59 | .auth-wrapper .form-control:focus {
60 | border-color: #167bff;
61 | box-shadow: none;
62 | }
63 |
64 | .auth-wrapper h3 {
65 | text-align: center;
66 | margin: 0;
67 | line-height: 1;
68 | padding-bottom: 20px;
69 | }
70 |
71 | .custom-control-label {
72 | font-weight: 400;
73 | }
74 |
75 | .forgot-password,
76 | .forgot-password a {
77 | text-align: right;
78 | font-size: 13px;
79 | padding-top: 10px;
80 | color: #7f7d7d;
81 | margin: 0;
82 | }
83 |
84 | .forgot-password a {
85 | color: #167bff;
86 | }
87 |
88 | .vertical-center {
89 | min-height: 100%; /* Fallback for browsers do NOT support vh unit */
90 | min-height: 100vh; /* These two lines are counted as one :-) */
91 |
92 | display: flex;
93 | align-items: center;
94 | }
95 |
--------------------------------------------------------------------------------
/admin/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/frontend/components/main/profile/Search.js:
--------------------------------------------------------------------------------
1 | import { FontAwesome5 } from '@expo/vector-icons';
2 | import React, { useState } from 'react';
3 | import { FlatList, Image, Text, TextInput, TouchableOpacity, View } from 'react-native';
4 | import { connect } from 'react-redux';
5 | import { bindActionCreators } from 'redux';
6 | import { queryUsersByUsername } from '../../../redux/actions/index';
7 | import { container, text, utils } from '../../styles';
8 |
9 | require('firebase/firestore');
10 |
11 |
12 | function Search(props) {
13 | const [users, setUsers] = useState([])
14 | return (
15 |
16 |
17 | props.queryUsersByUsername(search).then(setUsers)} />
21 |
22 |
23 |
24 | (
29 | props.navigation.navigate("Profile", { uid: item.id, username: undefined })}>
32 |
33 | {item.image == 'default' ?
34 | (
35 |
38 |
39 | )
40 | :
41 | (
42 |
48 | )
49 | }
50 |
51 | {item.username}
52 | {item.name}
53 |
54 |
55 |
56 | )}
57 | />
58 |
59 | )
60 | }
61 |
62 | const mapDispatchProps = (dispatch) => bindActionCreators({ queryUsersByUsername }, dispatch);
63 |
64 | export default connect(null, mapDispatchProps)(Search);
--------------------------------------------------------------------------------
/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "main": "node_modules/expo/AppEntry.js",
3 | "scripts": {
4 | "start": "expo start",
5 | "android": "expo start --android",
6 | "ios": "expo start --ios",
7 | "web": "expo start --web",
8 | "eject": "expo eject"
9 | },
10 | "dependencies": {
11 | "@ffprobe-installer/ffprobe": "^1.1.0",
12 | "@react-native-community/cameraroll": "^4.0.1",
13 | "@react-native-community/masked-view": "0.1.10",
14 | "@react-native-community/netinfo": "6.0.0",
15 | "@react-native-community/slider": "3.0.3",
16 | "@react-navigation/bottom-tabs": "^5.8.0",
17 | "@react-navigation/material-bottom-tabs": "^5.2.16",
18 | "@react-navigation/material-top-tabs": "^5.3.13",
19 | "@react-navigation/native": "^5.7.3",
20 | "@react-navigation/stack": "^5.9.0",
21 | "@skele/components": "^1.0.0-alpha.40",
22 | "babel-preset-expo": "^8.3.0",
23 | "expo": "~42.0.3",
24 | "expo-av": "~9.2.3",
25 | "expo-camera": "~11.2.2",
26 | "expo-cameraroll": "^1.1.0",
27 | "expo-checkbox": "^1.0.3",
28 | "expo-device": "~3.3.0",
29 | "expo-image-picker": "~10.2.2",
30 | "expo-linear-gradient": "~9.2.0",
31 | "expo-media-library": "~12.1.2",
32 | "expo-notifications": "~0.12.3",
33 | "expo-status-bar": "~1.0.4",
34 | "expo-updates": "~0.8.3",
35 | "expo-video-player": "^2.0.1",
36 | "expo-video-thumbnails": "~5.2.1",
37 | "firebase": "8.2.3",
38 | "get-video-duration": "^3.1.0",
39 | "queue": "^6.0.2",
40 | "react": "16.13.1",
41 | "react-dom": "16.13.1",
42 | "react-native": "https://github.com/expo/react-native/archive/sdk-42.0.0.tar.gz",
43 | "react-native-bottomsheet-reanimated": "0.0.22",
44 | "react-native-elements": "^3.0.0-alpha.1",
45 | "react-native-expo-cached-image": "^1.3.1",
46 | "react-native-fast-image": "^8.3.4",
47 | "react-native-gesture-handler": "~1.10.2",
48 | "react-native-interactable-reanimated": "0.0.8",
49 | "react-native-mentions": "^1.1.4",
50 | "react-native-optimized-flatlist": "^1.0.4",
51 | "react-native-paper": "^4.7.1",
52 | "react-native-parsed-text": "0.0.22",
53 | "react-native-reanimated": "~2.2.0",
54 | "react-native-restart": "0.0.20",
55 | "react-native-screens": "~3.4.0",
56 | "react-native-tab-view": "^2.15.2",
57 | "react-native-unimodules": " ~0.14.6",
58 | "react-native-vector-icons": "^7.1.0",
59 | "react-native-web": "~0.13.12",
60 | "react-redux": "^7.2.1",
61 | "react-uuid": "^1.0.2",
62 | "react-visibility-sensor": "^5.1.1",
63 | "reanimated-bottom-sheet": "^1.0.0-alpha.22",
64 | "redux": "^4.0.5",
65 | "redux-thunk": "^2.3.0",
66 | "sentry-expo": "^4.0.0"
67 | },
68 | "devDependencies": {
69 | "@babel/core": "~7.13.0",
70 | "babel-plugin-module-resolver": "^4.1.0"
71 | },
72 | "private": true
73 | }
--------------------------------------------------------------------------------
/admin/src/components/Users.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 |
3 | import firebase from 'firebase/app';
4 | import 'firebase/firestore';
5 |
6 | import { DataGrid } from '@material-ui/data-grid';
7 | import Chip from '@material-ui/core/Chip';
8 | import { Clear, Check } from '@material-ui/icons';
9 | import DoneIcon from '@material-ui/icons/Done';
10 | import Button from '@material-ui/core/Button';
11 | import { useHistory } from "react-router-dom";
12 |
13 | export default function Users() {
14 | const [users, setUsers] = useState([])
15 | useEffect(() => {
16 | firebase.firestore()
17 | .collection("users")
18 |
19 | .onSnapshot((snapshot) => {
20 | let result = snapshot.docs.map(doc => {
21 | const data = doc.data();
22 | const id = doc.id;
23 | return { id, ...data }
24 | })
25 | setUsers(result)
26 | })
27 | }, [])
28 | const history = useHistory();
29 |
30 | const columns = [
31 | { field: 'id', headerName: 'ID', width: 280 },
32 | { field: 'name', headerName: 'Name', width: 130 },
33 | { field: 'username', headerName: 'Username', width: 130 },
34 | {
35 | field: 'banned', headerName: 'banned', width: 150,
36 | renderCell: (params) => (
37 |
38 | {params.value ?
39 | }
41 | label="True"
42 | color="primary"
43 | variant="outlined"
44 | />
45 | :
46 | }
48 | label="False"
49 | color="secondary"
50 | variant="outlined"
51 | />
52 |
53 |
54 | }
55 |
56 |
57 | ),
58 |
59 | },
60 | {
61 | field: 'link', headerName: 'Detail', width: 150,
62 | renderCell: (params) => (
63 |
64 |
65 |
68 |
69 |
70 | ),
71 |
72 | },
73 | ];
74 |
75 |
76 |
77 | return (
78 |
79 | ({
80 | ...column,
81 | disableClickEventBubbling: true,
82 | }))} />
83 |
84 | )
85 | }
86 |
--------------------------------------------------------------------------------
/backend/functions/index.js:
--------------------------------------------------------------------------------
1 | const functions = require('firebase-functions');
2 |
3 | const admin = require('firebase-admin');
4 | admin.initializeApp();
5 |
6 | const db = admin.firestore();
7 |
8 | exports.addLike = functions.firestore.document('/posts/{creatorId}/userPosts/{postId}/likes/{userId}')
9 | .onCreate((snap, context) => {
10 | return db
11 | .collection("posts")
12 | .doc(context.params.creatorId)
13 | .collection("userPosts")
14 | .doc(context.params.postId)
15 | .update({
16 | likesCount: admin.firestore.FieldValue.increment(1)
17 | })
18 | });
19 | exports.removeLike = functions.firestore.document('/posts/{creatorId}/userPosts/{postId}/likes/{userId}')
20 | .onDelete((snap, context) => {
21 | return db
22 | .collection('posts')
23 | .doc(context.params.creatorId)
24 | .collection('userPosts')
25 | .doc(context.params.postId)
26 | .update({
27 | likesCount: admin.firestore.FieldValue.increment(-1)
28 | })
29 | })
30 |
31 |
32 | exports.addFollower = functions.firestore.document('/following/{userId}/userFollowing/{FollowingId}')
33 | .onCreate((snap, context) => {
34 | return db
35 | .collection('users')
36 | .doc(context.params.FollowingId)
37 | .update({
38 | followersCount: admin.firestore.FieldValue.increment(1)
39 | }).then(() => {
40 | return db
41 | .collection('users')
42 | .doc(context.params.userId)
43 | .update({
44 | followingCount: admin.firestore.FieldValue.increment(1)
45 | })
46 | })
47 | })
48 |
49 | exports.removeFollower = functions.firestore.document('/following/{userId}/userFollowing/{FollowingId}')
50 | .onDelete((snap, context) => {
51 | return db
52 | .collection('users')
53 | .doc(context.params.FollowingId)
54 | .update({
55 | followersCount: admin.firestore.FieldValue.increment(-1)
56 | }).then(() => {
57 | return db
58 | .collection('users')
59 | .doc(context.params.userId)
60 | .update({
61 | followingCount: admin.firestore.FieldValue.increment(-1)
62 | })
63 | })
64 | })
65 |
66 | exports.addComment = functions.firestore.document('/posts/{creatorId}/userPosts/{postId}/comments/{userId}')
67 | .onCreate((snap, context) => {
68 | return db
69 | .collection("posts")
70 | .doc(context.params.creatorId)
71 | .collection("userPosts")
72 | .doc(context.params.postId)
73 | .update({
74 | commentsCount: admin.firestore.FieldValue.increment(1)
75 | })
76 | })
77 |
--------------------------------------------------------------------------------
/admin/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `npm start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13 |
14 | The page will reload if you make edits.\
15 | You will also see any lint errors in the console.
16 |
17 | ### `npm test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `npm run build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `npm run eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35 |
36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39 |
40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `npm run build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------
/frontend/components/auth/Register.js:
--------------------------------------------------------------------------------
1 | import firebase from 'firebase';
2 | import React, { useState } from 'react';
3 | import { Button, Text, TextInput, View } from 'react-native';
4 | import { Snackbar } from 'react-native-paper';
5 | import { container, form } from '../styles';
6 |
7 | require('firebase/firestore');
8 |
9 | export default function Register(props) {
10 | const [email, setEmail] = useState('');
11 | const [password, setPassword] = useState('');
12 | const [name, setName] = useState('');
13 | const [username, setUsername] = useState('');
14 | const [isValid, setIsValid] = useState(true);
15 |
16 | const onRegister = () => {
17 | if (name.lenght == 0 || username.lenght == 0 || email.length == 0 || password.length == 0) {
18 | setIsValid({ bool: true, boolSnack: true, message: "Please fill out everything" })
19 | return;
20 | }
21 | if (password.length < 6) {
22 | setIsValid({ bool: true, boolSnack: true, message: "passwords must be at least 6 characters" })
23 | return;
24 | }
25 | if (password.length < 6) {
26 | setIsValid({ bool: true, boolSnack: true, message: "passwords must be at least 6 characters" })
27 | return;
28 | }
29 | firebase.firestore()
30 | .collection('users')
31 | .where('username', '==', username)
32 | .get()
33 | .then((snapshot) => {
34 |
35 | if (!snapshot.exist) {
36 | firebase.auth().createUserWithEmailAndPassword(email, password)
37 | .then(() => {
38 | if (snapshot.exist) {
39 | return
40 | }
41 | firebase.firestore().collection("users")
42 | .doc(firebase.auth().currentUser.uid)
43 | .set({
44 | name,
45 | email,
46 | username,
47 | image: 'default',
48 | followingCount: 0,
49 | followersCount: 0,
50 |
51 | })
52 | })
53 | .catch(() => {
54 | setIsValid({ bool: true, boolSnack: true, message: "Something went wrong" })
55 | })
56 | }
57 | }).catch(() => {
58 | setIsValid({ bool: true, boolSnack: true, message: "Something went wrong" })
59 | })
60 |
61 | }
62 |
63 | return (
64 |
65 |
66 | setUsername(username.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, '').replace(/[^a-z0-9]/gi, ''))}
72 | />
73 | setName(name)}
77 | />
78 | setEmail(email)}
82 | />
83 | setPassword(password)}
88 | />
89 |
90 |
96 |
97 |
98 | props.navigation.navigate("Login")} >
100 | Already have an account? SignIn.
101 |
102 |
103 | { setIsValid({ boolSnack: false }) }}>
107 | {isValid.message}
108 |
109 |
110 |
111 | )
112 | }
113 |
114 |
--------------------------------------------------------------------------------
/admin/src/components/Ride.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import { useLocation } from "react-router-dom";
3 | import firebase from 'firebase/app';
4 | import 'firebase/firestore';
5 | import { Paper, Avatar, Divider, CircularProgress, Button, TextField } from '@material-ui/core';
6 |
7 | export default function Ride(props) {
8 | const [user, setUser] = useState(null)
9 | const [banReason, setBanReason] = useState('')
10 | const location = useLocation();
11 |
12 | useEffect(() => {
13 | firebase.firestore()
14 | .collection("users")
15 | .doc(props.match.params.id)
16 | .onSnapshot((snapshot) => {
17 | if (snapshot.exists) {
18 | let user = snapshot.data();
19 | user.uid = snapshot.id;
20 |
21 | setUser(user);
22 | }
23 | })
24 | }, [])
25 |
26 | const banUser = () => {
27 | firebase.firestore()
28 | .collection("users")
29 | .doc(firebase.auth().currentUser.uid)
30 | .update({
31 | banned: true,
32 | banDetails: {
33 | banReason,
34 | date: firebase.firestore.FieldValue.serverTimestamp()
35 | }
36 | })
37 | }
38 | if (user == null) {
39 | return (
40 |
46 | )
47 | }
48 | return (
49 |
50 |
51 |
52 |
53 |
54 |
{user.name}
55 |
{user.username}
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
phone Number
64 |
{user.phoneNumber}
65 |
66 |
67 |
Birthday
68 |
{user.birthday}
69 |
70 |
71 |
Last Login
72 |
{user.lastLogin}
73 |
74 |
75 |
Phone Info
76 |
{user.device}
77 |
78 |
79 |
Identification
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
96 |
97 |
98 |
99 |
100 |
110 |
111 |
112 |
113 |
114 |
115 |
116 | )
117 | }
118 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | [](https://opensource.org/licenses/MIT)
3 | [](https://expo.io/)
4 | [](https://twitter.com/simcoder_here)
5 | [](https://www.instagram.com/simcoder_here/)
6 | [](https://www.youtube.com/channel/UCQ5xY26cw5Noh6poIE-VBog)
7 | [](https://www.buymeacoffee.com/simcoder)
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
Instagram Clone
17 |
18 |
19 | A Instagram clone app made with React Native and firebase
20 |
21 | Explore the docs »
22 |
23 |
24 | Report Bug
25 | ·
26 | Request Feature
27 |
28 |
29 |
30 |
31 |
32 | Table of Contents
33 |
34 | -
35 | About The Project
36 |
39 |
40 | -
41 | Getting Started
42 |
46 |
47 | - Roadmap
48 | - Contributing
49 | - Support
50 | - License
51 | - Contact
52 |
53 |
54 |
55 |
56 |
57 | ## ℹ️ About The Project
58 |
59 | 
60 |
61 | This repo contains the project made in my youtube chanel called simcoder. This project is a clone of the Instagram android app.
62 |
63 | It is made using React Native with Expo using firebase services (authentication, firestore and storage).
64 | The admin panel is made with ReactJS.
65 | The backend is all NodeJS
66 |
67 | In the [master](https://github.com/SimCoderYoutube/InstagramClone/tree/master) branch you have the redesign project which I was previously selling in my website, however you still have access to the youtube series repo in the [youtube_series](https://github.com/SimCoderYoutube/InstagramClone/tree/youtube_series)
68 |
69 | You can follow the youtube series in the following [link](https://www.youtube.com/watch?v=xE8UEX7vXVQ&list=PLxabZQCAe5fgatwOQny9wKJVs4YD6xkf1)
70 |
71 | ## 🆕 Getting Started
72 |
73 | - ### **Prerequisites**
74 |
75 | - [React Native](https://reactnative.dev/)
76 | - [Expo](https://expo.dev/)
77 | - [Firebase](https://firebase.google.com/)
78 |
79 |
80 |
81 | - ### **Installation**
82 |
83 | In order to deploy the project you'll need to follow the [wiki page](https://github.com/SimCoderYoutube/InstagramClone/wiki/Setup-your-project) dedicated to this effect.
84 |
85 | ## 🚧 Roadmap
86 |
87 | See the [open issues](https://github.com/SimCoderYoutube/InstagramClone/issues) for a list of proposed features (and known issues).
88 |
89 |
90 |
91 | ## ➕ Contributing
92 |
93 | Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**. Please check the [Wiki](https://github.com/SimCoderYoutube/InstagramClone/wiki/How-to-Contribute)
94 |
95 | ## 🌟 Show your support
96 |
97 | Give a ⭐️ if this project helped you!
98 |
99 | And don't forget to subscribe to the [youtube chanel](https://www.youtube.com/c/SimpleCoder?sub_confirmation=1)
100 |
101 | ## 📝 License
102 |
103 | Copyright © 2021 [SimCoder](https://github.com/simcoderYoutube).
104 |
105 | This project is [Apache License 2.0](https://github.com/SimCoderYoutube/InstagramClone/blob/master/LICENSE) licensed. Some of the dependencies are licensed differently.
106 |
107 |
108 |
109 | ## 👤 Contact
110 |
111 | **SimCoder**
112 |
113 | - Website: www.simcoder.com
114 | - Twitter: [@simcoder_here](https://twitter.com/simcoder_here)
115 | - Github: [@simcoderYoutube](https://github.com/simcoderYoutube)
116 | - Youtube: [SimCoder](https://www.youtube.com/channel/UCQ5xY26cw5Noh6poIE-VBog)
117 |
--------------------------------------------------------------------------------
/admin/src/components/Post.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import { useLocation } from "react-router-dom";
3 | import firebase from 'firebase/app';
4 | import 'firebase/firestore';
5 | import { Paper, Avatar, Divider, CircularProgress, Button, TextField } from '@material-ui/core';
6 | import { DataGrid } from '@material-ui/data-grid';
7 |
8 | import Chip from '@material-ui/core/Chip';
9 | import { Clear, Check, PhotoSizeSelectLargeRounded, Markunread } from '@material-ui/icons';
10 | import DoneIcon from '@material-ui/icons/Done';
11 | import { useHistory } from "react-router-dom";
12 | import { FaBeer } from 'react-icons/fa';
13 |
14 | export default function Post(props) {
15 | const [post, setPost] = useState(null)
16 | const [comments, setComments] = useState([])
17 | const [loaded, setLoaded] = useState(false)
18 | const location = useLocation();
19 | const history = useHistory();
20 |
21 | useEffect(() => {
22 | firebase.firestore()
23 | .collection("posts")
24 | .doc(props.match.params.uid)
25 | .collection('userPosts')
26 | .doc(props.match.params.id)
27 | .onSnapshot((snapshot) => {
28 | if (snapshot.exists) {
29 | let result = snapshot.data();
30 | result.id = snapshot.id;
31 | setPost(result);
32 | }
33 | })
34 | }, [])
35 |
36 | useEffect(() => {
37 | if (post == null) {
38 | return;
39 | }
40 | firebase.firestore()
41 | .collection("posts")
42 | .doc(props.match.params.uid)
43 | .collection("userPosts")
44 | .doc(props.match.params.id)
45 | .collection('comments')
46 | .onSnapshot((snapshot) => {
47 | let result = snapshot.docs.map(doc => {
48 | const data = doc.data();
49 | const id = doc.id;
50 | return { id, ...data }
51 | })
52 | setComments(result)
53 | setLoaded(true)
54 | })
55 | }, [post])
56 |
57 | const deleteComment = (id) => {
58 | firebase.firestore()
59 | .collection("posts")
60 | .doc(props.match.params.uid)
61 | .collection("userPosts")
62 | .doc(props.match.params.id)
63 | .collection('comments')
64 | .doc(id)
65 | .delete()
66 | }
67 | const deletePost = () => {
68 | firebase.firestore()
69 | .collection("posts")
70 | .doc(props.match.params.uid)
71 | .collection("userPosts")
72 | .doc(props.match.params.id)
73 | .delete()
74 |
75 | firebase.firestore()
76 | .collection("feed")
77 | .doc(post.id)
78 | .delete()
79 | }
80 |
81 |
82 | const columns = [
83 | { field: 'id', headerName: 'ID', width: 280 },
84 | { field: 'text', headerName: 'text', width: 400 },
85 | {
86 | field: 'delete', headerName: 'delete', width: 150,
87 | renderCell: (params) => (
88 |
89 |
90 |
93 |
94 |
95 | ),
96 |
97 | },
98 | {
99 | field: 'user', headerName: 'user', width: 150,
100 | renderCell: (params) => (
101 |
102 |
103 |
106 |
107 |
108 | ),
109 |
110 | },
111 | ];
112 |
113 | if (!loaded) {
114 | return (
115 |
121 | )
122 | }
123 | const date = new Date(post['creation'].seconds * 1000)
124 | return (
125 |
126 |
127 |
128 |
129 |
Caption
130 |
{post.caption}
131 |
132 |
133 |
Date
134 |
{date.toString()}
135 |
136 |
137 |
138 |
141 |
142 |
143 |
144 |
145 | ({
146 | ...column,
147 | disableClickEventBubbling: true,
148 | }))} />
149 |
150 |
151 | )
152 | }
153 |
--------------------------------------------------------------------------------
/frontend/App.js:
--------------------------------------------------------------------------------
1 | import { getFocusedRouteNameFromRoute, NavigationContainer } from '@react-navigation/native';
2 | import { createStackNavigator } from '@react-navigation/stack';
3 | import 'expo-asset';
4 | import * as firebase from 'firebase';
5 | import _ from 'lodash';
6 | import React, { Component } from 'react';
7 | import { Image, LogBox } from 'react-native';
8 | import { Provider } from 'react-redux';
9 | import { applyMiddleware, createStore } from 'redux';
10 | import thunk from 'redux-thunk';
11 | import LoginScreen from './components/auth/Login';
12 | import RegisterScreen from './components/auth/Register';
13 | import MainScreen from './components/Main';
14 | import SaveScreen from './components/main/add/Save';
15 | import ChatScreen from './components/main/chat/Chat';
16 | import ChatListScreen from './components/main/chat/List';
17 | import CommentScreen from './components/main/post/Comment';
18 | import PostScreen from './components/main/post/Post';
19 | import EditScreen from './components/main/profile/Edit';
20 | import ProfileScreen from './components/main/profile/Profile';
21 | import BlockedScreen from './components/main/random/Blocked';
22 | import { container } from './components/styles';
23 | import rootReducer from './redux/reducers';
24 |
25 | const store = createStore(rootReducer, applyMiddleware(thunk))
26 |
27 | LogBox.ignoreLogs(['Setting a timer']);
28 | const _console = _.clone(console);
29 | console.warn = message => {
30 | if (message.indexOf('Setting a timer') <= -1) {
31 | _console.warn(message);
32 | }
33 | };
34 |
35 | const firebaseConfig = {
36 | apiKey: "****",
37 | authDomain: "****",
38 | databaseURL: "****",
39 | projectId: "****",
40 | storageBucket: "****",
41 | messagingSenderId: "****",
42 | appId: "****",
43 | measurementId: "****"
44 | };
45 |
46 | const logo = require('./assets/logo.png')
47 |
48 | if (firebase.apps.length === 0) {
49 | firebase.initializeApp(firebaseConfig)
50 | }
51 |
52 | const Stack = createStackNavigator();
53 |
54 | export class App extends Component {
55 | constructor(props) {
56 | super()
57 | this.state = {
58 | loaded: false,
59 | }
60 | }
61 |
62 | componentDidMount() {
63 | firebase.auth().onAuthStateChanged((user) => {
64 | if (!user) {
65 | this.setState({
66 | loggedIn: false,
67 | loaded: true,
68 | })
69 | } else {
70 | this.setState({
71 | loggedIn: true,
72 | loaded: true,
73 | })
74 | }
75 | })
76 | }
77 | render() {
78 | const { loggedIn, loaded } = this.state;
79 | if (!loaded) {
80 | return (
81 |
82 | )
83 | }
84 |
85 | if (!loggedIn) {
86 | return (
87 |
88 |
89 |
90 |
91 |
92 |
93 | );
94 | }
95 |
96 | return (
97 |
98 |
99 |
100 | {
101 | const routeName = getFocusedRouteNameFromRoute(route) ?? 'Feed';
102 |
103 | switch (routeName) {
104 | case 'Camera': {
105 | return {
106 | headerTitle: 'Camera',
107 | };
108 | }
109 | case 'chat': {
110 | return {
111 | headerTitle: 'Chat',
112 | };
113 | }
114 | case 'Profile': {
115 | return {
116 | headerTitle: 'Profile',
117 | };
118 | }
119 | case 'Search': {
120 | return {
121 | headerTitle: 'Search',
122 | };
123 | }
124 | case 'Feed':
125 | default: {
126 | return {
127 | headerTitle: 'Instagram',
128 | };
129 | }
130 | }
131 | }}
132 | />
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 | )
147 | }
148 | }
149 |
150 | export default App
151 |
--------------------------------------------------------------------------------
/admin/src/components/User.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react'
2 | import { useHistory, useLocation } from "react-router-dom";
3 | import firebase from 'firebase/app';
4 | import 'firebase/firestore';
5 | import { Paper, Avatar, Divider, CircularProgress, Button, TextField } from '@material-ui/core';
6 | import { DataGrid } from '@material-ui/data-grid';
7 |
8 | export default function User(props) {
9 | const [user, setUser] = useState([])
10 | const [banReason, setBanReason] = useState('')
11 | const location = useLocation();
12 | const [posts, setPosts] = useState([])
13 | useEffect(() => {
14 | firebase.firestore()
15 | .collection("posts")
16 | .doc(props.match.params.id)
17 | .collection("userPosts")
18 | .onSnapshot((snapshot) => {
19 | let result = snapshot.docs.map(doc => {
20 | const data = doc.data();
21 | const id = doc.id;
22 | return { id, ...data }
23 | })
24 | setPosts(result)
25 | })
26 | }, [])
27 | useEffect(() => {
28 | firebase.firestore()
29 | .collection("users")
30 | .doc(props.match.params.id)
31 | .onSnapshot((snapshot) => {
32 | if (snapshot.exists) {
33 | let user = snapshot.data();
34 | user.uid = snapshot.id;
35 |
36 | setUser(user);
37 | }
38 | })
39 | }, [])
40 |
41 | const banUser = () => {
42 | firebase.firestore()
43 | .collection("users")
44 | .doc(props.match.params.id)
45 | .update({
46 | banned: true,
47 | banDetails: {
48 | banReason: banReason.target.value,
49 | date: firebase.firestore.FieldValue.serverTimestamp()
50 | }
51 | })
52 | }
53 | const unbanUser = () => {
54 | firebase.firestore()
55 | .collection("users")
56 | .doc(props.match.params.id)
57 | .update({
58 | banned: false,
59 | banDetails: {}
60 | })
61 | }
62 | const history = useHistory();
63 | const columns = [
64 | { field: 'caption', headerName: 'caption', width: 400 },
65 |
66 | { field: 'likesCount', headerName: 'likesCount', width: 130 },
67 | { field: 'commentsCount', headerName: 'commentsCount', width: 130 },
68 | {
69 | field: 'creation', headerName: 'creation', width: 200,
70 | valueGetter: (params) =>
71 | `${new Date(params.value.seconds * 1000)}`
72 | },
73 | {
74 | field: 'link', headerName: 'Detail', width: 150,
75 | renderCell: (params) => (
76 |
77 |
80 |
81 | ),
82 |
83 | },
84 | ];
85 |
86 | if (user.length == 0) {
87 | return (
88 |
94 | )
95 | }
96 | return (
97 |
98 |
99 |
100 |
101 |
102 |
{user.name}
103 |
{user.username}
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
email
112 |
{user.email}
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 | {!user.banned ?
121 |
122 |
132 |
133 |
134 |
135 |
136 | :
137 |
138 |
139 |
140 |
141 | }
142 |
143 |
144 |
145 | ({
146 | ...column,
147 | disableClickEventBubbling: true,
148 | }))} />
149 |
150 |
151 | )
152 | }
--------------------------------------------------------------------------------
/frontend/components/main/profile/Edit.js:
--------------------------------------------------------------------------------
1 | import { Feather, FontAwesome5 } from '@expo/vector-icons';
2 | import * as ImagePicker from 'expo-image-picker';
3 | import * as Updates from 'expo-updates';
4 | import firebase from 'firebase';
5 | import React, { useEffect, useLayoutEffect, useState } from 'react';
6 | import { Button, Image, Text, TextInput, TouchableOpacity, View } from 'react-native';
7 | import { connect } from 'react-redux';
8 | import { bindActionCreators } from 'redux';
9 | import { updateUserFeedPosts } from '../../../redux/actions/index';
10 | import { container, form, navbar, text, utils } from '../../styles';
11 |
12 | require('firebase/firestore')
13 |
14 |
15 | function Edit(props) {
16 | const [name, setName] = useState(props.currentUser.name);
17 | const [description, setDescription] = useState("");
18 | const [image, setImage] = useState(props.currentUser.image);
19 | const [imageChanged, setImageChanged] = useState(false);
20 | const [hasGalleryPermission, setHasGalleryPermission] = useState(null);
21 |
22 | const onLogout = async () => {
23 | firebase.auth().signOut();
24 | Updates.reloadAsync()
25 | }
26 |
27 |
28 | useEffect(() => {
29 | (async () => {
30 | if (props.currentUser.description !== undefined) {
31 | setDescription(props.currentUser.description)
32 | }
33 |
34 | })();
35 | }, []);
36 |
37 | useLayoutEffect(() => {
38 | props.navigation.setOptions({
39 | headerRight: () => (
40 |
41 | { console.log({ name, description }); Save() }} />
42 | ),
43 | });
44 | }, [props.navigation, name, description, image, imageChanged]);
45 |
46 |
47 | const pickImage = async () => {
48 | if (true) {
49 | let result = await ImagePicker.launchImageLibraryAsync({
50 | mediaTypes: ImagePicker.MediaTypeOptions.Images,
51 | allowsEditing: true,
52 | aspect: [1, 1],
53 | quality: 1,
54 | });
55 |
56 | if (!result.cancelled) {
57 | setImage(result.uri);
58 | setImageChanged(true);
59 | }
60 | }
61 | };
62 |
63 |
64 | const Save = async () => {
65 | if (imageChanged) {
66 | const uri = image;
67 | const childPath = `profile/${firebase.auth().currentUser.uid}`;
68 |
69 | const response = await fetch(uri);
70 | const blob = await response.blob();
71 |
72 | const task = firebase
73 | .storage()
74 | .ref()
75 | .child(childPath)
76 | .put(blob);
77 |
78 | const taskProgress = snapshot => {
79 | console.log(`transferred: ${snapshot.bytesTransferred}`)
80 | }
81 |
82 | const taskCompleted = () => {
83 | task.snapshot.ref.getDownloadURL().then((snapshot) => {
84 |
85 | firebase.firestore().collection("users")
86 | .doc(firebase.auth().currentUser.uid)
87 | .update({
88 | name,
89 | description,
90 | image: snapshot,
91 | }).then(() => {
92 | props.updateUserFeedPosts();
93 | props.navigation.goBack()
94 |
95 | })
96 | })
97 | }
98 |
99 | const taskError = snapshot => {
100 | console.log(snapshot)
101 | }
102 |
103 | task.on("state_changed", taskProgress, taskError, taskCompleted);
104 | } else {
105 | saveData({
106 | name,
107 | description,
108 | })
109 | }
110 | }
111 |
112 | const saveData = (data) => {
113 | firebase.firestore().collection("users")
114 | .doc(firebase.auth().currentUser.uid)
115 | .update(data).then(() => {
116 | props.updateUserFeedPosts();
117 |
118 | props.navigation.goBack()
119 | })
120 | }
121 |
122 | return (
123 |
124 |
125 | pickImage()} >
126 | {image == 'default' ?
127 | (
128 |
131 | )
132 | :
133 | (
134 |
140 | )
141 | }
142 | Change Profile Photo
143 |
144 |
145 | setName(name)}
150 | />
151 | { setDescription(description); }}
157 | />
158 |
162 |
163 | )
164 | }
165 |
166 | const mapStateToProps = (store) => ({
167 | currentUser: store.userState.currentUser,
168 | })
169 |
170 | const mapDispatchProps = (dispatch) => bindActionCreators({ updateUserFeedPosts }, dispatch);
171 |
172 | export default connect(mapStateToProps, mapDispatchProps)(Edit);
173 |
--------------------------------------------------------------------------------
/frontend/components/styles.js:
--------------------------------------------------------------------------------
1 |
2 | import { StyleSheet } from 'react-native'
3 | const utils = StyleSheet.create({
4 | centerHorizontal: {
5 | alignItems: 'center',
6 | },
7 | marginBottom: {
8 | marginBottom: 20,
9 | },
10 | marginBottomBar: {
11 | marginBottom: 330,
12 | },
13 | marginBottomSmall: {
14 | marginBottom: 10,
15 | },
16 | profileImageBig: {
17 | width: 80,
18 | height: 80,
19 | borderRadius: 80 / 2,
20 | },
21 | profileImage: {
22 | marginRight: 15,
23 | width: 50,
24 | height: 50,
25 | borderRadius: 50 / 2,
26 | },
27 | profileImageSmall: {
28 | marginRight: 15,
29 | width: 35,
30 | height: 35,
31 | borderRadius: 35 / 2,
32 | },
33 | searchBar: {
34 | backgroundColor: 'whitesmoke',
35 | color: 'grey',
36 | paddingLeft: 10,
37 | borderRadius: 8,
38 | height: 40,
39 | marginTop: -5
40 | },
41 | justifyCenter: {
42 | justifyContent: 'center',
43 | },
44 | alignItemsCenter: {
45 | alignItems: 'center'
46 | },
47 | padding15: {
48 | paddingTop: 15,
49 | paddingRight: 15,
50 | paddingLeft: 15,
51 | },
52 | padding10Top: {
53 | paddingTop: 10
54 |
55 | },
56 | padding10: {
57 | padding: 10
58 | },
59 | margin15: {
60 | margin: 15
61 | },
62 | padding10Sides: {
63 | paddingRight: 10,
64 | paddingLeft: 10,
65 | },
66 | margin15Left: {
67 | marginLeft: 15,
68 | },
69 | margin15Right: {
70 | marginRight: 15,
71 | },
72 | margin5Bottom: {
73 | marginBottom: 5,
74 | },
75 | backgroundWhite: {
76 | backgroundColor: 'white',
77 | },
78 | borderTopGray: {
79 | borderTopWidth: 1,
80 | borderColor: 'lightgrey'
81 | },
82 | borderWhite: {
83 | borderLeftWidth: 2,
84 | borderRightWidth: 2,
85 | borderTopWidth: 2,
86 | borderColor: 'white'
87 | },
88 | buttonOutlined: {
89 | padding: 8,
90 | color: 'white',
91 | borderWidth: 1,
92 | borderColor: 'lightgrey',
93 | borderRadius: 8,
94 | textAlign: 'center',
95 | },
96 |
97 | fixedRatio: {
98 | flex: 1,
99 | aspectRatio: 1
100 | }
101 | })
102 | const navbar = StyleSheet.create({
103 |
104 | image: {
105 | padding: 20
106 | },
107 | custom: {
108 | marginTop: 30,
109 | height: 60,
110 | backgroundColor: 'white',
111 | padding: 15,
112 | borderBottomWidth: 1,
113 | borderColor: 'lightgrey'
114 | },
115 |
116 | title: {
117 | fontWeight: '700',
118 | fontSize: 20//'larger',
119 | }
120 | })
121 | const container = StyleSheet.create({
122 | container: {
123 | flex: 1,
124 | },
125 | camera: {
126 | flex: 1,
127 | flexDirection: 'row'
128 | },
129 | input: {
130 | flexWrap: "wrap"
131 | },
132 | containerPadding: {
133 | flex: 1,
134 | padding: 15
135 | },
136 | center: {
137 | flex: 1,
138 | },
139 | horizontal: {
140 | flexDirection: 'row',
141 | display: 'flex',
142 | },
143 | form: {
144 | flex: 1,
145 | margin: 25
146 | },
147 | profileInfo: {
148 | padding: 25,
149 | flexDirection: 'column',
150 | },
151 | row: {
152 | flexDirection: 'row',
153 | alignItems: 'center',
154 | height: 'auto',
155 |
156 | },
157 | formCenter: {
158 | justifyContent: 'center',
159 | flex: 1,
160 | margin: 25
161 | },
162 | containerImage: {
163 | flex: 1 / 3
164 |
165 | },
166 | image: {
167 | aspectRatio: 1 / 1,
168 | },
169 | fillHorizontal: {
170 | flexGrow: 1,
171 | paddingBottom: 0
172 | },
173 | imageSmall: {
174 | aspectRatio: 1 / 1,
175 | height: 70
176 | },
177 | gallery: {
178 |
179 | borderWidth: 1,
180 | borderColor: 'gray',
181 | },
182 | splash: {
183 | padding: 200,
184 | height: '100%',
185 | width: '100%'
186 | },
187 | chatRight: {
188 | margin: 10,
189 | marginBottom: 10,
190 | backgroundColor: 'dodgerblue',
191 | padding: 10,
192 | borderRadius: 8,
193 | alignSelf: 'flex-end'
194 |
195 | },
196 | chatLeft: {
197 | margin: 10,
198 | marginBottom: 10,
199 | backgroundColor: 'grey',
200 | padding: 10,
201 | borderRadius: 8,
202 | alignItems: 'flex-end',
203 | textAlign: 'right',
204 | alignSelf: 'flex-start'
205 | }
206 | })
207 |
208 | const form = StyleSheet.create({
209 | textInput: {
210 | marginBottom: 10,
211 | borderColor: 'gray',
212 | backgroundColor: 'whitesmoke',
213 | padding: 10,
214 | borderWidth: 1,
215 | borderRadius: 8
216 | },
217 | bottomButton: {
218 | alignContent: 'center',
219 | borderTopColor: 'gray',
220 | borderTopWidth: 1,
221 | padding: 10,
222 | textAlign: 'center',
223 | },
224 | roundImage: {
225 | width: 100,
226 | height: 100,
227 | borderRadius: 100 / 2
228 | }
229 |
230 | })
231 |
232 | const text = StyleSheet.create({
233 | center: {
234 | textAlign: 'center',
235 | },
236 | notAvailable: {
237 | textAlign: 'center',
238 | fontWeight: '700',//'bolder',
239 | fontSize: 20//'large',
240 | },
241 | profileDescription: {
242 | fontWeight: '300'
243 | },
244 | changePhoto: {
245 | marginTop: 5,
246 | color: 'deepskyblue',
247 | },
248 | deepskyblue: {
249 | color: 'deepskyblue',
250 | },
251 | username: {
252 | fontWeight: '600',
253 | color: 'black',
254 | },
255 | name: {
256 | color: 'grey',
257 | },
258 | bold: {
259 | fontWeight: '700',
260 | },
261 | large: {
262 | fontSize: 20//'large'
263 | },
264 | small: {
265 | fontSize: 10//'large'
266 | },
267 | medium: {
268 | fontSize: 15, //'large'
269 | marginBottom: 10
270 | },
271 | grey: {
272 | color: 'grey'
273 | },
274 | green: {
275 | color: 'lightgreen'
276 | },
277 | white: {
278 | color: 'white'
279 | },
280 | whitesmoke: {
281 | color: 'whitesmoke'
282 | }
283 |
284 |
285 |
286 | })
287 |
288 | export { container, form, text, utils, navbar }
--------------------------------------------------------------------------------
/admin/src/components/Home.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import clsx from 'clsx';
3 | import { makeStyles, useTheme } from '@material-ui/core/styles';
4 | import Drawer from '@material-ui/core/Drawer';
5 | import AppBar from '@material-ui/core/AppBar';
6 | import Toolbar from '@material-ui/core/Toolbar';
7 | import List from '@material-ui/core/List';
8 | import CssBaseline from '@material-ui/core/CssBaseline';
9 | import Typography from '@material-ui/core/Typography';
10 | import Divider from '@material-ui/core/Divider';
11 | import IconButton from '@material-ui/core/IconButton';
12 | import MenuIcon from '@material-ui/icons/Menu';
13 | import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
14 | import ChevronRightIcon from '@material-ui/icons/ChevronRight';
15 | import ListItem from '@material-ui/core/ListItem';
16 | import ListItemIcon from '@material-ui/core/ListItemIcon';
17 | import ListItemText from '@material-ui/core/ListItemText';
18 | import InboxIcon from '@material-ui/icons/MoveToInbox';
19 | import MailIcon from '@material-ui/icons/Mail';
20 | import { BrowserRouter as Router, Link, Route } from 'react-router-dom'
21 | import Users from './Users';
22 | import User from './User';
23 | import Post from './Post';
24 | import { useHistory } from "react-router-dom";
25 |
26 | const drawerWidth = 240;
27 |
28 | const useStyles = makeStyles((theme) => ({
29 | root: {
30 | display: 'flex',
31 | },
32 | appBar: {
33 | zIndex: theme.zIndex.drawer + 1,
34 | transition: theme.transitions.create(['width', 'margin'], {
35 | easing: theme.transitions.easing.sharp,
36 | duration: theme.transitions.duration.leavingScreen,
37 | }),
38 | },
39 | appBarShift: {
40 | marginLeft: drawerWidth,
41 | width: `calc(100% - ${drawerWidth}px)`,
42 | transition: theme.transitions.create(['width', 'margin'], {
43 | easing: theme.transitions.easing.sharp,
44 | duration: theme.transitions.duration.enteringScreen,
45 | }),
46 | },
47 | menuButton: {
48 | marginRight: 36,
49 | },
50 | hide: {
51 | display: 'none',
52 | },
53 | drawer: {
54 | width: drawerWidth,
55 | flexShrink: 0,
56 | whiteSpace: 'nowrap',
57 | },
58 | drawerOpen: {
59 | width: drawerWidth,
60 | transition: theme.transitions.create('width', {
61 | easing: theme.transitions.easing.sharp,
62 | duration: theme.transitions.duration.enteringScreen,
63 | }),
64 | },
65 | drawerClose: {
66 | transition: theme.transitions.create('width', {
67 | easing: theme.transitions.easing.sharp,
68 | duration: theme.transitions.duration.leavingScreen,
69 | }),
70 | overflowX: 'hidden',
71 | width: theme.spacing(7) + 1,
72 | [theme.breakpoints.up('sm')]: {
73 | width: theme.spacing(9) + 1,
74 | },
75 | },
76 | toolbar: {
77 | display: 'flex',
78 | alignItems: 'center',
79 | justifyContent: 'flex-end',
80 | padding: theme.spacing(0, 1),
81 | // necessary for content to be below app bar
82 | ...theme.mixins.toolbar,
83 | },
84 | content: {
85 | flexGrow: 1,
86 | padding: theme.spacing(3),
87 | },
88 | }));
89 |
90 | export default function Home() {
91 | const classes = useStyles();
92 | const theme = useTheme();
93 | const [open, setOpen] = React.useState(false);
94 | const history = useHistory();
95 |
96 | const handleDrawerOpen = () => {
97 | setOpen(true);
98 | };
99 |
100 | const handleDrawerClose = () => {
101 | setOpen(false);
102 | };
103 | return (
104 |
105 |
106 |
107 |
108 |
114 |
115 |
124 |
125 |
126 |
127 | FreeRide Admin
128 |
129 |
130 |
131 |
144 |
145 |
146 | {theme.direction === 'rtl' ? : }
147 |
148 |
149 |
150 |
151 | {['Users'].map((text, index) => (
152 |
153 |
154 | {index % 2 === 0 ? : }
155 |
156 |
157 |
158 | ))}
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 | );
173 | }
--------------------------------------------------------------------------------
/frontend/components/main/post/Feed.js:
--------------------------------------------------------------------------------
1 | import firebase from 'firebase'
2 | import React, { useEffect, useRef, useState } from 'react'
3 | import { FlatList, RefreshControl, Text, View } from 'react-native'
4 | import BottomSheet from 'react-native-bottomsheet-reanimated'
5 | import { TouchableOpacity } from 'react-native-gesture-handler'
6 | import { Divider, Snackbar } from 'react-native-paper'
7 | import { connect } from 'react-redux'
8 | import { bindActionCreators } from 'redux'
9 | import { deletePost, fetchFeedPosts, reload, sendNotification } from '../../../redux/actions/index'
10 | import { container, utils } from '../../styles'
11 | import Post from './Post'
12 | require('firebase/firestore')
13 |
14 | function Feed(props) {
15 | const [posts, setPosts] = useState([]);
16 | const [refreshing, setRefreshing] = useState(false)
17 | const [unmutted, setUnmutted] = useState(null)
18 | const [inViewPort, setInViewPort] = useState(0)
19 | const [sheetRef, setSheetRef] = useState(useRef(null))
20 | const [modalShow, setModalShow] = useState({ visible: false, item: null })
21 | const [isValid, setIsValid] = useState(true);
22 |
23 | useEffect(() => {
24 | if (props.usersFollowingLoaded == props.following.length && props.following.length !== 0) {
25 | props.feed.sort(function (x, y) {
26 | return y.creation.toDate() - x.creation.toDate();
27 | })
28 |
29 | setPosts(props.feed);
30 | setRefreshing(false)
31 | for (let i = 0; i < props.feed.length; i++) {
32 | if (props.feed[i].type == 0) {
33 | setUnmutted(i)
34 | return;
35 | }
36 | }
37 | }
38 | props.navigation.setParams({ param: "value" })
39 |
40 | }, [props.usersFollowingLoaded, props.feed])
41 |
42 | const onViewableItemsChanged = useRef(({ viewableItems, changed }) => {
43 | if (changed && changed.length > 0) {
44 | setInViewPort(changed[0].index);
45 | }
46 | })
47 |
48 |
49 |
50 |
51 | if (posts.length == 0) {
52 | return ()
53 | }
54 |
55 | if (sheetRef.current !== null) {
56 | if (modalShow.visible) {
57 | sheetRef.snapTo(0)
58 | } else {
59 | sheetRef.snapTo(1)
60 | }
61 | }
62 | return (
63 |
64 |
65 | {
70 | setRefreshing(true);
71 | props.reload()
72 | }}
73 | />
74 | }
75 | onViewableItemsChanged={onViewableItemsChanged.current}
76 | viewabilityConfig={{
77 | waitForInteraction: false,
78 | viewAreaCoveragePercentThreshold: 70
79 | }}
80 | numColumns={1}
81 | horizontal={false}
82 | data={posts}
83 | keyExtractor={(item, index) => index.toString()}
84 |
85 | renderItem={({ item, index }) => (
86 |
87 |
88 |
89 | )}
90 | />
91 |
92 |
109 |
110 | {modalShow.item != null ?
111 |
112 | {
114 | props.navigation.navigate("ProfileOther", { uid: modalShow.item.user.uid, username: undefined });
115 | setModalShow({ visible: false, item: null });
116 | }}>
117 | Profile
118 |
119 |
120 | {modalShow.item.creator == firebase.auth().currentUser.uid ?
121 | {
123 | props.deletePost(modalShow.item).then(() => {
124 | setRefreshing(true);
125 | props.reload()
126 | })
127 | setModalShow({ visible: false, item: null });
128 | }}>
129 | Delete
130 |
131 | : null}
132 |
133 |
134 | setModalShow({ visible: false, item: null })}>
135 | Cancel
136 |
137 |
138 | : null}
139 |
140 |
141 | }
142 | />
143 | { setIsValid({ boolSnack: false }) }}>
147 | {isValid.message}
148 |
149 |
150 |
151 | )
152 | }
153 |
154 |
155 | const mapStateToProps = (store) => ({
156 | currentUser: store.userState.currentUser,
157 | following: store.userState.following,
158 | feed: store.usersState.feed,
159 | usersFollowingLoaded: store.usersState.usersFollowingLoaded,
160 |
161 |
162 | })
163 |
164 | const mapDispatchProps = (dispatch) => bindActionCreators({ reload, sendNotification, fetchFeedPosts, deletePost }, dispatch);
165 |
166 | export default connect(mapStateToProps, mapDispatchProps)(Feed);
167 |
--------------------------------------------------------------------------------
/frontend/components/Main.js:
--------------------------------------------------------------------------------
1 | import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
2 | import * as Notifications from 'expo-notifications';
3 | import firebase from 'firebase';
4 | import React, { useEffect, useState } from 'react';
5 | import { View } from 'react-native';
6 | import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
7 | import { connect } from 'react-redux';
8 | import { bindActionCreators } from 'redux';
9 | import { reload } from '../redux/actions/index';
10 | import CameraScreen from './main/add/Camera';
11 | import ChatListScreen from './main/chat/List';
12 | import FeedScreen from './main/post/Feed';
13 | import ProfileScreen from './main/profile/Profile';
14 | import SearchScreen from './main/profile/Search';
15 |
16 |
17 | const Tab = createMaterialBottomTabNavigator();
18 |
19 | function Main(props) {
20 | const [unreadChats, setUnreadChats] = useState(false)
21 | const [lastNot, setLastNot] = useState(false)
22 |
23 | const lastNotificationResponse = Notifications.useLastNotificationResponse();
24 |
25 |
26 | if (lastNotificationResponse != null && lastNotificationResponse != lastNot) {
27 | setLastNot(lastNotificationResponse)
28 | switch (lastNotificationResponse.notification.request.content.data.type) {
29 | case 0:
30 | props.navigation.navigate("Post", { item: lastNotificationResponse.notification.request.content.data.postId, user: lastNotificationResponse.notification.request.content.data.user, notification: true })
31 | break;
32 | case 1:
33 | props.navigation.navigate("Chat", { user: lastNotificationResponse.notification.request.content.data.user, notification: true })
34 | break;
35 | case 2:
36 | props.navigation.navigate("ProfileOther", { uid: lastNotificationResponse.notification.request.content.data.user, username: undefined, notification: true })
37 | break;
38 | }
39 | }
40 | useEffect(() => {
41 | props.reload();
42 | Notifications.addNotificationResponseReceivedListener((notification) => {
43 | switch (notification.notification.request.content.data.type) {
44 | case "post":
45 | props.navigation.navigate("Post", { item: notification.notification.request.content.data.postId, user: notification.notification.request.content.data.user, notification: true })
46 | break;
47 | case "chat":
48 | props.navigation.navigate("Chat", { user: notification.notification.request.content.data.user, notification: true })
49 | break;
50 | case "profile":
51 | props.navigation.navigate("ProfileOther", { uid: notification.notification.request.content.data.user, username: undefined, notification: true })
52 | break;
53 | }
54 | });
55 |
56 |
57 | }, [])
58 |
59 | useEffect(() => {
60 | if (props.currentUser != null) {
61 | if (props.currentUser.banned) {
62 | props.navigation.navigate("Blocked")
63 | }
64 | }
65 | setUnreadChats(false)
66 | for (let i = 0; i < props.chats.length; i++) {
67 | if (!props.chats[i][firebase.auth().currentUser.uid]) {
68 |
69 | setUnreadChats(true)
70 | }
71 | }
72 | }, [props.currentUser, props.chats])
73 |
74 | if (props.currentUser == null) {
75 | return ()
76 | }
77 |
78 | return (
79 |
80 |
89 | (
92 |
93 | ),
94 | }} />
95 | (
99 |
100 | ),
101 | }} />
102 | (
105 |
106 | ),
107 | }} />
108 | (
111 |
112 |
113 |
114 | {unreadChats ?
115 |
116 |
117 | :
118 | null
119 | }
120 |
121 |
122 |
123 |
124 | ),
125 | }} />
126 | ({
128 | tabPress: event => {
129 | event.preventDefault();
130 | navigation.navigate("Profile", { uid: firebase.auth().currentUser.uid })
131 | }
132 | })}
133 | options={{
134 | tabBarIcon: ({ color, size }) => (
135 |
136 | ),
137 | }} />
138 |
139 |
140 |
141 | )
142 | }
143 |
144 | const mapStateToProps = (store) => ({
145 | currentUser: store.userState.currentUser,
146 | chats: store.userState.chats,
147 | friendsRequestsReceived: store.userState.friendsRequestsReceived,
148 | })
149 | const mapDispatchProps = (dispatch) => bindActionCreators({ reload }, dispatch);
150 |
151 | export default connect(mapStateToProps, mapDispatchProps)(Main);
152 |
--------------------------------------------------------------------------------
/frontend/components/main/post/Comment.js:
--------------------------------------------------------------------------------
1 | import { FontAwesome5 } from '@expo/vector-icons';
2 | import firebase from 'firebase';
3 | import React, { useEffect, useState } from 'react';
4 | import { FlatList, Image, Text, TextInput, TouchableOpacity, View } from 'react-native';
5 | import { connect } from 'react-redux';
6 | import { bindActionCreators } from 'redux';
7 | import { fetchUsersData, sendNotification } from '../../../redux/actions/index';
8 | import { container, text, utils } from '../../styles';
9 | import { timeDifference } from '../../utils';
10 |
11 | require('firebase/firestore')
12 |
13 |
14 | function Comment(props) {
15 | const [comments, setComments] = useState([])
16 | const [postId, setPostId] = useState("")
17 | const [input, setInput] = useState("")
18 | const [refresh, setRefresh] = useState(false)
19 | const [textInput, setTextInput] = useState(null)
20 |
21 | useEffect(() => {
22 | getComments();
23 | }, [props.route.params.postId, props.users, refresh])
24 |
25 | const matchUserToComment = (comments) => {
26 | for (let i = 0; i < comments.length; i++) {
27 | if (comments[i].hasOwnProperty('user')) {
28 | continue;
29 | }
30 |
31 | const user = props.users.find(x => x.uid === comments[i].creator)
32 | if (user == undefined) {
33 | props.fetchUsersData(comments[i].creator, false)
34 | } else {
35 | comments[i].user = user
36 | }
37 | }
38 | setComments(comments)
39 | setRefresh(false)
40 | }
41 | const getComments = () => {
42 | if (props.route.params.postId !== postId || refresh) {
43 | firebase.firestore()
44 | .collection('posts')
45 | .doc(props.route.params.uid)
46 | .collection('userPosts')
47 | .doc(props.route.params.postId)
48 | .collection('comments')
49 | .orderBy('creation', 'desc')
50 | .get()
51 | .then((snapshot) => {
52 | let comments = snapshot.docs.map(doc => {
53 | const data = doc.data();
54 | const id = doc.id;
55 | return { id, ...data }
56 | })
57 | matchUserToComment(comments)
58 | })
59 | setPostId(props.route.params.postId)
60 | } else {
61 | matchUserToComment(comments)
62 | }
63 | }
64 | const onCommentSend = () => {
65 | const textToSend = input;
66 |
67 | if (input.length == 0) {
68 | return;
69 | }
70 | setInput("")
71 |
72 | textInput.clear()
73 | firebase.firestore()
74 | .collection('posts')
75 | .doc(props.route.params.uid)
76 | .collection('userPosts')
77 | .doc(props.route.params.postId)
78 | .collection('comments')
79 | .add({
80 | creator: firebase.auth().currentUser.uid,
81 | text: textToSend,
82 | creation: firebase.firestore.FieldValue.serverTimestamp()
83 |
84 | }).then(() => {
85 |
86 | setRefresh(true)
87 | })
88 |
89 | firebase.firestore()
90 | .collection("users")
91 | .doc(props.route.params.uid)
92 | .get()
93 | .then((snapshot) => {
94 | props.sendNotification(snapshot.data().notificationToken, "New Comment", `${props.currentUser.name} Commented on your post`, { type: 0, user: firebase.auth().currentUser.uid })
95 | })
96 |
97 |
98 | }
99 |
100 | return (
101 |
102 | (
107 |
108 | {item.user !== undefined ?
109 |
110 | {item.user.image == 'default' ?
111 | (
112 | props.navigation.navigate("Profile", { uid: item.user.uid, username: undefined })} />
116 |
117 |
118 | )
119 | :
120 | (
121 | props.navigation.navigate("Profile", { uid: item.user.uid, username: undefined })} />
127 |
128 | )
129 | }
130 |
131 |
132 |
133 | props.navigation.navigate("Profile", { uid: item.user.uid, username: undefined })}>
135 | {item.user.name}
136 |
137 | {" "} {item.text}
138 |
139 |
141 | {timeDifference(new Date(), item.creation.toDate())}
142 |
143 |
144 |
145 |
146 |
147 | : null}
148 |
149 |
150 |
151 | )
152 | }
153 | />
154 |
155 | < View style={[container.horizontal, utils.padding10, utils.alignItemsCenter, utils.backgroundWhite]} >
156 | {
157 | props.currentUser.image == 'default' ?
158 | (
159 |
162 |
163 | )
164 | :
165 | (
166 |
172 | )
173 | }
174 |
175 | < TextInput
176 | ref={input => { setTextInput(input) }}
177 | value={input}
178 | multiline={true}
179 | style={[container.fillHorizontal, container.input, container.container]}
180 | placeholder='comment...'
181 | onChangeText={(input) => setInput(input)} />
182 |
183 | < TouchableOpacity
184 | onPress={() => onCommentSend()}
185 | style={{ width: 100, alignSelf: 'center' }}>
186 | Post
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 | )
195 | }
196 |
197 |
198 | const mapStateToProps = (store) => ({
199 | users: store.usersState.users,
200 | currentUser: store.userState.currentUser
201 | })
202 | const mapDispatchProps = (dispatch) => bindActionCreators({ fetchUsersData, sendNotification }, dispatch);
203 |
204 | export default connect(mapStateToProps, mapDispatchProps)(Comment);
205 |
--------------------------------------------------------------------------------
/frontend/components/main/chat/List.js:
--------------------------------------------------------------------------------
1 | import { FontAwesome5 } from '@expo/vector-icons';
2 | import firebase from 'firebase';
3 | import React, { useEffect, useState } from 'react';
4 | import { FlatList, Image, Text, TouchableOpacity, View } from 'react-native';
5 | import { TextInput } from 'react-native-gesture-handler';
6 | import { Divider } from 'react-native-paper';
7 | import { connect } from 'react-redux';
8 | import { bindActionCreators } from 'redux';
9 | import { fetchUsersData } from '../../../redux/actions/index';
10 | import { container, text, utils } from '../../styles';
11 | import { timeDifference } from '../../utils';
12 | import CachedImage from '../random/CachedImage';
13 |
14 | require('firebase/firestore')
15 |
16 |
17 |
18 | function Chat(props) {
19 | const [chats, setChats] = useState([])
20 | const [reload, setReload] = useState(false)
21 | const [input, setInput] = useState("")
22 | const [caption, setCaption] = useState("")
23 | const [textInput, setTextInput] = useState(null)
24 |
25 | useEffect(() => {
26 | for (let i = 0; i < props.chats.length; i++) {
27 | if (props.chats[i].hasOwnProperty('otherUser')) {
28 | continue;
29 | }
30 | let otherUserId;
31 | if (props.chats[i].users[0] == firebase.auth().currentUser.uid) {
32 | otherUserId = props.chats[i].users[1];
33 | } else {
34 | otherUserId = props.chats[i].users[0];
35 | }
36 |
37 | const user = props.users.find(x => x.uid === otherUserId)
38 | if (user == undefined) {
39 | props.fetchUsersData(otherUserId, false)
40 | } else {
41 | props.chats[i].otherUser = user
42 | }
43 | }
44 | setChats(props.chats)
45 | }, [props.chats, props.users])
46 |
47 |
48 |
49 | const sendPost = (item) => {
50 | if (item.sent != undefined) {
51 | return;
52 | }
53 | const textToSend = input;
54 |
55 | setInput("")
56 |
57 | textInput.clear()
58 |
59 | let post = props.route.params.post
60 | delete post.doc
61 | firebase.firestore()
62 | .collection('chats')
63 | .doc(item.id)
64 | .collection('messages')
65 | .add({
66 | creator: firebase.auth().currentUser.uid,
67 | text: textToSend,
68 | post: post,
69 | creation: firebase.firestore.FieldValue.serverTimestamp()
70 | })
71 | firebase.firestore()
72 | .collection('chats')
73 | .doc(item.id)
74 | .update({
75 | lastMessage: "post sent",
76 | lastMessageTimestamp: firebase.firestore.FieldValue.serverTimestamp()
77 | })
78 |
79 |
80 | firebase.firestore()
81 | .collection('chats')
82 | .doc(item.id)
83 | .update({
84 | lastMessage: textToSend,
85 | lastMessageTimestamp: firebase.firestore.FieldValue.serverTimestamp(),
86 | [item.users[0]]: false,
87 | [item.users[1]]: false
88 | })
89 |
90 | props.navigation.popToTop()
91 |
92 | }
93 |
94 | let share = false;
95 | let item = null;
96 |
97 | if (props.route.params !== undefined) {
98 | share = props.route.params.share
99 | item = props.route.params.post
100 | }
101 |
102 |
103 | if (chats.length === 0) {
104 | return (
105 |
106 |
107 | No chats notAvailable
108 |
109 | )
110 | }
111 | return (
112 |
113 | {item != null ?
114 |
115 | setInput(caption)}
121 | />
122 | {item.type == 1 ?
123 |
128 | :
129 |
130 |
135 |
136 | }
137 |
138 | : null}
139 |
140 |
141 | {chats.length !== 0 ?
142 | item.id}
147 | renderItem={({ item }) => (
148 |
149 |
150 | {item.otherUser == null ? (
151 |
154 | )
155 | :
156 | (
157 | {
160 | if (!share) {
161 | props.navigation.navigate("Chat", { user: item.otherUser })
162 |
163 | }
164 | }}>
165 |
166 |
167 |
168 | {item.otherUser.image == 'default' ? (
169 |
172 | )
173 | :
174 | (
175 |
180 | )}
181 |
182 |
183 |
184 |
185 |
186 | {item.otherUser.name}
187 |
188 |
189 | {item.lastMessage} {" "}
190 | {item.lastMessageTimestamp == null ? (
191 |
192 | Now
193 | ) : (
194 |
196 | {timeDifference(new Date(), item.lastMessageTimestamp.toDate())}
197 |
198 | )}
199 |
200 |
201 |
202 | {share ? sendPost(item)}>
205 | Send
206 | :
207 | null}
208 |
209 |
210 |
211 |
212 | )}
213 |
214 |
215 |
216 | )
217 | }
218 | />
219 |
220 | :
221 |
222 |
223 |
224 | No chats available
225 |
226 | }
227 |
228 | )
229 | }
230 |
231 | const mapStateToProps = (store) => ({
232 | currentUser: store.userState.currentUser,
233 | chats: store.userState.chats,
234 | users: store.usersState.users,
235 | })
236 | const mapDispatchProps = (dispatch) => bindActionCreators({ fetchUsersData }, dispatch);
237 |
238 | export default connect(mapStateToProps, mapDispatchProps)(Chat);
239 |
--------------------------------------------------------------------------------
/frontend/components/main/profile/Profile.js:
--------------------------------------------------------------------------------
1 | import { FontAwesome5 } from '@expo/vector-icons';
2 | import firebase from 'firebase';
3 | import React, { useEffect, useState } from 'react';
4 | import { ActivityIndicator, FlatList, Image, Text, TouchableOpacity, View } from 'react-native';
5 | import { ScrollView } from 'react-native-gesture-handler';
6 | import { connect } from 'react-redux';
7 | import { bindActionCreators } from 'redux';
8 | import { sendNotification } from '../../../redux/actions/index';
9 | import { container, text, utils } from '../../styles';
10 | import CachedImage from '../random/CachedImage';
11 | require('firebase/firestore')
12 |
13 |
14 |
15 | function Profile(props) {
16 | const [userPosts, setUserPosts] = useState([]);
17 | const [user, setUser] = useState(null);
18 | const [loading, setLoading] = useState(true);
19 | const [following, setFollowing] = useState(false)
20 |
21 | useEffect(() => {
22 | const { currentUser, posts } = props;
23 |
24 | if (props.route.params.uid === firebase.auth().currentUser.uid) {
25 | setUser(currentUser)
26 | setUserPosts(posts)
27 | setLoading(false)
28 | }
29 | else {
30 | firebase.firestore()
31 | .collection("users")
32 | .doc(props.route.params.uid)
33 | .get()
34 | .then((snapshot) => {
35 | if (snapshot.exists) {
36 | props.navigation.setOptions({
37 | title: snapshot.data().username,
38 | })
39 |
40 | setUser({ uid: props.route.params.uid, ...snapshot.data() });
41 | }
42 | setLoading(false)
43 |
44 | })
45 | firebase.firestore()
46 | .collection("posts")
47 | .doc(props.route.params.uid)
48 | .collection("userPosts")
49 | .orderBy("creation", "desc")
50 | .get()
51 | .then((snapshot) => {
52 | let posts = snapshot.docs.map(doc => {
53 | const data = doc.data();
54 | const id = doc.id;
55 | return { id, ...data }
56 | })
57 | setUserPosts(posts)
58 | })
59 | }
60 |
61 |
62 | if (props.following.indexOf(props.route.params.uid) > -1) {
63 | setFollowing(true);
64 | } else {
65 | setFollowing(false);
66 | }
67 |
68 | }, [props.route.params.uid, props.following, props.currentUser, props.posts])
69 |
70 | const onFollow = () => {
71 | firebase.firestore()
72 | .collection("following")
73 | .doc(firebase.auth().currentUser.uid)
74 | .collection("userFollowing")
75 | .doc(props.route.params.uid)
76 | .set({})
77 |
78 | props.sendNotification(user.notificationToken, "New Follower", `${props.currentUser.name} Started following you`, { type: 'profile', user: firebase.auth().currentUser.uid })
79 | }
80 | const onUnfollow = () => {
81 | firebase.firestore()
82 | .collection("following")
83 | .doc(firebase.auth().currentUser.uid)
84 | .collection("userFollowing")
85 | .doc(props.route.params.uid)
86 | .delete()
87 | }
88 |
89 | if (loading) {
90 | return (
91 |
92 |
93 | Loading
94 |
95 | )
96 | }
97 | if (user === null) {
98 | return (
99 |
100 |
101 | User Not Found
102 |
103 | )
104 | }
105 | return (
106 |
107 |
108 |
109 |
110 |
111 |
112 | {user.image == 'default' ?
113 | (
114 |
117 | )
118 | :
119 | (
120 |
126 | )
127 | }
128 |
129 |
130 |
131 |
132 | {userPosts.length}
133 | Posts
134 |
135 |
136 | {user.followersCount}
137 | Followers
138 |
139 |
140 | {user.followingCount}
141 | Following
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 | {user.name}
150 | {user.description}
151 |
152 | {props.route.params.uid !== firebase.auth().currentUser.uid ? (
153 |
154 | {following ? (
155 | onUnfollow()}>
159 | Following
160 |
161 | )
162 | :
163 | (
164 | onFollow()}>
168 | Follow
169 |
170 |
171 | )}
172 |
173 | props.navigation.navigate('Chat', { user })}>
177 | Message
178 |
179 |
180 | ) :
181 | props.navigation.navigate('Edit')}>
184 | Edit Profile
185 | }
186 |
187 |
188 |
189 |
190 | (
196 | props.navigation.navigate("Post", { item, user })}>
199 |
200 | {item.type == 0 ?
201 |
202 |
207 |
208 | :
209 |
210 |
215 | }
216 |
217 |
218 | )}
219 |
220 | />
221 |
222 |
223 |
224 | )
225 | }
226 |
227 | const mapStateToProps = (store) => ({
228 | currentUser: store.userState.currentUser,
229 | posts: store.userState.posts,
230 | following: store.userState.following
231 |
232 | })
233 |
234 | const mapDispatchProps = (dispatch) => bindActionCreators({ sendNotification }, dispatch);
235 |
236 | export default connect(mapStateToProps, mapDispatchProps)(Profile);
237 |
238 |
--------------------------------------------------------------------------------
/frontend/redux/actions/index.js:
--------------------------------------------------------------------------------
1 | import * as Notifications from 'expo-notifications';
2 | import firebase from 'firebase';
3 | import { Constants } from 'react-native-unimodules';
4 | import { CLEAR_DATA, USERS_DATA_STATE_CHANGE, USERS_LIKES_STATE_CHANGE, USERS_POSTS_STATE_CHANGE, USER_CHATS_STATE_CHANGE, USER_FOLLOWING_STATE_CHANGE, USER_POSTS_STATE_CHANGE, USER_STATE_CHANGE } from '../constants/index';
5 | require('firebase/firestore')
6 |
7 |
8 | let unsubscribe = [];
9 |
10 | export function clearData() {
11 | return ((dispatch) => {
12 | for (let i = unsubscribe; i < unsubscribe.length; i++) {
13 | unsubscribe[i]();
14 | }
15 | dispatch({ type: CLEAR_DATA })
16 | })
17 | }
18 | export function reload() {
19 | return ((dispatch) => {
20 | dispatch(clearData())
21 | dispatch(fetchUser())
22 | dispatch(setNotificationService())
23 | dispatch(fetchUserPosts())
24 | dispatch(fetchUserFollowing())
25 | dispatch(fetchUserChats())
26 |
27 | })
28 | }
29 |
30 | export const setNotificationService = () => async dispatch => {
31 | let token;
32 | if (Constants.isDevice) {
33 | const existingStatus = await Notifications.getPermissionsAsync();
34 | let finalStatus = existingStatus;
35 | if (existingStatus.status !== 'granted') {
36 | const status = await Notifications.requestPermissionsAsync();
37 | finalStatus = status;
38 | }
39 |
40 | if (finalStatus.status !== 'granted') {
41 | alert('Failed to get push token for push notification!');
42 | return;
43 | }
44 | token = (await Notifications.getExpoPushTokenAsync());
45 | } else {
46 | alert('Must use physical device for Push Notifications');
47 | }
48 |
49 | if (Platform.OS === 'android') {
50 | Notifications.setNotificationChannelAsync('default', {
51 | name: 'default',
52 | importance: Notifications.AndroidImportance.MAX,
53 | vibrationPattern: [0, 250, 250, 250],
54 | lightColor: '#FF231F7C',
55 | });
56 | }
57 |
58 | Notifications.setNotificationHandler({
59 | handleNotification: async () => ({
60 | shouldShowAlert: true,
61 | shouldPlaySound: false,
62 | shouldSetBadge: false,
63 | }),
64 | });
65 |
66 | if (token != undefined) {
67 | firebase.firestore()
68 | .collection("users")
69 | .doc(firebase.auth().currentUser.uid)
70 | .update({
71 | notificationToken: token.data,
72 | })
73 | }
74 |
75 | }
76 |
77 | export const sendNotification = (to, title, body, data) => dispatch => {
78 | if (to == null) {
79 | return;
80 | }
81 |
82 | let response = fetch('https://exp.host/--/api/v2/push/send', {
83 | method: 'POST',
84 | headers: {
85 | Accept: 'application/json',
86 | 'Content-Type': 'application/json'
87 | },
88 | body: JSON.stringify({
89 | to,
90 | sound: 'default',
91 | title,
92 | body,
93 | data
94 | })
95 | })
96 |
97 | }
98 |
99 | export function fetchUser() {
100 | return ((dispatch) => {
101 | let listener = firebase.firestore()
102 | .collection("users")
103 | .doc(firebase.auth().currentUser.uid)
104 | .onSnapshot((snapshot, error) => {
105 | if (snapshot.exists) {
106 | dispatch({ type: USER_STATE_CHANGE, currentUser: { uid: firebase.auth().currentUser.uid, ...snapshot.data() } })
107 | }
108 | })
109 | unsubscribe.push(listener)
110 | })
111 | }
112 |
113 | export function fetchUserChats() {
114 | return ((dispatch) => {
115 | let listener = firebase.firestore()
116 | .collection("chats")
117 | .where("users", "array-contains", firebase.auth().currentUser.uid)
118 | .orderBy("lastMessageTimestamp", "desc")
119 | .onSnapshot((snapshot) => {
120 | let chats = snapshot.docs.map(doc => {
121 | const data = doc.data();
122 | const id = doc.id;
123 | return { id, ...data }
124 | })
125 |
126 | for (let i = 0; i < chats.length; i++) {
127 | let otherUserId;
128 | if (chats[i].users[0] == firebase.auth().currentUser.uid) {
129 | otherUserId = chats[i].users[1];
130 | } else {
131 | otherUserId = chats[i].users[0];
132 | }
133 | dispatch(fetchUsersData(otherUserId, false))
134 | }
135 |
136 | dispatch({ type: USER_CHATS_STATE_CHANGE, chats })
137 | })
138 | unsubscribe.push(listener)
139 | })
140 | }
141 | export function fetchUserPosts() {
142 | return ((dispatch) => {
143 | firebase.firestore()
144 | .collection("posts")
145 | .doc(firebase.auth().currentUser.uid)
146 | .collection("userPosts")
147 | .orderBy("creation", "desc")
148 | .get()
149 | .then((snapshot) => {
150 | let posts = snapshot.docs.map(doc => {
151 | const data = doc.data();
152 | const id = doc.id;
153 | return { id, ...data }
154 | })
155 | dispatch({ type: USER_POSTS_STATE_CHANGE, posts })
156 | })
157 | })
158 | }
159 |
160 |
161 | export function fetchUserFollowing() {
162 | return ((dispatch) => {
163 | let listener = firebase.firestore()
164 | .collection("following")
165 | .doc(firebase.auth().currentUser.uid)
166 | .collection("userFollowing")
167 | .onSnapshot((snapshot) => {
168 | let following = snapshot.docs.map(doc => {
169 | const id = doc.id;
170 | return id
171 | })
172 | dispatch({ type: USER_FOLLOWING_STATE_CHANGE, following });
173 | for (let i = 0; i < following.length; i++) {
174 | dispatch(fetchUsersData(following[i], true));
175 | }
176 | })
177 | unsubscribe.push(listener)
178 | })
179 | }
180 |
181 | export function fetchUsersData(uid, getPosts) {
182 | return ((dispatch, getState) => {
183 | const found = getState().usersState.users.some(el => el.uid === uid);
184 | if (!found) {
185 | firebase.firestore()
186 | .collection("users")
187 | .doc(uid)
188 | .get()
189 | .then((snapshot) => {
190 | if (snapshot.exists) {
191 | let user = snapshot.data();
192 | user.uid = snapshot.id;
193 |
194 | dispatch({ type: USERS_DATA_STATE_CHANGE, user });
195 | }
196 | })
197 | if (getPosts) {
198 | dispatch(fetchUsersFollowingPosts(uid));
199 | }
200 | }
201 | })
202 | }
203 |
204 | export function fetchUsersFollowingPosts(uid) {
205 | return ((dispatch, getState) => {
206 | firebase.firestore()
207 | .collection("posts")
208 | .doc(uid)
209 | .collection("userPosts")
210 | .orderBy("creation", "asc")
211 | .get()
212 | .then((snapshot) => {
213 | const uid = snapshot.docs[0].ref.path.split('/')[1];
214 | const user = getState().usersState.users.find(el => el.uid === uid);
215 |
216 |
217 | let posts = snapshot.docs.map(doc => {
218 | const data = doc.data();
219 | const id = doc.id;
220 | return { id, ...data, user }
221 | })
222 |
223 | for (let i = 0; i < posts.length; i++) {
224 | dispatch(fetchUsersFollowingLikes(uid, posts[i].id))
225 | }
226 | dispatch({ type: USERS_POSTS_STATE_CHANGE, posts, uid })
227 |
228 | })
229 | })
230 | }
231 |
232 | export function fetchUsersFollowingLikes(uid, postId) {
233 | return ((dispatch, getState) => {
234 | let listener = firebase.firestore()
235 | .collection("posts")
236 | .doc(uid)
237 | .collection("userPosts")
238 | .doc(postId)
239 | .collection("likes")
240 | .doc(firebase.auth().currentUser.uid)
241 | .onSnapshot((snapshot) => {
242 | const postId = snapshot.id;
243 |
244 | let currentUserLike = false;
245 | if (snapshot.exists) {
246 | currentUserLike = true;
247 | }
248 |
249 | dispatch({ type: USERS_LIKES_STATE_CHANGE, postId, currentUserLike })
250 | })
251 | unsubscribe.push(listener)
252 | })
253 | }
254 |
255 |
256 |
257 | export function queryUsersByUsername(username) {
258 | return ((dispatch, getState) => {
259 | return new Promise((resolve, reject) => {
260 | if (username.length == 0) {
261 | resolve([])
262 | }
263 | firebase.firestore()
264 | .collection('users')
265 | .where('username', '>=', username)
266 | .limit(10)
267 | .get()
268 | .then((snapshot) => {
269 | let users = snapshot.docs.map(doc => {
270 | const data = doc.data();
271 | const id = doc.id;
272 | return { id, ...data }
273 | });
274 | resolve(users);
275 | })
276 | })
277 | })
278 | }
279 |
280 |
281 | export function deletePost(item) {
282 | return ((dispatch, getState) => {
283 | return new Promise((resolve, reject) => {
284 | firebase.firestore()
285 | .collection('posts')
286 | .doc(firebase.auth().currentUser.uid)
287 | .collection("userPosts")
288 | .doc(item.id)
289 | .delete()
290 | .then(() => {
291 | resolve();
292 | }).catch(() => {
293 | reject();
294 | })
295 | })
296 | })
297 | }
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
--------------------------------------------------------------------------------
/frontend/components/main/add/Save.js:
--------------------------------------------------------------------------------
1 | import { Feather } from '@expo/vector-icons';
2 | import { Video } from 'expo-av';
3 | import firebase from 'firebase';
4 | import React, { useLayoutEffect, useState } from 'react';
5 | import { ActivityIndicator, Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
6 | import MentionsTextInput from 'react-native-mentions';
7 | import { Snackbar } from 'react-native-paper';
8 | import { connect } from 'react-redux';
9 | import { bindActionCreators } from 'redux';
10 | import { fetchUserPosts, sendNotification } from '../../../redux/actions/index';
11 | import { container, navbar, text, utils } from '../../styles';
12 |
13 |
14 | require("firebase/firestore")
15 | require("firebase/firebase-storage")
16 |
17 |
18 |
19 | function Save(props) {
20 | const [caption, setCaption] = useState("")
21 | const [uploading, setUploading] = useState(false)
22 | const [error, setError] = useState(false)
23 | const [data, setData] = useState("")
24 | const [keyword, setKeyword] = useState("")
25 |
26 |
27 | useLayoutEffect(() => {
28 | props.navigation.setOptions({
29 | headerRight: () => (
30 | { uploadImage() }} />
31 | ),
32 | });
33 | }, [caption]);
34 |
35 | const uploadImage = async () => {
36 | if (uploading) {
37 | return;
38 | }
39 | setUploading(true)
40 | let downloadURLStill = null
41 | let downloadURL = await SaveStorage(props.route.params.source, `post/${firebase.auth().currentUser.uid}/${Math.random().toString(36)}`)
42 |
43 | if (props.route.params.imageSource != null) {
44 | downloadURLStill = await SaveStorage(props.route.params.imageSource, `post/${firebase.auth().currentUser.uid}/${Math.random().toString(36)}`)
45 | }
46 |
47 | savePostData(downloadURL, downloadURLStill);
48 |
49 | }
50 |
51 | const SaveStorage = async (image, path) => {
52 | if (image == 'default') {
53 | return '';
54 | }
55 |
56 | const fileRef = firebase.storage().ref()
57 | .child(path);
58 |
59 | const response = await fetch(image);
60 | const blob = await response.blob();
61 |
62 | const task = await fileRef.put(blob);
63 |
64 | const downloadURL = await task.ref.getDownloadURL();
65 |
66 | return downloadURL;
67 | }
68 | const savePostData = (downloadURL, downloadURLStill) => {
69 | let object = {
70 | downloadURL,
71 | caption,
72 | likesCount: 0,
73 | commentsCount: 0,
74 | type: props.route.params.type,
75 | creation: firebase.firestore.FieldValue.serverTimestamp()
76 | }
77 | if (downloadURLStill != null) {
78 | object.downloadURLStill = downloadURLStill
79 | }
80 |
81 | firebase.firestore()
82 | .collection('posts')
83 | .doc(firebase.auth().currentUser.uid)
84 | .collection("userPosts")
85 | .add(object).then((result) => {
86 | props.fetchUserPosts()
87 | props.navigation.popToTop()
88 | }).catch((error) => {
89 | setUploading(false)
90 | setError(true)
91 | })
92 |
93 | var pattern = /\B@[a-z0-9_-]+/gi;
94 | let array = caption.match(pattern);
95 |
96 | if (array !== null) {
97 |
98 | for (let i = 0; i < array.length; i++) {
99 | firebase.firestore()
100 | .collection("users")
101 | .where("username", "==", array[i].substring(1))
102 | .get()
103 | .then((snapshot) => {
104 |
105 | snapshot.forEach((doc) => {
106 | props.sendNotification(doc.data().notificationToken, "New tag", `${props.currentUser.name} Tagged you in a post`, { type: 0, user: firebase.auth().currentUser.uid })
107 |
108 | });
109 | })
110 | }
111 | }
112 |
113 |
114 | }
115 |
116 | const renderSuggestionsRow = ({ item }, hidePanel) => {
117 | return (
118 | onSuggestionTap(item.username, hidePanel)}>
119 |
120 |
121 |
127 |
128 |
129 | {item.name}
130 | @{item.username}
131 |
132 |
133 |
134 | )
135 | }
136 |
137 | const onSuggestionTap = (username, hidePanel) => {
138 | hidePanel();
139 | const comment = caption.slice(0, - keyword.length)
140 | setCaption(comment + '@' + username + " ");
141 | }
142 |
143 |
144 | const callback = (keyword) => {
145 | setKeyword(keyword)
146 | firebase.firestore()
147 | .collection("users")
148 | .where("username", ">=", keyword.substring(1))
149 | .limit(10)
150 | .get()
151 | .then((snapshot) => {
152 | let result = snapshot.docs.map(doc => {
153 |
154 | const data = doc.data();
155 | const id = doc.id;
156 | return { id, ...data }
157 | });
158 | setData(result)
159 |
160 | })
161 | }
162 | return (
163 |
164 | {uploading ? (
165 |
166 |
167 |
168 | Upload in progress...
169 |
170 | ) : (
171 |
172 |
173 |
174 |
175 |
176 |
177 | }
182 | textInputMinHeight={30}
183 | textInputMaxHeight={80}
184 | trigger={'@'}
185 | triggerLocation={'new-word-only'} // 'new-word-only', 'anywhere'
186 | value={caption}
187 | onChangeText={setCaption}
188 | triggerCallback={callback.bind(this)}
189 | renderSuggestionsRow={renderSuggestionsRow.bind(this)}
190 | suggestionsData={data}
191 | keyExtractor={(item, index) => item.username}
192 | suggestionRowHeight={45}
193 | horizontal={true}
194 | MaxVisibleRowCount={3}
195 | />
196 |
197 |
198 | {props.route.params.type ?
199 |
200 |
205 |
206 | :
207 |
208 |
216 | }
217 |
218 |
219 |
220 | setError(false)}>
224 | Something Went Wrong!
225 |
226 |
227 | )}
228 |
229 |
230 |
231 | )
232 | }
233 | const styles = StyleSheet.create({
234 | container: {
235 | height: 300,
236 | justifyContent: 'flex-end',
237 | paddingTop: 100
238 | },
239 | suggestionsRowContainer: {
240 | flexDirection: 'row',
241 | },
242 | userAvatarBox: {
243 | width: 35,
244 | paddingTop: 2
245 | },
246 | userIconBox: {
247 | height: 45,
248 | width: 45,
249 | alignItems: 'center',
250 | justifyContent: 'center',
251 | backgroundColor: '#54c19c'
252 | },
253 | usernameInitials: {
254 | color: '#fff',
255 | fontWeight: '800',
256 | fontSize: 14
257 | },
258 | userDetailsBox: {
259 | flex: 1,
260 | justifyContent: 'center',
261 | paddingLeft: 10,
262 | paddingRight: 15
263 | },
264 | displayNameText: {
265 | fontSize: 13,
266 | fontWeight: '500'
267 | },
268 | usernameText: {
269 | fontSize: 12,
270 | color: 'rgba(0,0,0,0.6)'
271 | }
272 | });
273 |
274 | const mapStateToProps = (store) => ({
275 | currentUser: store.userState.currentUser
276 | })
277 |
278 | const mapDispatchProps = (dispatch) => bindActionCreators({ fetchUserPosts, sendNotification }, dispatch);
279 |
280 |
281 | export default connect(mapStateToProps, mapDispatchProps)(Save);
--------------------------------------------------------------------------------
/frontend/components/main/chat/Chat.js:
--------------------------------------------------------------------------------
1 | import { FontAwesome5 } from '@expo/vector-icons';
2 | import firebase from 'firebase';
3 | import React, { useEffect, useState } from 'react';
4 | import { FlatList, Image, Text, TextInput, TouchableOpacity, View } from 'react-native';
5 | import CachedImage from 'react-native-expo-cached-image';
6 | import { Provider } from 'react-native-paper';
7 | import { connect } from 'react-redux';
8 | import { bindActionCreators } from 'redux';
9 | import { fetchFeedPosts, fetchUserChats, sendNotification } from '../../../redux/actions/index';
10 | import { container, text, utils } from '../../styles';
11 | import { timeDifference } from '../../utils';
12 | require('firebase/firestore')
13 |
14 |
15 | function Chat(props) {
16 | const [user, setUser] = useState(null)
17 | const [chat, setChat] = useState(null)
18 | const [messages, setMessages] = useState([])
19 | const [input, setInput] = useState("")
20 | const [textInput, setTextInput] = useState(null)
21 | const [flatList, setFlatList] = useState(null)
22 | const [initialFetch, setInitialFetch] = useState(false)
23 |
24 | useEffect(() => {
25 | if (props.route.params.notification) {
26 | firebase.firestore()
27 | .collection("users")
28 | .doc(props.route.params.user)
29 | .get()
30 | .then((snapshot) => {
31 | if (snapshot.exists) {
32 | let user = snapshot.data();
33 | user.uid = snapshot.id;
34 |
35 | setUser(user)
36 | }
37 | })
38 | }
39 | else {
40 | setUser(props.route.params.user)
41 | }
42 |
43 | }, [props.route.params.notification, props.route.params.user])
44 |
45 |
46 | useEffect(() => {
47 | if (user == null) {
48 | return;
49 | }
50 | if (initialFetch) {
51 | return;
52 | }
53 |
54 | const chat = props.chats.find(el => el.users.includes(user.uid));
55 | setChat(chat)
56 |
57 |
58 | props.navigation.setOptions({
59 | headerTitle: () => (
60 |
61 | {
62 | user.image == 'default' ?
63 | (
64 |
67 |
68 | )
69 | :
70 | (
71 |
77 | )
78 | }
79 | {props.route.params.user.username}
80 |
81 | ),
82 | });
83 | if (chat !== undefined) {
84 | firebase.firestore()
85 | .collection("chats")
86 | .doc(chat.id)
87 | .collection("messages")
88 | .orderBy("creation", "asc")
89 | .onSnapshot((snapshot) => {
90 |
91 | let messages = snapshot.docs.map(doc => {
92 | const data = doc.data();
93 | const id = doc.id;
94 | return { id, ...data }
95 | })
96 | setMessages(messages)
97 | })
98 |
99 | firebase.firestore()
100 | .collection('chats')
101 | .doc(chat.id)
102 | .update({
103 | [firebase.auth().currentUser.uid]: true,
104 | })
105 | setInitialFetch(true)
106 |
107 | } else {
108 | createChat()
109 | }
110 | }, [user, props.chats])
111 |
112 | const createChat = () => {
113 | firebase.firestore()
114 | .collection("chats")
115 | .add({
116 | users: [firebase.auth().currentUser.uid, user.uid],
117 | lastMessage: 'Send the first message',
118 | lastMessageTimestamp: firebase.firestore.FieldValue.serverTimestamp()
119 | }).then(() => {
120 | props.fetchUserChats()
121 | })
122 | }
123 | const onSend = () => {
124 | const textToSend = input;
125 | if (chat == undefined) {
126 | return;
127 | }
128 |
129 | if (input.length == 0) {
130 | return;
131 | }
132 | setInput("")
133 |
134 |
135 | textInput.clear()
136 |
137 | firebase.firestore()
138 | .collection('chats')
139 | .doc(chat.id)
140 | .collection('messages')
141 | .add({
142 | creator: firebase.auth().currentUser.uid,
143 | text: textToSend,
144 | creation: firebase.firestore.FieldValue.serverTimestamp()
145 | })
146 |
147 | firebase.firestore()
148 | .collection('chats')
149 | .doc(chat.id)
150 | .update({
151 | lastMessage: textToSend,
152 | lastMessageTimestamp: firebase.firestore.FieldValue.serverTimestamp(),
153 | [chat.users[0]]: false,
154 | [chat.users[1]]: false
155 |
156 | })
157 |
158 | props.sendNotification(user.notificationToken, "New Message", textToSend, { type: "chat", user: firebase.auth().currentUser.uid })
159 |
160 |
161 | }
162 |
163 | return (
164 |
165 |
166 |
167 | { if (flatList != null) flatList.scrollToEnd({ animated: true }) }}
173 |
174 | renderItem={({ item }) => (
175 |
176 | {item.creator !== undefined && item.creation !== null ?
177 |
178 |
179 |
180 | {item.text}
181 |
182 | {item.post != null ?
183 |
184 | { props.navigation.navigate("Post", { item: item.post, user: item.post.user }) }}>
185 | {item.post.type == 0 ?
186 |
191 | :
192 |
193 |
198 | }
199 |
200 | : null}
201 |
203 | {timeDifference(new Date(), item.creation.toDate())}
204 |
205 |
206 |
207 | : null}
208 |
209 |
210 |
211 | )
212 | }
213 | />
214 |
215 |
216 | < View style={[container.horizontal, utils.padding10, utils.alignItemsCenter, utils.backgroundWhite, utils.borderTopGray]} >
217 | {
218 | props.currentUser.image == 'default' ?
219 | (
220 |
223 |
224 | )
225 | :
226 | (
227 |
233 | )
234 | }
235 |
236 |
237 |
238 | < TextInput
239 | ref={input => { setTextInput(input) }}
240 | value={input}
241 | multiline={true}
242 | style={[container.fillHorizontal, container.input, container.container]}
243 | placeholder='message...'
244 | onChangeText={(input) => setInput(input)} />
245 |
246 | < TouchableOpacity
247 | onPress={() => onSend()}
248 | style={{ width: 100, alignSelf: 'center' }}>
249 | Send
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 | )
258 | }
259 |
260 | const mapStateToProps = (store) => ({
261 | currentUser: store.userState.currentUser,
262 | chats: store.userState.chats,
263 | following: store.userState.following,
264 | feed: store.usersState.feed,
265 |
266 | })
267 | const mapDispatchProps = (dispatch) => bindActionCreators({ fetchUserChats, sendNotification, fetchFeedPosts }, dispatch);
268 |
269 | export default connect(mapStateToProps, mapDispatchProps)(Chat);
270 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/frontend/components/main/add/Camera.js:
--------------------------------------------------------------------------------
1 | import { Feather } from '@expo/vector-icons';
2 | import { useIsFocused } from '@react-navigation/native';
3 | import { Audio } from "expo-av";
4 | import { Camera } from "expo-camera";
5 | import * as ImagePicker from 'expo-image-picker';
6 | import * as MediaLibrary from 'expo-media-library';
7 | import * as VideoThumbnails from 'expo-video-thumbnails';
8 | import React, { useEffect, useRef, useState } from "react";
9 | import {
10 | Dimensions, FlatList, Image, ScrollView, StyleSheet, Text, TouchableOpacity, View
11 | } from "react-native";
12 | import { container, utils } from '../../styles';
13 | const WINDOW_HEIGHT = Dimensions.get("window").height;
14 | const WINDOW_WIDTH = Dimensions.get("window").width;
15 | const closeButtonSize = Math.floor(WINDOW_HEIGHT * 0.032);
16 | const captureSize = Math.floor(WINDOW_HEIGHT * 0.09);
17 |
18 |
19 |
20 |
21 |
22 | export default function VideoScreen(props) {
23 | const [hasPermission, setHasPermission] = useState(null);
24 | const [cameraType, setCameraType] = useState(Camera.Constants.Type.back);
25 | const [isPreview, setIsPreview] = useState(false);
26 | const [isCameraReady, setIsCameraReady] = useState(false);
27 | const [isFlash, setIsFlash] = useState(false);
28 | const [isVideoRecording, setIsVideoRecording] = useState(false);
29 | const [type, setType] = useState(0);
30 | const [showGallery, setShowGallery] = useState(true)
31 | const [galleryItems, setGalleryItems] = useState([])
32 | const [galleryScrollRef, setGalleryScrollRef] = useState(null)
33 | const [galleryPickedImage, setGalleryPickedImage] = useState(null)
34 | const cameraRef = useRef();
35 | const isFocused = useIsFocused();
36 |
37 | useEffect(() => {
38 | (async () => {
39 |
40 | const cameraPermissions = await Camera.requestPermissionsAsync();
41 | const galleryPermissions = await MediaLibrary.requestPermissionsAsync();
42 |
43 | const audioPermissions = await Audio.requestPermissionsAsync();
44 |
45 | if (cameraPermissions.status === 'granted' && audioPermissions.status === 'granted' && galleryPermissions.status === 'granted') {
46 | const getPhotos = await MediaLibrary.getAssetsAsync({ sortBy: ['creationTime'], mediaType: ['photo', 'video'] })
47 | setGalleryItems(getPhotos)
48 | setGalleryPickedImage(getPhotos.assets[0])
49 | setHasPermission(true)
50 |
51 | }
52 |
53 | })();
54 | }, []);
55 | const onCameraReady = () => {
56 | setIsCameraReady(true);
57 | };
58 | const takePicture = async () => {
59 | if (cameraRef.current) {
60 | const options = { quality: 0.5, base64: true, skipProcessing: true };
61 | const data = await cameraRef.current.takePictureAsync(options);
62 | const source = data.uri;
63 | if (source) {
64 | props.navigation.navigate('Save', { source, imageSource: null, type })
65 | }
66 | }
67 | };
68 | const recordVideo = async () => {
69 | if (cameraRef.current) {
70 | try {
71 |
72 | const options = { maxDuration: 60, quality: Camera.Constants.VideoQuality['480p'] }
73 |
74 |
75 | const videoRecordPromise = cameraRef.current.recordAsync(options);
76 | if (videoRecordPromise) {
77 | setIsVideoRecording(true);
78 | const data = await videoRecordPromise;
79 | const source = data.uri;
80 | let imageSource = await generateThumbnail(source)
81 | props.navigation.navigate('Save', { source, imageSource, type })
82 |
83 | }
84 | } catch (error) {
85 | console.warn(error);
86 | }
87 | }
88 | };
89 | const generateThumbnail = async (source) => {
90 | try {
91 | const { uri } = await VideoThumbnails.getThumbnailAsync(
92 | source,
93 | {
94 | time: 5000,
95 | }
96 | );
97 | return uri;
98 | } catch (e) {
99 | console.warn(e);
100 | }
101 | };
102 |
103 |
104 | const stopVideoRecording = async () => {
105 |
106 | if (cameraRef.current) {
107 | setIsVideoRecording(false);
108 | cameraRef.current.stopRecording();
109 | }
110 | };
111 | const switchCamera = () => {
112 | if (isPreview) {
113 | return;
114 | }
115 | setCameraType((prevCameraType) =>
116 | prevCameraType === Camera.Constants.Type.back
117 | ? Camera.Constants.Type.front
118 | : Camera.Constants.Type.back
119 | );
120 | };
121 | const handleGoToSaveOnGalleryPick = async () => {
122 | let type = galleryPickedImage.mediaType == 'video' ? 0 : 1
123 |
124 |
125 | const loadedAsset = await MediaLibrary.getAssetInfoAsync(galleryPickedImage);
126 | let imageSource = null
127 | if (type == 0) {
128 | imageSource = await generateThumbnail(galleryPickedImage.uri)
129 |
130 | }
131 |
132 | props.navigation.navigate('Save', {
133 | source: loadedAsset.localUri,
134 | type,
135 | imageSource
136 | })
137 | }
138 |
139 | const renderCaptureControl = () => (
140 |
141 |
142 | setIsFlash(!isFlash)} >
143 |
144 |
145 |
146 |
147 |
148 | {type == 0 ?
149 |
150 |
157 | :
158 | }
164 |
165 | type == 1 ? setType(0) : setType(1)} >
166 |
167 |
168 | setShowGallery(true)} >
169 |
170 |
171 |
172 |
173 |
174 |
175 | );
176 | if (hasPermission === null) {
177 | return ;
178 | }
179 | if (hasPermission === false) {
180 | return No access to camera;
181 | }
182 |
183 | if (showGallery) {
184 | return (
185 | setGalleryScrollRef(ref)}
187 | style={[container.container, utils.backgroundWhite]}>
188 |
189 |
191 |
199 |
200 |
201 |
202 | handleGoToSaveOnGalleryPick()} >
205 |
206 | Continue
207 |
208 | setShowGallery(false)} >
209 |
210 |
211 |
212 |
213 |
214 | (
223 | { galleryScrollRef.scrollTo({ x: 0, y: 0, animated: true }); setGalleryPickedImage(item); }}>
226 |
227 |
231 |
232 |
233 |
234 | )}
235 |
236 | />
237 |
238 |
239 |
240 | )
241 | }
242 | return (
243 |
244 |
245 |
248 | {isFocused ?
249 |
258 | : null}
259 |
260 |
261 |
262 |
267 |
268 | {renderCaptureControl()}
269 |
270 |
271 |
272 |
273 | );
274 | }
275 | const styles = StyleSheet.create({
276 | closeButton: {
277 | position: "absolute",
278 | top: 35,
279 | left: 15,
280 | height: closeButtonSize,
281 | width: closeButtonSize,
282 | borderRadius: Math.floor(closeButtonSize / 2),
283 | justifyContent: "center",
284 | alignItems: "center",
285 | backgroundColor: "#c4c5c4",
286 | opacity: 0.7,
287 | zIndex: 2,
288 | },
289 | media: {
290 | ...StyleSheet.absoluteFillObject,
291 | },
292 | closeCross: {
293 | width: "68%",
294 | height: 1,
295 | backgroundColor: "black",
296 | },
297 | control: {
298 | position: "absolute",
299 | flexDirection: "row",
300 | bottom: 38,
301 | width: "100%",
302 |
303 | alignItems: "center",
304 | justifyContent: "center",
305 | },
306 | recordIndicatorContainer: {
307 | flexDirection: "row",
308 | position: "absolute",
309 | top: 0,
310 | opacity: 0.7,
311 | },
312 | recordTitle: {
313 | fontSize: 14,
314 | color: "black",
315 | textAlign: "center",
316 | },
317 | recordDot: {
318 | borderRadius: 3,
319 | height: 6,
320 | width: 6,
321 | backgroundColor: "#ff0000",
322 | marginHorizontal: 5,
323 | },
324 | text: {
325 | color: "#000000",
326 | },
327 |
328 | capture: {
329 | backgroundColor: "red",
330 | borderRadius: 5,
331 | height: captureSize,
332 | width: captureSize,
333 | borderRadius: Math.floor(captureSize / 2),
334 | marginHorizontal: 31,
335 | },
336 | capturePicture: {
337 | borderWidth: 6,
338 | borderColor: 'gray',
339 | backgroundColor: "white",
340 | borderRadius: 5,
341 | height: captureSize,
342 | width: captureSize,
343 | borderRadius: Math.floor(captureSize / 2),
344 | marginHorizontal: 31,
345 | },
346 | });
347 |
--------------------------------------------------------------------------------
/frontend/components/main/post/Post.js:
--------------------------------------------------------------------------------
1 | import { Entypo, Feather, FontAwesome5 } from '@expo/vector-icons';
2 | import { useIsFocused } from '@react-navigation/native';
3 | import { Video } from 'expo-av';
4 | import VideoPlayer from 'expo-video-player';
5 | import firebase from 'firebase';
6 | import React, { useEffect, useRef, useState } from 'react';
7 | import { Dimensions, Image, Text, TouchableOpacity, View } from 'react-native';
8 | import BottomSheet from 'react-native-bottomsheet-reanimated';
9 | import { Divider, Snackbar } from 'react-native-paper';
10 | import ParsedText from 'react-native-parsed-text';
11 | import { connect } from 'react-redux';
12 | import { bindActionCreators } from 'redux';
13 | import { deletePost, fetchUserPosts, sendNotification } from '../../../redux/actions/index';
14 | import { container, text, utils } from '../../styles';
15 | import { timeDifference } from '../../utils';
16 | import CachedImage from '../random/CachedImage';
17 | require('firebase/firestore')
18 |
19 |
20 |
21 | const WINDOW_WIDTH = Dimensions.get("window").width;
22 |
23 | function Post(props) {
24 | const [item, setItem] = useState(props.route.params.item)
25 | const [user, setUser] = useState(props.route.params.user)
26 | const [currentUserLike, setCurrentUserLike] = useState(false)
27 | const [unmutted, setUnmutted] = useState(true)
28 | const [videoref, setvideoref] = useState(null)
29 | const [sheetRef, setSheetRef] = useState(useRef(null))
30 | const [modalShow, setModalShow] = useState({ visible: false, item: null })
31 | const [isValid, setIsValid] = useState(true);
32 | const [exists, setExists] = useState(false);
33 | const [loaded, setLoaded] = useState(false);
34 |
35 | const isFocused = useIsFocused();
36 | useEffect(() => {
37 |
38 | if (props.route.params.notification != undefined) {
39 |
40 | firebase.firestore()
41 | .collection("users")
42 | .doc(props.route.params.user)
43 | .get()
44 | .then((snapshot) => {
45 | if (snapshot.exists) {
46 | let user = snapshot.data();
47 | user.uid = snapshot.id;
48 |
49 | setUser(user)
50 | }
51 | })
52 |
53 | firebase.firestore()
54 | .collection("posts")
55 | .doc(props.route.params.user)
56 | .collection("userPosts")
57 | .doc(props.route.params.item)
58 | .get()
59 | .then((snapshot) => {
60 | if (snapshot.exists) {
61 | let post = snapshot.data();
62 | post.id = snapshot.id;
63 |
64 | setItem(post)
65 | setLoaded(true)
66 | setExists(true)
67 | }
68 | })
69 | firebase.firestore()
70 | .collection("posts")
71 | .doc(props.route.params.user)
72 | .collection("userPosts")
73 | .doc(props.route.params.item)
74 | .collection("likes")
75 | .doc(firebase.auth().currentUser.uid)
76 | .onSnapshot((snapshot) => {
77 | let currentUserLike = false;
78 | if (snapshot.exists) {
79 | currentUserLike = true;
80 | }
81 | setCurrentUserLike(currentUserLike)
82 |
83 | })
84 |
85 | }
86 | else {
87 | firebase.firestore()
88 | .collection("posts")
89 | .doc(props.route.params.user.uid)
90 | .collection("userPosts")
91 | .doc(props.route.params.item.id)
92 | .collection("likes")
93 | .doc(firebase.auth().currentUser.uid)
94 | .onSnapshot((snapshot) => {
95 | let currentUserLike = false;
96 | if (snapshot.exists) {
97 | currentUserLike = true;
98 | }
99 | setCurrentUserLike(currentUserLike)
100 |
101 | })
102 |
103 | setItem(props.route.params.item)
104 | setUser(props.route.params.user)
105 | setLoaded(true)
106 | setExists(true)
107 | }
108 |
109 | }, [props.route.params.notification, props.route.params.item])
110 |
111 | useEffect(() => {
112 | if (videoref !== null) {
113 | videoref.setIsMutedAsync(props.route.params.unmutted)
114 | }
115 | setUnmutted(props.route.params.unmutted)
116 | }, [props.route.params.unmutted])
117 |
118 | useEffect(() => {
119 | if (videoref !== null) {
120 | if (isFocused) {
121 | videoref.playAsync()
122 | } else {
123 | videoref.stopAsync()
124 |
125 | }
126 | }
127 |
128 | }, [props.route.params.index, props.route.params.inViewPort])
129 |
130 | const onUsernamePress = (username, matchIndex) => {
131 | props.navigation.navigate("ProfileOther", { username, uid: undefined })
132 | }
133 |
134 | const onLikePress = (userId, postId, item) => {
135 | item.likesCount += 1;
136 | setCurrentUserLike(true)
137 | firebase.firestore()
138 | .collection("posts")
139 | .doc(userId)
140 | .collection("userPosts")
141 | .doc(postId)
142 | .collection("likes")
143 | .doc(firebase.auth().currentUser.uid)
144 | .set({})
145 | .then()
146 | props.sendNotification(user.notificationToken, "New Like", `${props.currentUser.name} liked your post`, { type: 0, postId, user: firebase.auth().currentUser.uid })
147 |
148 | }
149 | const onDislikePress = (userId, postId, item) => {
150 | item.likesCount -= 1;
151 |
152 | setCurrentUserLike(false)
153 | firebase.firestore()
154 | .collection("posts")
155 | .doc(userId)
156 | .collection("userPosts")
157 | .doc(postId)
158 | .collection("likes")
159 | .doc(firebase.auth().currentUser.uid)
160 | .delete()
161 | }
162 | if (!exists && loaded) {
163 | return (
164 |
165 |
166 | Post does not exist
167 |
168 | )
169 | }
170 | if (!loaded) {
171 | return ()
172 |
173 | }
174 | if (user == undefined) {
175 | return ()
176 | }
177 | if (item == null) {
178 | return ()
179 | }
180 |
181 | const _handleVideoRef = (component) => {
182 | setvideoref(component);
183 |
184 | if (component !== null) {
185 | component.setIsMutedAsync(props.route.params.unmutted)
186 | }
187 | }
188 |
189 | if (videoref !== null) {
190 | videoref.setIsMutedAsync(unmutted)
191 | if (isFocused && props.route.params.index == props.route.params.inViewPort) {
192 | videoref.playAsync()
193 | } else {
194 | videoref.stopAsync()
195 |
196 | }
197 | }
198 |
199 |
200 | if (sheetRef.current !== null && !props.route.params.feed) {
201 | if (modalShow.visible) {
202 | sheetRef.snapTo(0)
203 | } else {
204 | sheetRef.snapTo(1)
205 | }
206 | }
207 |
208 | return (
209 |
210 |
211 |
212 |
213 | props.navigation.navigate("ProfileOther", { uid: user.uid, username: undefined })}>
216 |
217 | {user.image == 'default' ?
218 | (
219 |
222 |
223 | )
224 | :
225 | (
226 |
232 | )
233 | }
234 |
235 | {user.name}
236 |
237 |
238 |
239 |
240 | {
244 | if (props.route.params.feed) {
245 | props.route.params.setModalShow({ visible: true, item })
246 | } else {
247 | setModalShow({ visible: true, item })
248 | }
249 | }}>
250 |
252 |
253 |
254 | {item.type == 0 ?
255 |
256 | {props.route.params.index == props.route.params.inViewPort && isFocused ?
257 |
258 |
280 |
281 | {
285 | if (videoref == null) {
286 | return;
287 | }
288 | if (unmutted) {
289 | if (props.route.params.setUnmuttedMain == undefined) {
290 | setUnmutted(false)
291 | } else {
292 | props.route.params.setUnmuttedMain(false)
293 |
294 | }
295 |
296 | } else {
297 | if (props.route.params.setUnmuttedMain == undefined) {
298 | setUnmutted(true)
299 | } else {
300 | props.route.params.setUnmuttedMain(true)
301 |
302 | }
303 |
304 | }
305 |
306 | }}>
307 | {!unmutted ?
308 |
309 |
310 | :
311 |
312 | }
313 |
314 |
315 |
316 |
317 | :
318 |
319 |
320 |
325 |
326 | }
327 |
328 |
329 |
330 | :
331 |
332 |
337 | }
338 |
339 |
340 | {currentUserLike ?
341 | (
342 | onDislikePress(user.uid, item.id, item)} />
343 | )
344 | :
345 | (
346 | onLikePress(user.uid, item.id, item)} />
347 |
348 | )
349 | }
350 | props.navigation.navigate('Comment', { postId: item.id, uid: user.uid, user })} />
351 | props.navigation.navigate('ChatList', { postId: item.id, post: { ...item, user: user }, share: true })} />
352 |
353 |
354 |
355 |
356 |
357 | {item.likesCount} likes
358 |
359 |
360 | props.navigation.navigate("ProfileOther", { uid: user.uid, username: undefined })}>
362 | {user.name}
363 |
364 |
365 |
366 | {item.caption}
373 |
374 |
375 | props.navigation.navigate('Comment', { postId: item.id, uid: user.uid, user })}>
377 | View all {item.commentsCount} Comments
378 |
379 |
381 | {timeDifference(new Date(), item.creation.toDate())}
382 |
383 |
384 |
385 |
386 |
403 |
404 | {modalShow.item != null ?
405 |
406 | {
408 | props.navigation.navigate("ProfileOther", { uid: modalShow.item.user.uid, username: undefined });
409 | setModalShow({ visible: false, item: null });
410 | }}>
411 | Profile
412 |
413 |
414 | {props.route.params.user.uid == firebase.auth().currentUser.uid ?
415 | {
417 | props.deletePost(modalShow.item).then(() => {
418 | props.fetchUserPosts()
419 | props.navigation.popToTop()
420 | })
421 | setModalShow({ visible: false, item: null });
422 | }}>
423 | Delete
424 |
425 | : null}
426 |
427 |
428 | setModalShow({ visible: false, item: null })}>
429 | Cancel
430 |
431 |
432 | : null}
433 |
434 |
435 | }
436 | />
437 | { setIsValid({ boolSnack: false }) }}>
441 | {isValid.message}
442 |
443 |
444 | )
445 | }
446 |
447 | const mapStateToProps = (store) => ({
448 | currentUser: store.userState.currentUser,
449 | following: store.userState.following,
450 | feed: store.usersState.feed,
451 | usersFollowingLoaded: store.usersState.usersFollowingLoaded,
452 | })
453 |
454 | const mapDispatchProps = (dispatch) => bindActionCreators({ sendNotification, fetchUserPosts, deletePost }, dispatch);
455 |
456 | export default connect(mapStateToProps, mapDispatchProps)(Post);
457 |
--------------------------------------------------------------------------------