├── .DS_Store
├── .gitignore
├── README.md
├── client
├── .bundle
│ └── config
├── .eslintrc.js
├── .gitignore
├── .prettierrc.js
├── .watchman-cookie-Shahriars-MacBook-Air.local-669-1494
├── .watchmanconfig
├── App.tsx
├── Gemfile
├── Gemfile.lock
├── Navigations
│ ├── Auth.tsx
│ ├── Main.tsx
│ └── Tabs.tsx
├── README.md
├── __tests__
│ └── App.test.tsx
├── android
│ ├── app
│ │ ├── build.gradle
│ │ ├── debug.keystore
│ │ ├── proguard-rules.pro
│ │ └── src
│ │ │ ├── debug
│ │ │ ├── AndroidManifest.xml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── becodemy
│ │ │ │ └── threads
│ │ │ │ └── ReactNativeFlipper.java
│ │ │ ├── main
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ │ └── becodemy
│ │ │ │ │ └── threads
│ │ │ │ │ ├── MainActivity.java
│ │ │ │ │ └── MainApplication.java
│ │ │ └── res
│ │ │ │ ├── drawable
│ │ │ │ └── rn_edit_text_material.xml
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ │ └── values
│ │ │ │ ├── strings.xml
│ │ │ │ └── styles.xml
│ │ │ └── release
│ │ │ └── java
│ │ │ └── com
│ │ │ └── becodemy
│ │ │ └── threads
│ │ │ └── ReactNativeFlipper.java
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ └── settings.gradle
├── app.json
├── babel.config.js
├── index.js
├── ios
│ ├── .xcode.env
│ ├── Podfile
│ ├── Podfile.lock
│ ├── Threadsclone.xcodeproj
│ │ ├── project.pbxproj
│ │ ├── project.xcworkspace
│ │ │ └── xcshareddata
│ │ │ │ └── IDEWorkspaceChecks.plist
│ │ └── xcshareddata
│ │ │ └── xcschemes
│ │ │ └── Threadsclone.xcscheme
│ ├── Threadsclone.xcworkspace
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata
│ │ │ └── IDEWorkspaceChecks.plist
│ ├── Threadsclone
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.mm
│ │ ├── Images.xcassets
│ │ │ ├── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── Info.plist
│ │ ├── LaunchScreen.storyboard
│ │ └── main.m
│ └── ThreadscloneTests
│ │ ├── Info.plist
│ │ └── ThreadscloneTests.m
├── jest.config.js
├── metro.config.js
├── my-app.d.ts
├── package-lock.json
├── package.json
├── redux
│ ├── Store.ts
│ ├── URI.tsx
│ ├── actions
│ │ ├── notificationAction.ts
│ │ ├── postAction.ts
│ │ └── userAction.ts
│ └── reducers
│ │ ├── notificationReducer.ts
│ │ ├── postReducer.ts
│ │ └── userReducer.ts
├── src
│ ├── assets
│ │ ├── animation_lkbqh8co.json
│ │ └── logo.png
│ ├── common
│ │ ├── Loader.tsx
│ │ └── TimeGenerator.tsx
│ ├── components
│ │ ├── EditProfile.tsx
│ │ ├── FollowerCard.tsx
│ │ ├── PostCard.tsx
│ │ ├── PostDetailsCard.tsx
│ │ └── PostLikeCard.tsx
│ └── screens
│ │ ├── CreateRepliesScreen.tsx
│ │ ├── HomeScreen.tsx
│ │ ├── LoginScreen.tsx
│ │ ├── NotificationScreen.tsx
│ │ ├── PostDetailsScreen.tsx
│ │ ├── PostScreen.tsx
│ │ ├── ProfileScreen.tsx
│ │ ├── SearchScreen.tsx
│ │ ├── SignupScreen.tsx
│ │ └── UserProfileScreen.tsx
├── tailwind.config.js
├── tsconfig.json
└── yarn.lock
└── server
├── .DS_Store
├── .env
├── app.js
├── controllers
├── post.js
└── user.js
├── db
└── db.js
├── middleware
├── auth.js
├── catchAsyncErrors.js
└── error.js
├── models
├── NotificationModel.js
├── PostModel.js
└── UserModel.js
├── package-lock.json
├── package.json
├── routes
├── Post.js
└── user.js
├── server.js
├── utils
├── ErrorHandler.js
└── jwtToken.js
└── vercel.json
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/.DS_Store
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | client/node_modules
2 | server/node_modules
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | Threads is the most popular social media platform on the internet and today we are gonna be build one thread clone with MERN and React Native. We will build this mobile app for both devices like Android and ios. And at the end, we will also build an apk of our app to share it with our friends. so they can install it on their phone and use it.
3 |
4 | Click here to watch Video with more detailed
5 |
6 |
7 | Don't forget to post your mobile app video and mention Becodemy on LinkedIn or Instagram.
8 |
9 |
10 | Follow Becodemy on social media for all updates
11 |
12 |
13 | Instagram: https://www.instagram.com/shahriar_sajeeb_/
14 |
15 | Threads: https://www.threads.net/@shahriar_sajeeb_
16 |
17 | Linkedin: https://www.linkedin.com/in/shahriar-sajeeb-76763222a/
18 |
19 |
20 | Important Links:
21 |
22 | Mobile App Download Link: https://we.tl/t-nS0tfyx4mr (only for Android phones)
23 |
24 | Starting Github Repo: https://github.com/shahriarsajeeb/Threads-starting-setup (Don't forget to give a star ⭐)
25 |
26 | Full source code: https://github.com/shahriarsajeeb/threads-clone (Don't forget to give a star ⭐)
27 |
28 | React Native setup: https://reactnative.dev/docs/environment-setup
29 |
30 | Build APK with React Native: https://reactnative.dev/docs/signed-apk-android
31 |
32 |
33 | #mern_stack #react_native #becodemy #typescript #nodejs #tailwindcss #typescript
34 |
--------------------------------------------------------------------------------
/client/.bundle/config:
--------------------------------------------------------------------------------
1 | BUNDLE_PATH: "vendor/bundle"
2 | BUNDLE_FORCE_RUBY_PLATFORM: 1
3 |
--------------------------------------------------------------------------------
/client/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | extends: '@react-native',
4 | };
5 |
--------------------------------------------------------------------------------
/client/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # Xcode
6 | #
7 | build/
8 | *.pbxuser
9 | !default.pbxuser
10 | *.mode1v3
11 | !default.mode1v3
12 | *.mode2v3
13 | !default.mode2v3
14 | *.perspectivev3
15 | !default.perspectivev3
16 | xcuserdata
17 | *.xccheckout
18 | *.moved-aside
19 | DerivedData
20 | *.hmap
21 | *.ipa
22 | *.xcuserstate
23 | ios/.xcode.env.local
24 |
25 | # Android/IntelliJ
26 | #
27 | build/
28 | .idea
29 | .gradle
30 | local.properties
31 | *.iml
32 | *.hprof
33 | .cxx/
34 | *.keystore
35 | !debug.keystore
36 |
37 | # node.js
38 | #
39 | node_modules/
40 | npm-debug.log
41 | yarn-error.log
42 |
43 | # fastlane
44 | #
45 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
46 | # screenshots whenever they are needed.
47 | # For more information about the recommended setup visit:
48 | # https://docs.fastlane.tools/best-practices/source-control/
49 |
50 | **/fastlane/report.xml
51 | **/fastlane/Preview.html
52 | **/fastlane/screenshots
53 | **/fastlane/test_output
54 |
55 | # Bundle artifact
56 | *.jsbundle
57 |
58 | # Ruby / CocoaPods
59 | /ios/Pods/
60 | /vendor/bundle/
61 |
62 | # Temporary files created by Metro to check the health of the file watcher
63 | .metro-health-check*
64 |
65 | # testing
66 | /coverage
67 |
--------------------------------------------------------------------------------
/client/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | arrowParens: 'avoid',
3 | bracketSameLine: true,
4 | bracketSpacing: false,
5 | singleQuote: true,
6 | trailingComma: 'all',
7 | };
8 |
--------------------------------------------------------------------------------
/client/.watchman-cookie-Shahriars-MacBook-Air.local-669-1494:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/.watchman-cookie-Shahriars-MacBook-Air.local-669-1494
--------------------------------------------------------------------------------
/client/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
2 |
--------------------------------------------------------------------------------
/client/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import {NavigationContainer} from '@react-navigation/native';
3 | import Main from './Navigations/Main';
4 | import Auth from './Navigations/Auth';
5 | import Store from './redux/Store';
6 | import {Provider, useDispatch, useSelector} from 'react-redux';
7 | import {getAllUsers, loadUser} from './redux/actions/userAction';
8 | import Loader from './src/common/Loader';
9 | import {LogBox} from 'react-native';
10 | import {StatusBar} from 'native-base';
11 | import { getAllPosts } from './redux/actions/postAction';
12 | LogBox.ignoreAllLogs();
13 |
14 | function App() {
15 | return (
16 |
17 |
18 |
19 | );
20 | }
21 |
22 | const AppStack = () => {
23 | const {isAuthenticated, loading} = useSelector((state: any) => state.user);
24 | // const dispatch = useDispatch();
25 |
26 | React.useEffect(() => {
27 | Store.dispatch(loadUser());
28 | }, []);
29 |
30 | return (
31 | <>
32 | <>
33 |
39 | >
40 | {loading ? (
41 |
42 | ) : (
43 | <>
44 | {isAuthenticated ? (
45 |
46 |
47 |
48 | ) : (
49 |
50 |
51 |
52 | )}
53 | >
54 | )}
55 | >
56 | );
57 | };
58 |
59 | export default App;
60 |
--------------------------------------------------------------------------------
/client/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
4 | ruby ">= 2.6.10"
5 |
6 | gem 'cocoapods', '~> 1.12'
7 |
--------------------------------------------------------------------------------
/client/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GEM
2 | remote: https://rubygems.org/
3 | specs:
4 | CFPropertyList (3.0.6)
5 | rexml
6 | activesupport (6.1.7.4)
7 | concurrent-ruby (~> 1.0, >= 1.0.2)
8 | i18n (>= 1.6, < 2)
9 | minitest (>= 5.1)
10 | tzinfo (~> 2.0)
11 | zeitwerk (~> 2.3)
12 | addressable (2.8.4)
13 | public_suffix (>= 2.0.2, < 6.0)
14 | algoliasearch (1.27.5)
15 | httpclient (~> 2.8, >= 2.8.3)
16 | json (>= 1.5.1)
17 | atomos (0.1.3)
18 | claide (1.1.0)
19 | cocoapods (1.12.1)
20 | addressable (~> 2.8)
21 | claide (>= 1.0.2, < 2.0)
22 | cocoapods-core (= 1.12.1)
23 | cocoapods-deintegrate (>= 1.0.3, < 2.0)
24 | cocoapods-downloader (>= 1.6.0, < 2.0)
25 | cocoapods-plugins (>= 1.0.0, < 2.0)
26 | cocoapods-search (>= 1.0.0, < 2.0)
27 | cocoapods-trunk (>= 1.6.0, < 2.0)
28 | cocoapods-try (>= 1.1.0, < 2.0)
29 | colored2 (~> 3.1)
30 | escape (~> 0.0.4)
31 | fourflusher (>= 2.3.0, < 3.0)
32 | gh_inspector (~> 1.0)
33 | molinillo (~> 0.8.0)
34 | nap (~> 1.0)
35 | ruby-macho (>= 2.3.0, < 3.0)
36 | xcodeproj (>= 1.21.0, < 2.0)
37 | cocoapods-core (1.12.1)
38 | activesupport (>= 5.0, < 8)
39 | addressable (~> 2.8)
40 | algoliasearch (~> 1.0)
41 | concurrent-ruby (~> 1.1)
42 | fuzzy_match (~> 2.0.4)
43 | nap (~> 1.0)
44 | netrc (~> 0.11)
45 | public_suffix (~> 4.0)
46 | typhoeus (~> 1.0)
47 | cocoapods-deintegrate (1.0.5)
48 | cocoapods-downloader (1.6.3)
49 | cocoapods-plugins (1.0.0)
50 | nap
51 | cocoapods-search (1.0.1)
52 | cocoapods-trunk (1.6.0)
53 | nap (>= 0.8, < 2.0)
54 | netrc (~> 0.11)
55 | cocoapods-try (1.2.0)
56 | colored2 (3.1.2)
57 | concurrent-ruby (1.2.2)
58 | escape (0.0.4)
59 | ethon (0.16.0)
60 | ffi (>= 1.15.0)
61 | ffi (1.15.5)
62 | fourflusher (2.3.1)
63 | fuzzy_match (2.0.4)
64 | gh_inspector (1.1.3)
65 | httpclient (2.8.3)
66 | i18n (1.14.1)
67 | concurrent-ruby (~> 1.0)
68 | json (2.6.3)
69 | minitest (5.18.1)
70 | molinillo (0.8.0)
71 | nanaimo (0.3.0)
72 | nap (1.1.0)
73 | netrc (0.11.0)
74 | public_suffix (4.0.7)
75 | rexml (3.2.5)
76 | ruby-macho (2.5.1)
77 | typhoeus (1.4.0)
78 | ethon (>= 0.9.0)
79 | tzinfo (2.0.6)
80 | concurrent-ruby (~> 1.0)
81 | xcodeproj (1.22.0)
82 | CFPropertyList (>= 2.3.3, < 4.0)
83 | atomos (~> 0.1.3)
84 | claide (>= 1.0.2, < 2.0)
85 | colored2 (~> 3.1)
86 | nanaimo (~> 0.3.0)
87 | rexml (~> 3.2.4)
88 | zeitwerk (2.6.8)
89 |
90 | PLATFORMS
91 | ruby
92 |
93 | DEPENDENCIES
94 | cocoapods (~> 1.12)
95 |
96 | RUBY VERSION
97 | ruby 2.6.10p210
98 |
99 | BUNDLED WITH
100 | 1.17.2
101 |
--------------------------------------------------------------------------------
/client/Navigations/Auth.tsx:
--------------------------------------------------------------------------------
1 | import {useEffect, useState} from 'react';
2 | import LoginScreen from '../src/screens/LoginScreen';
3 | import SignUpScreen from '../src/screens/SignupScreen';
4 | import {createNativeStackNavigator} from '@react-navigation/native-stack';
5 |
6 | const Auth = () => {
7 | const Stack = createNativeStackNavigator();
8 |
9 | return (
10 |
15 |
16 |
17 |
18 | );
19 | };
20 |
21 | export default Auth;
22 |
--------------------------------------------------------------------------------
/client/Navigations/Main.tsx:
--------------------------------------------------------------------------------
1 | import {useEffect, useState} from 'react';
2 | import {createNativeStackNavigator} from '@react-navigation/native-stack';
3 | import Tabs from "./Tabs";
4 | import UserProfileScreen from '../src/screens/UserProfileScreen';
5 | import CreateRepliesScreen from "../src/screens/CreateRepliesScreen";
6 | import PostDetailsScreen from "../src/screens/PostDetailsScreen";
7 | import PostLikeCard from '../src/components/PostLikeCard';
8 | import FollowerCard from '../src/components/FollowerCard';
9 | import EditProfile from "../src/components/EditProfile";
10 |
11 | type Props = {};
12 |
13 | const Main = (props: Props) => {
14 | const Stack = createNativeStackNavigator();
15 | return (
16 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 | );
29 | };
30 |
31 | export default Main;
32 |
--------------------------------------------------------------------------------
/client/Navigations/Tabs.tsx:
--------------------------------------------------------------------------------
1 | import {Image, TouchableOpacity} from 'react-native';
2 | import React, {useEffect} from 'react';
3 | import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
4 | import HomeScreen from '../src/screens/HomeScreen';
5 | import SearchScreen from '../src/screens/SearchScreen';
6 | import PostScreen from '../src/screens/PostScreen';
7 | import NotificationScreen from '../src/screens/NotificationScreen';
8 | import ProfileScreen from '../src/screens/ProfileScreen';
9 | import {getAllPosts} from '../redux/actions/postAction';
10 | import {useDispatch} from 'react-redux';
11 | import {loadUser} from '../redux/actions/userAction';
12 |
13 | type Props = {};
14 |
15 | const Tab = createBottomTabNavigator();
16 |
17 | const Tabs = (props: Props) => {
18 | return (
19 |
26 | ({
30 | tabBarIcon: ({focused}) => (
31 |
43 | ),
44 | })}
45 | />
46 |
47 | ({
51 | tabBarIcon: ({focused}) => (
52 |
64 | ),
65 | })}
66 | />
67 |
68 | ({
72 | tabBarStyle: {display: route.name === 'Post' ? 'none' : 'flex'},
73 | tabBarIcon: ({focused}) => (
74 |
86 | ),
87 | })}
88 | />
89 |
90 | ({
94 | tabBarIcon: ({focused}) => (
95 |
107 | ),
108 | })}
109 | />
110 |
111 | ({
115 | tabBarIcon: ({focused}) => (
116 |
128 | ),
129 | })}
130 | />
131 |
132 | );
133 | };
134 |
135 | export default Tabs;
136 |
--------------------------------------------------------------------------------
/client/README.md:
--------------------------------------------------------------------------------
1 | This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli).
2 |
3 | # Getting Started
4 |
5 | >**Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till "Creating a new application" step, before proceeding.
6 |
7 | ## Step 1: Start the Metro Server
8 |
9 | First, you will need to start **Metro**, the JavaScript _bundler_ that ships _with_ React Native.
10 |
11 | To start Metro, run the following command from the _root_ of your React Native project:
12 |
13 | ```bash
14 | # using npm
15 | npm start
16 |
17 | # OR using Yarn
18 | yarn start
19 | ```
20 |
21 | ## Step 2: Start your Application
22 |
23 | Let Metro Bundler run in its _own_ terminal. Open a _new_ terminal from the _root_ of your React Native project. Run the following command to start your _Android_ or _iOS_ app:
24 |
25 | ### For Android
26 |
27 | ```bash
28 | # using npm
29 | npm run android
30 |
31 | # OR using Yarn
32 | yarn android
33 | ```
34 |
35 | ### For iOS
36 |
37 | ```bash
38 | # using npm
39 | npm run ios
40 |
41 | # OR using Yarn
42 | yarn ios
43 | ```
44 |
45 | If everything is set up _correctly_, you should see your new app running in your _Android Emulator_ or _iOS Simulator_ shortly provided you have set up your emulator/simulator correctly.
46 |
47 | This is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively.
48 |
49 | ## Step 3: Modifying your App
50 |
51 | Now that you have successfully run the app, let's modify it.
52 |
53 | 1. Open `App.tsx` in your text editor of choice and edit some lines.
54 | 2. For **Android**: Press the R key twice or select **"Reload"** from the **Developer Menu** (Ctrl + M (on Window and Linux) or Cmd ⌘ + M (on macOS)) to see your changes!
55 |
56 | For **iOS**: Hit Cmd ⌘ + R in your iOS Simulator to reload the app and see your changes!
57 |
58 | ## Congratulations! :tada:
59 |
60 | You've successfully run and modified your React Native App. :partying_face:
61 |
62 | ### Now what?
63 |
64 | - If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).
65 | - If you're curious to learn more about React Native, check out the [Introduction to React Native](https://reactnative.dev/docs/getting-started).
66 |
67 | # Troubleshooting
68 |
69 | If you can't get this to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.
70 |
71 | # Learn More
72 |
73 | To learn more about React Native, take a look at the following resources:
74 |
75 | - [React Native Website](https://reactnative.dev) - learn more about React Native.
76 | - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.
77 | - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.
78 | - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.
79 | - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.
80 |
--------------------------------------------------------------------------------
/client/__tests__/App.test.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * @format
3 | */
4 |
5 | import 'react-native';
6 | import React from 'react';
7 | import App from '../App';
8 |
9 | // Note: import explicitly to use the types shiped with jest.
10 | import {it} from '@jest/globals';
11 |
12 | // Note: test renderer must be required after react-native.
13 | import renderer from 'react-test-renderer';
14 |
15 | it('renders correctly', () => {
16 | renderer.create( );
17 | });
18 |
--------------------------------------------------------------------------------
/client/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 | apply plugin: "com.facebook.react"
3 | apply plugin: 'com.android.application'
4 |
5 | /**
6 | * This is the configuration block to customize your React Native Android app.
7 | * By default you don't need to apply any configuration, just uncomment the lines you need.
8 |
9 | */
10 | react {
11 | /* Folders */
12 | // The root of your project, i.e. where "package.json" lives. Default is '..'
13 | // root = file("../")
14 | // The folder where the react-native NPM package is. Default is ../node_modules/react-native
15 | // reactNativeDir = file("../node_modules/react-native")
16 | // The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
17 | // codegenDir = file("../node_modules/@react-native/codegen")
18 | // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
19 | // cliFile = file("../node_modules/react-native/cli.js")
20 |
21 | /* Variants */
22 | // The list of variants to that are debuggable. For those we're going to
23 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'.
24 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
25 | // debuggableVariants = ["liteDebug", "prodDebug"]
26 |
27 | /* Bundling */
28 | // A list containing the node command and its flags. Default is just 'node'.
29 | // nodeExecutableAndArgs = ["node"]
30 | //
31 | // The command to run when bundling. By default is 'bundle'
32 | // bundleCommand = "ram-bundle"
33 | //
34 | // The path to the CLI configuration file. Default is empty.
35 | // bundleConfig = file(../rn-cli.config.js)
36 | //
37 | // The name of the generated asset file containing your JS bundle
38 | // bundleAssetName = "MyApplication.android.bundle"
39 | //
40 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
41 | // entryFile = file("../js/MyApplication.android.js")
42 | //
43 | // A list of extra flags to pass to the 'bundle' commands.
44 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
45 | // extraPackagerArgs = []
46 |
47 | /* Hermes Commands */
48 | // The hermes compiler command to run. By default it is 'hermesc'
49 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
50 | //
51 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
52 | // hermesFlags = ["-O", "-output-source-map"]
53 | }
54 |
55 | /**
56 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
57 | */
58 | def enableProguardInReleaseBuilds = true
59 |
60 | /**
61 | * The preferred build flavor of JavaScriptCore (JSC)
62 | *
63 | * For example, to use the international variant, you can use:
64 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
65 | *
66 | * The international variant includes ICU i18n library and necessary data
67 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
68 | * give correct results when using with locales other than en-US. Note that
69 | * this variant is about 6MiB larger per architecture than default.
70 | */
71 | def jscFlavor = 'org.webkit:android-jsc:+'
72 |
73 | android {
74 | ndkVersion rootProject.ext.ndkVersion
75 | compileSdkVersion 31
76 | buildToolsVersion "31.0.0"
77 | compileSdkVersion rootProject.ext.compileSdkVersion
78 |
79 | namespace "com.becodemy.threads"
80 | defaultConfig {
81 | applicationId "com.becodemy.threads"
82 | minSdkVersion rootProject.ext.minSdkVersion
83 | vectorDrawables.useSupportLibrary = true
84 | targetSdkVersion rootProject.ext.targetSdkVersion
85 | versionCode 1
86 | versionName "1.0"
87 | targetSdkVersion 31
88 | }
89 | signingConfigs {
90 | release {
91 | if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
92 | storeFile file(MYAPP_UPLOAD_STORE_FILE)
93 | storePassword MYAPP_UPLOAD_STORE_PASSWORD
94 | keyAlias MYAPP_UPLOAD_KEY_ALIAS
95 | keyPassword MYAPP_UPLOAD_KEY_PASSWORD
96 | }
97 | }
98 | }
99 | buildTypes {
100 | debug {
101 | signingConfig signingConfigs.debug
102 | }
103 | release {
104 | // Caution! In production, you need to generate your own keystore file.
105 | // see https://reactnative.dev/docs/signed-apk-android.
106 | signingConfig signingConfigs.release
107 | minifyEnabled enableProguardInReleaseBuilds
108 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
109 | }
110 | }
111 | }
112 |
113 | dependencies {
114 | // The version of react-native is set by the React Native Gradle Plugin
115 | implementation("com.facebook.react:react-android")
116 |
117 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
118 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
119 | exclude group:'com.squareup.okhttp3', module:'okhttp'
120 | }
121 |
122 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")
123 | if (hermesEnabled.toBoolean()) {
124 | implementation("com.facebook.react:hermes-android")
125 | } else {
126 | implementation jscFlavor
127 | }
128 | }
129 |
130 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
131 |
--------------------------------------------------------------------------------
/client/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/debug.keystore
--------------------------------------------------------------------------------
/client/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/client/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/client/android/app/src/debug/java/com/becodemy/threads/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.becodemy.threads;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
21 | import com.facebook.react.ReactInstanceEventListener;
22 | import com.facebook.react.ReactInstanceManager;
23 | import com.facebook.react.bridge.ReactContext;
24 | import com.facebook.react.modules.network.NetworkingModule;
25 | import okhttp3.OkHttpClient;
26 |
27 | /**
28 | * Class responsible of loading Flipper inside your React Native application. This is the debug
29 | * flavor of it. Here you can add your own plugins and customize the Flipper setup.
30 | */
31 | public class ReactNativeFlipper {
32 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
33 | if (FlipperUtils.shouldEnableFlipper(context)) {
34 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
35 |
36 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
37 | client.addPlugin(new DatabasesFlipperPlugin(context));
38 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
39 | client.addPlugin(CrashReporterPlugin.getInstance());
40 |
41 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
42 | NetworkingModule.setCustomClientBuilder(
43 | new NetworkingModule.CustomClientBuilder() {
44 | @Override
45 | public void apply(OkHttpClient.Builder builder) {
46 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
47 | }
48 | });
49 | client.addPlugin(networkFlipperPlugin);
50 | client.start();
51 |
52 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
53 | // Hence we run if after all native modules have been initialized
54 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
55 | if (reactContext == null) {
56 | reactInstanceManager.addReactInstanceEventListener(
57 | new ReactInstanceEventListener() {
58 | @Override
59 | public void onReactContextInitialized(ReactContext reactContext) {
60 | reactInstanceManager.removeReactInstanceEventListener(this);
61 | reactContext.runOnNativeModulesQueueThread(
62 | new Runnable() {
63 | @Override
64 | public void run() {
65 | client.addPlugin(new FrescoFlipperPlugin());
66 | }
67 | });
68 | }
69 | });
70 | } else {
71 | client.addPlugin(new FrescoFlipperPlugin());
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/client/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
12 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/client/android/app/src/main/java/com/becodemy/threads/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.becodemy.threads;
2 |
3 | import com.facebook.react.ReactActivity;
4 | import com.facebook.react.ReactActivityDelegate;
5 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
6 | import com.facebook.react.defaults.DefaultReactActivityDelegate;
7 | import android.os.Bundle;
8 |
9 | public class MainActivity extends ReactActivity {
10 |
11 | /**
12 | * Returns the name of the main component registered from JavaScript. This is used to schedule
13 | * rendering of the component.
14 | */
15 | @Override
16 | protected void onCreate(Bundle savedInstanceState) {
17 | super.onCreate(null);
18 | }
19 |
20 | @Override
21 | protected String getMainComponentName() {
22 | return "Threads clone";
23 | }
24 |
25 | /**
26 | * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link
27 | * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React
28 | * (aka React 18) with two boolean flags.
29 | */
30 | @Override
31 | protected ReactActivityDelegate createReactActivityDelegate() {
32 | return new DefaultReactActivityDelegate(
33 | this,
34 | getMainComponentName(),
35 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
36 | DefaultNewArchitectureEntryPoint.getFabricEnabled());
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/client/android/app/src/main/java/com/becodemy/threads/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.becodemy.threads;
2 |
3 | import android.app.Application;
4 | import com.facebook.react.PackageList;
5 | import com.facebook.react.ReactApplication;
6 | import com.facebook.react.ReactNativeHost;
7 | import com.facebook.react.ReactPackage;
8 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
9 | import com.facebook.react.defaults.DefaultReactNativeHost;
10 | import com.facebook.soloader.SoLoader;
11 | import java.util.List;
12 |
13 | public class MainApplication extends Application implements ReactApplication {
14 |
15 | private final ReactNativeHost mReactNativeHost =
16 | new DefaultReactNativeHost(this) {
17 | @Override
18 | public boolean getUseDeveloperSupport() {
19 | return BuildConfig.DEBUG;
20 | }
21 |
22 | @Override
23 | protected List getPackages() {
24 | @SuppressWarnings("UnnecessaryLocalVariable")
25 | List packages = new PackageList(this).getPackages();
26 | // Packages that cannot be autolinked yet can be added manually here, for example:
27 | // packages.add(new MyReactNativePackage());
28 | return packages;
29 | }
30 |
31 | @Override
32 | protected String getJSMainModuleName() {
33 | return "index";
34 | }
35 |
36 | @Override
37 | protected boolean isNewArchEnabled() {
38 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
39 | }
40 |
41 | @Override
42 | protected Boolean isHermesEnabled() {
43 | return BuildConfig.IS_HERMES_ENABLED;
44 | }
45 | };
46 |
47 | @Override
48 | public ReactNativeHost getReactNativeHost() {
49 | return mReactNativeHost;
50 | }
51 |
52 | @Override
53 | public void onCreate() {
54 | super.onCreate();
55 | SoLoader.init(this, /* native exopackage */ false);
56 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
57 | // If you opted-in for the New Architecture, we load the native entry point for this app.
58 | DefaultNewArchitectureEntryPoint.load();
59 | }
60 | ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/client/android/app/src/main/res/drawable/rn_edit_text_material.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
21 |
22 |
23 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/client/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Threads clone
3 |
4 |
--------------------------------------------------------------------------------
/client/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/client/android/app/src/release/java/com/becodemy/threads/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.becodemy.threads;
8 |
9 | import android.content.Context;
10 | import com.facebook.react.ReactInstanceManager;
11 |
12 | /**
13 | * Class responsible of loading Flipper inside your React Native application. This is the release
14 | * flavor of it so it's empty as we don't want to load Flipper.
15 | */
16 | public class ReactNativeFlipper {
17 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
18 | // Do nothing as we don't want to initialize Flipper on Release.
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/client/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = "33.0.0"
6 | minSdkVersion = 21
7 | compileSdkVersion = 33
8 | targetSdkVersion = 33
9 |
10 | // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
11 | ndkVersion = "23.1.7779620"
12 | }
13 | repositories {
14 | google()
15 | mavenCentral()
16 | maven { url 'https://maven.google.com' }
17 |
18 | // ADD THIS
19 | maven { url "https://www.jitpack.io" }
20 |
21 | }
22 | dependencies {
23 | classpath("com.android.tools.build:gradle:7.2.1")
24 | classpath("com.facebook.react:react-native-gradle-plugin")
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/client/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # AndroidX package structure to make it clearer which packages are bundled with the
21 | # Android operating system, and which are packaged with your app's APK
22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
23 | android.useAndroidX=true
24 | # Automatically convert third-party libraries to use AndroidX
25 | android.enableJetifier=true
26 |
27 | # Version of flipper SDK to use with React Native
28 | FLIPPER_VERSION=0.182.0
29 |
30 | # Use this property to specify which architecture you want to build.
31 | # You can also override it from the CLI using
32 | # ./gradlew -PreactNativeArchitectures=x86_64
33 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
34 |
35 | # Use this property to enable support to the new architecture.
36 | # This will allow you to use TurboModules and the Fabric render in
37 | # your application. You should enable this flag either if you want
38 | # to write custom TurboModules/Fabric components OR use libraries that
39 | # are providing them.
40 | newArchEnabled=false
41 |
42 | # Use this property to enable or disable the Hermes JS engine.
43 | # If set to false, you will be using JSC instead.
44 | hermesEnabled=true
45 |
46 |
47 | MYAPP_UPLOAD_STORE_FILE=my-upload-key.keystore
48 | MYAPP_UPLOAD_KEY_ALIAS=my-key-alias
49 | MYAPP_UPLOAD_STORE_PASSWORD=becodemy
50 | MYAPP_UPLOAD_KEY_PASSWORD=becodemy
--------------------------------------------------------------------------------
/client/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/client/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-all.zip
4 | networkTimeout=10000
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/client/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
147 | # shellcheck disable=SC3045
148 | MAX_FD=$( ulimit -H -n ) ||
149 | warn "Could not query maximum file descriptor limit"
150 | esac
151 | case $MAX_FD in #(
152 | '' | soft) :;; #(
153 | *)
154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
155 | # shellcheck disable=SC3045
156 | ulimit -n "$MAX_FD" ||
157 | warn "Could not set maximum file descriptor limit to $MAX_FD"
158 | esac
159 | fi
160 |
161 | # Collect all arguments for the java command, stacking in reverse order:
162 | # * args from the command line
163 | # * the main class name
164 | # * -classpath
165 | # * -D...appname settings
166 | # * --module-path (only if needed)
167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
168 |
169 | # For Cygwin or MSYS, switch paths to Windows format before running java
170 | if "$cygwin" || "$msys" ; then
171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
173 |
174 | JAVACMD=$( cygpath --unix "$JAVACMD" )
175 |
176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
177 | for arg do
178 | if
179 | case $arg in #(
180 | -*) false ;; # don't mess with options #(
181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
182 | [ -e "$t" ] ;; #(
183 | *) false ;;
184 | esac
185 | then
186 | arg=$( cygpath --path --ignore --mixed "$arg" )
187 | fi
188 | # Roll the args list around exactly as many times as the number of
189 | # args, so each arg winds up back in the position where it started, but
190 | # possibly modified.
191 | #
192 | # NB: a `for` loop captures its iteration list before it begins, so
193 | # changing the positional parameters here affects neither the number of
194 | # iterations, nor the values presented in `arg`.
195 | shift # remove old arg
196 | set -- "$@" "$arg" # push replacement arg
197 | done
198 | fi
199 |
200 | # Collect all arguments for the java command;
201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
202 | # shell script including quotes and variable substitutions, so put them in
203 | # double quotes to make sure that they get re-expanded; and
204 | # * put everything else in single quotes, so that it's not re-expanded.
205 |
206 | set -- \
207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
208 | -classpath "$CLASSPATH" \
209 | org.gradle.wrapper.GradleWrapperMain \
210 | "$@"
211 |
212 | # Stop when "xargs" is not available.
213 | if ! command -v xargs >/dev/null 2>&1
214 | then
215 | die "xargs is not available"
216 | fi
217 |
218 | # Use "xargs" to parse quoted args.
219 | #
220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
221 | #
222 | # In Bash we could simply go:
223 | #
224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
225 | # set -- "${ARGS[@]}" "$@"
226 | #
227 | # but POSIX shell has neither arrays nor command substitution, so instead we
228 | # post-process each arg (as a line of input to sed) to backslash-escape any
229 | # character that might be a shell metacharacter, then use eval to reverse
230 | # that process (while maintaining the separation between arguments), and wrap
231 | # the whole thing up as a single "set" statement.
232 | #
233 | # This will of course break if any of these variables contains a newline or
234 | # an unmatched quote.
235 | #
236 |
237 | eval "set -- $(
238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
239 | xargs -n1 |
240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
241 | tr '\n' ' '
242 | )" '"$@"'
243 |
244 | exec "$JAVACMD" "$@"
245 |
--------------------------------------------------------------------------------
/client/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/client/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'Threads clone'
2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
3 | include ':app'
4 | includeBuild('../node_modules/@react-native/gradle-plugin')
5 |
--------------------------------------------------------------------------------
/client/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Threads clone",
3 | "displayName": "Threads clone"
4 | }
5 |
--------------------------------------------------------------------------------
/client/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | plugins: ["nativewind/babel"],
4 | };
5 |
--------------------------------------------------------------------------------
/client/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @format
3 | */
4 |
5 | import {AppRegistry} from 'react-native';
6 | import App from './App';
7 | import {name as appName} from './app.json';
8 |
9 | AppRegistry.registerComponent(appName, () => App);
10 |
--------------------------------------------------------------------------------
/client/ios/.xcode.env:
--------------------------------------------------------------------------------
1 | # This `.xcode.env` file is versioned and is used to source the environment
2 | # used when running script phases inside Xcode.
3 | # To customize your local environment, you can create an `.xcode.env.local`
4 | # file that is not versioned.
5 |
6 | # NODE_BINARY variable contains the PATH to the node executable.
7 | #
8 | # Customize the NODE_BINARY variable here.
9 | # For example, to use nvm with brew, add the following line
10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use
11 | export NODE_BINARY=$(command -v node)
12 |
--------------------------------------------------------------------------------
/client/ios/Podfile:
--------------------------------------------------------------------------------
1 | # Resolve react_native_pods.rb with node to allow for hoisting
2 | require Pod::Executable.execute_command('node', ['-p',
3 | 'require.resolve(
4 | "react-native/scripts/react_native_pods.rb",
5 | {paths: [process.argv[1]]},
6 | )', __dir__]).strip
7 |
8 | platform :ios, min_ios_version_supported
9 | prepare_react_native_project!
10 |
11 | # If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
12 | # because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
13 | #
14 | # To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
15 | # ```js
16 | # module.exports = {
17 | # dependencies: {
18 | # ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
19 | # ```
20 | flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled
21 |
22 | linkage = ENV['USE_FRAMEWORKS']
23 | if linkage != nil
24 | Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
25 | use_frameworks! :linkage => linkage.to_sym
26 | end
27 |
28 | target 'Threadsclone' do
29 | config = use_native_modules!
30 |
31 | # Flags change depending on the env values.
32 | flags = get_default_flags()
33 |
34 | use_react_native!(
35 | :path => config[:reactNativePath],
36 | # Hermes is now enabled by default. Disable by setting this flag to false.
37 | :hermes_enabled => flags[:hermes_enabled],
38 | :fabric_enabled => flags[:fabric_enabled],
39 | # Enables Flipper.
40 | #
41 | # Note that if you have use_frameworks! enabled, Flipper will not work and
42 | # you should disable the next line.
43 | :flipper_configuration => flipper_config,
44 | # An absolute path to your application root.
45 | :app_path => "#{Pod::Config.instance.installation_root}/.."
46 | )
47 |
48 | target 'ThreadscloneTests' do
49 | inherit! :complete
50 | # Pods for testing
51 | end
52 |
53 | post_install do |installer|
54 | # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
55 | react_native_post_install(
56 | installer,
57 | config[:reactNativePath],
58 | :mac_catalyst_enabled => false
59 | )
60 | __apply_Xcode_12_5_M1_post_install_workaround(installer)
61 | end
62 | end
63 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone.xcodeproj/xcshareddata/xcschemes/Threadsclone.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone/AppDelegate.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | @interface AppDelegate : RCTAppDelegate
5 |
6 | @end
7 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone/AppDelegate.mm:
--------------------------------------------------------------------------------
1 | #import "AppDelegate.h"
2 |
3 | #import
4 |
5 | @implementation AppDelegate
6 |
7 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
8 | {
9 | self.moduleName = @"Threads clone";
10 | // You can add your custom initial props in the dictionary below.
11 | // They will be passed down to the ViewController used by React Native.
12 | self.initialProps = @{};
13 |
14 | return [super application:application didFinishLaunchingWithOptions:launchOptions];
15 | }
16 |
17 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
18 | {
19 | #if DEBUG
20 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
21 | #else
22 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
23 | #endif
24 | }
25 |
26 | @end
27 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ios-marketing",
45 | "scale" : "1x",
46 | "size" : "1024x1024"
47 | }
48 | ],
49 | "info" : {
50 | "author" : "xcode",
51 | "version" : 1
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | Threads clone
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(MARKETING_VERSION)
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | $(CURRENT_PROJECT_VERSION)
25 | LSRequiresIPhoneOS
26 |
27 | NSAppTransportSecurity
28 |
29 | NSExceptionDomains
30 |
31 | localhost
32 |
33 | NSExceptionAllowsInsecureHTTPLoads
34 |
35 |
36 |
37 |
38 | NSPhotoLibraryUsageDescription
39 | For create post and account we need your gallery!
40 | NSLocationWhenInUseUsageDescription
41 |
42 | UILaunchStoryboardName
43 | LaunchScreen
44 | UIRequiredDeviceCapabilities
45 |
46 | armv7
47 |
48 | UISupportedInterfaceOrientations
49 |
50 | UIInterfaceOrientationPortrait
51 | UIInterfaceOrientationLandscapeLeft
52 | UIInterfaceOrientationLandscapeRight
53 |
54 | UIViewControllerBasedStatusBarAppearance
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/client/ios/Threadsclone/main.m:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | #import "AppDelegate.h"
4 |
5 | int main(int argc, char *argv[])
6 | {
7 | @autoreleasepool {
8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/client/ios/ThreadscloneTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/client/ios/ThreadscloneTests/ThreadscloneTests.m:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | #import
5 | #import
6 |
7 | #define TIMEOUT_SECONDS 600
8 | #define TEXT_TO_LOOK_FOR @"Welcome to React"
9 |
10 | @interface ThreadscloneTests : XCTestCase
11 |
12 | @end
13 |
14 | @implementation ThreadscloneTests
15 |
16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test
17 | {
18 | if (test(view)) {
19 | return YES;
20 | }
21 | for (UIView *subview in [view subviews]) {
22 | if ([self findSubviewInView:subview matching:test]) {
23 | return YES;
24 | }
25 | }
26 | return NO;
27 | }
28 |
29 | - (void)testRendersWelcomeScreen
30 | {
31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
33 | BOOL foundElement = NO;
34 |
35 | __block NSString *redboxError = nil;
36 | #ifdef DEBUG
37 | RCTSetLogFunction(
38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
39 | if (level >= RCTLogLevelError) {
40 | redboxError = message;
41 | }
42 | });
43 | #endif
44 |
45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
48 |
49 | foundElement = [self findSubviewInView:vc.view
50 | matching:^BOOL(UIView *view) {
51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
52 | return YES;
53 | }
54 | return NO;
55 | }];
56 | }
57 |
58 | #ifdef DEBUG
59 | RCTSetLogFunction(RCTDefaultLogFunction);
60 | #endif
61 |
62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
64 | }
65 |
66 | @end
67 |
--------------------------------------------------------------------------------
/client/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: 'react-native',
3 | };
4 |
--------------------------------------------------------------------------------
/client/metro.config.js:
--------------------------------------------------------------------------------
1 | const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
2 |
3 | /**
4 | * Metro configuration
5 | * https://facebook.github.io/metro/docs/configuration
6 | *
7 | * @type {import('metro-config').MetroConfig}
8 | */
9 | const config = {};
10 |
11 | module.exports = mergeConfig(getDefaultConfig(__dirname), config);
12 |
--------------------------------------------------------------------------------
/client/my-app.d.ts:
--------------------------------------------------------------------------------
1 | ///
--------------------------------------------------------------------------------
/client/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "threadsclone",
3 | "version": "0.0.1",
4 | "private": true,
5 | "scripts": {
6 | "android": "react-native run-android",
7 | "ios": "react-native run-ios",
8 | "lint": "eslint .",
9 | "start": "react-native start",
10 | "test": "jest"
11 | },
12 | "dependencies": {
13 | "@react-native-async-storage/async-storage": "^1.19.0",
14 | "@react-navigation/bottom-tabs": "^6.5.8",
15 | "@react-navigation/native": "^6.1.7",
16 | "@react-navigation/native-stack": "^6.9.13",
17 | "@reduxjs/toolkit": "^1.9.5",
18 | "axios": "^1.4.0",
19 | "lottie-react-native": "^5.1.6",
20 | "moment": "^2.29.4",
21 | "native-base": "^3.4.28",
22 | "nativewind": "^2.0.11",
23 | "react": "18.2.0",
24 | "react-native": "0.72.1",
25 | "react-native-image-crop-picker": "^0.40.0",
26 | "react-native-safe-area-context": "^4.6.4",
27 | "react-native-screens": "^3.22.1",
28 | "react-native-svg": "^13.10.0",
29 | "react-redux": "^8.1.1",
30 | "redux": "^4.2.1",
31 | "tailwind-react-native-classnames": "^1.5.1"
32 | },
33 | "devDependencies": {
34 | "@babel/core": "^7.20.0",
35 | "@babel/preset-env": "^7.20.0",
36 | "@babel/runtime": "^7.20.0",
37 | "@react-native/eslint-config": "^0.72.2",
38 | "@react-native/metro-config": "^0.72.7",
39 | "@tsconfig/react-native": "^3.0.0",
40 | "@types/metro-config": "^0.76.3",
41 | "@types/react": "^18.0.24",
42 | "@types/react-native-vector-icons": "^6.4.13",
43 | "@types/react-test-renderer": "^18.0.0",
44 | "babel-jest": "^29.2.1",
45 | "eslint": "^8.19.0",
46 | "jest": "^29.2.1",
47 | "metro-react-native-babel-preset": "0.76.5",
48 | "prettier": "^2.4.1",
49 | "react-test-renderer": "18.2.0",
50 | "tailwindcss": "^3.3.2",
51 | "typescript": "4.8.4"
52 | },
53 | "engines": {
54 | "node": ">=16"
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/client/redux/Store.ts:
--------------------------------------------------------------------------------
1 | import { configureStore } from "@reduxjs/toolkit";
2 | import { userReducer } from "./reducers/userReducer";
3 | import { postReducer } from "./reducers/postReducer";
4 | import { notificationReducer } from "./reducers/notificationReducer";
5 |
6 |
7 | const Store = configureStore({
8 | reducer:{
9 | user: userReducer,
10 | post: postReducer,
11 | notification: notificationReducer,
12 | },
13 | middleware: getDefaultMiddleware =>
14 | getDefaultMiddleware({
15 | immutableCheck: false,
16 | serializableCheck: false,
17 | }),
18 | });
19 |
20 | export default Store;
--------------------------------------------------------------------------------
/client/redux/URI.tsx:
--------------------------------------------------------------------------------
1 | import {Platform} from 'react-native';
2 |
3 | let URI = '';
4 |
5 | if (Platform.OS === 'ios') {
6 | URI = 'https://threads-clone-ten.vercel.app/api/v1';
7 | } else {
8 | URI = 'https://threads-clone-ten.vercel.app/api/v1';
9 | }
10 |
11 | export {URI};
12 |
--------------------------------------------------------------------------------
/client/redux/actions/notificationAction.ts:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 | import {URI} from '../URI';
3 | import {Dispatch} from 'react';
4 | import AsyncStorage from '@react-native-async-storage/async-storage';
5 |
6 | // get notifications
7 | export const getNotifications = () => async (dispatch: Dispatch) => {
8 | try {
9 | dispatch({
10 | type: 'getNotificationRequest',
11 | });
12 |
13 | const token = await AsyncStorage.getItem('token');
14 |
15 | const {data} = await axios.get(`${URI}/get-notifications`, {
16 | headers: {
17 | Authorization: `Bearer ${token}`,
18 | },
19 | });
20 |
21 | dispatch({
22 | type: 'getNotificationSuccess',
23 | payload: data.notifications,
24 | });
25 | } catch (error: any) {
26 | dispatch({
27 | type: 'getNotificationFailed',
28 | payload: error.response.data.message,
29 | });
30 | }
31 | };
32 |
--------------------------------------------------------------------------------
/client/redux/actions/postAction.ts:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 | import {URI} from '../URI';
3 | import {Dispatch} from 'react';
4 | import AsyncStorage from '@react-native-async-storage/async-storage';
5 |
6 | // create post
7 | export const createPostAction =
8 | (
9 | title: string,
10 | image: string,
11 | user: Object,
12 | replies: Array<{title: string; image: string; user: any}>,
13 | ) =>
14 | async (dispatch: Dispatch) => {
15 | try {
16 | dispatch({
17 | type: 'postCreateRequest',
18 | });
19 |
20 | const token = await AsyncStorage.getItem('token');
21 |
22 | const {data} = await axios.post(
23 | `${URI}/create-post`,
24 | {title, image, user, replies},
25 | {
26 | headers: {
27 | Authorization: `Bearer ${token}`,
28 | },
29 | },
30 | );
31 | dispatch({
32 | type: 'postCreateSuccess',
33 | payload: data.user,
34 | });
35 | } catch (error: any) {
36 | dispatch({
37 | type: 'postCreateFailed',
38 | payload: error.response.data.message,
39 | });
40 | }
41 | };
42 |
43 | // get all Posts
44 | export const getAllPosts = () => async (dispatch: Dispatch) => {
45 | try {
46 | dispatch({
47 | type: 'getAllPostsRequest',
48 | });
49 |
50 | const token = await AsyncStorage.getItem('token');
51 |
52 | const {data} = await axios.get(`${URI}/get-all-posts`, {
53 | headers: {
54 | Authorization: `Bearer ${token}`,
55 | },
56 | });
57 |
58 | dispatch({
59 | type: 'getAllPostsSuccess',
60 | payload: data.posts,
61 | });
62 | } catch (error: any) {
63 | dispatch({
64 | type: 'getAllPostsFailed',
65 | payload: error.response.data.message,
66 | });
67 | }
68 | };
69 |
70 | interface LikesParams {
71 | postId?: string | null;
72 | posts: any;
73 | user: any;
74 | replyId?: string | null;
75 | title?: string;
76 | singleReplyId?: string;
77 | }
78 |
79 | // add likes
80 | export const addLikes =
81 | ({postId, posts, user}: LikesParams) =>
82 | async (dispatch: Dispatch) => {
83 | try {
84 | const token = await AsyncStorage.getItem('token');
85 |
86 | const updatedPosts = posts.map((userObj: any) =>
87 | userObj._id === postId
88 | ? {
89 | ...userObj,
90 | likes: [
91 | ...userObj.likes,
92 | {
93 | userName: user.name,
94 | userId: user._id,
95 | userAvatar: user.avatar.url,
96 | postId,
97 | },
98 | ],
99 | }
100 | : userObj,
101 | );
102 |
103 | dispatch({
104 | type: 'getAllPostsSuccess',
105 | payload: updatedPosts,
106 | });
107 |
108 | await axios.put(
109 | `${URI}/update-likes`,
110 | {postId},
111 | {
112 | headers: {
113 | Authorization: `Bearer ${token}`,
114 | },
115 | },
116 | );
117 | } catch (error: any) {
118 | console.log(error, 'error');
119 | }
120 | };
121 |
122 | // remove likes
123 | export const removeLikes =
124 | ({postId, posts, user}: LikesParams) =>
125 | async (dispatch: Dispatch) => {
126 | try {
127 | const token = await AsyncStorage.getItem('token');
128 |
129 | const updatedPosts = posts.map((userObj: any) =>
130 | userObj._id === postId
131 | ? {
132 | ...userObj,
133 | likes: userObj.likes.filter(
134 | (like: any) => like.userId !== user._id,
135 | ),
136 | }
137 | : userObj,
138 | );
139 | dispatch({
140 | type: 'getAllPostsSuccess',
141 | payload: updatedPosts,
142 | });
143 |
144 | await axios.put(
145 | `${URI}/update-likes`,
146 | {postId},
147 | {
148 | headers: {
149 | Authorization: `Bearer ${token}`,
150 | },
151 | },
152 | );
153 | } catch (error) {
154 | console.error('Error following likes:', error);
155 | }
156 | };
157 |
158 | // add likes to reply
159 | export const addLikesToReply =
160 | ({postId, posts, user, replyId, title}: LikesParams) =>
161 | async (dispatch: Dispatch) => {
162 | try {
163 | const token = await AsyncStorage.getItem('token');
164 | const updatedPosts = posts.map((post: any) =>
165 | post._id === postId
166 | ? {
167 | ...post,
168 | replies: post.replies.map((reply: any) =>
169 | reply._id === replyId
170 | ? {
171 | ...reply,
172 | likes: [
173 | ...reply.likes,
174 | {
175 | userName: user.name,
176 | userId: user._id,
177 | userAvatar: user.avatar.url,
178 | },
179 | ],
180 | }
181 | : reply,
182 | ),
183 | }
184 | : post,
185 | );
186 | dispatch({
187 | type: 'getAllPostsSuccess',
188 | payload: updatedPosts,
189 | });
190 |
191 | await axios.put(
192 | `${URI}/update-replies-react`,
193 | {postId, replyId, replyTitle: title},
194 | {
195 | headers: {
196 | Authorization: `Bearer ${token}`,
197 | },
198 | },
199 | );
200 | } catch (error) {
201 | console.log(error, 'error');
202 | }
203 | };
204 |
205 | // remove likes from reply
206 | export const removeLikesFromReply =
207 | ({postId, posts, user, replyId}: LikesParams) =>
208 | async (dispatch: Dispatch) => {
209 | try {
210 | const token = await AsyncStorage.getItem('token');
211 |
212 | const updatedPosts = posts.map((post: any) =>
213 | post._id === postId
214 | ? {
215 | ...post,
216 | replies: post.replies.map((reply: any) =>
217 | reply._id === replyId
218 | ? {
219 | ...reply,
220 | likes: reply.likes.filter(
221 | (like: any) => like.userId !== user._id,
222 | ),
223 | }
224 | : reply,
225 | ),
226 | }
227 | : post,
228 | );
229 |
230 | dispatch({
231 | type: 'getAllPostsSuccess',
232 | payload: updatedPosts,
233 | });
234 |
235 | await axios.put(
236 | `${URI}/update-replies-react`,
237 | {postId, replyId},
238 | {
239 | headers: {
240 | Authorization: `Bearer ${token}`,
241 | },
242 | },
243 | );
244 | } catch (error: any) {
245 | console.log(error, 'error');
246 | }
247 | };
248 |
249 | // add likes to replies > reply
250 | export const addLikesToRepliesReply =
251 | ({postId, posts, user, replyId, singleReplyId, title}: LikesParams) =>
252 | async (dispatch: Dispatch) => {
253 | try {
254 | const token = await AsyncStorage.getItem('token');
255 |
256 | const updatedPosts = posts.map((post: any) =>
257 | post._id === postId
258 | ? {
259 | ...post,
260 | replies: post.replies.map((r: any) =>
261 | r._id === replyId
262 | ? {
263 | ...r,
264 | reply: r.reply.map((reply: any) =>
265 | reply._id === singleReplyId
266 | ? {
267 | ...reply,
268 | likes: [
269 | ...reply.likes,
270 | {
271 | userName: user.name,
272 | userId: user._id,
273 | userAvatar: user.avatar.url,
274 | },
275 | ],
276 | }
277 | : reply,
278 | ),
279 | }
280 | : r,
281 | ),
282 | }
283 | : post,
284 | );
285 |
286 | dispatch({
287 | type: 'getAllPostsSuccess',
288 | payload: updatedPosts,
289 | });
290 | await axios.put(
291 | `${URI}/update-reply-react`,
292 | {postId, replyId, singleReplyId, replyTitle: title},
293 | {
294 | headers: {
295 | Authorization: `Bearer ${token}`,
296 | },
297 | },
298 | );
299 | } catch (error) {
300 | console.log(error, 'error');
301 | }
302 | };
303 |
304 | // remove likes from replies > reply
305 | export const removeLikesFromRepliesReply =
306 | ({postId, posts, user, replyId, singleReplyId}: LikesParams) =>
307 | async (dispatch: Dispatch) => {
308 | try {
309 | const token = await AsyncStorage.getItem('token');
310 |
311 | const updatedPosts = posts.map((post: any) =>
312 | post._id === postId
313 | ? {
314 | ...post,
315 | replies: post.replies.map((r: any) =>
316 | r._id === replyId
317 | ? {
318 | ...r,
319 | reply: r.reply.map((reply: any) =>
320 | reply._id === singleReplyId
321 | ? {
322 | ...reply,
323 | likes: reply.likes.filter(
324 | (like: any) => like.userId !== user._id,
325 | ),
326 | }
327 | : reply,
328 | ),
329 | }
330 | : r,
331 | ),
332 | }
333 | : post,
334 | );
335 |
336 | dispatch({
337 | type: 'getAllPostsSuccess',
338 | payload: updatedPosts,
339 | });
340 |
341 | await axios.put(
342 | `${URI}/update-reply-react`,
343 | {postId, replyId, singleReplyId},
344 | {
345 | headers: {
346 | Authorization: `Bearer ${token}`,
347 | },
348 | },
349 | );
350 | } catch (error: any) {
351 | console.log(error, 'error');
352 | }
353 | };
354 |
--------------------------------------------------------------------------------
/client/redux/actions/userAction.ts:
--------------------------------------------------------------------------------
1 | import axios from 'axios';
2 | import {URI} from '../URI';
3 | import {Dispatch} from 'react';
4 | import AsyncStorage from '@react-native-async-storage/async-storage';
5 |
6 | // register user
7 | export const registerUser =
8 | (name: string, email: string, password: string, avatar: string) =>
9 | async (dispatch: Dispatch) => {
10 | try {
11 | dispatch({
12 | type: 'userRegisterRequest',
13 | });
14 |
15 | const config = {headers: {'Content-Type': 'application/json'}};
16 |
17 | const {data} = await axios.post(
18 | `${URI}/registration`,
19 | {name, email, password, avatar},
20 | config,
21 | );
22 | dispatch({
23 | type: 'userRegisterSuccess',
24 | payload: data.user,
25 | });
26 | await AsyncStorage.setItem('token', data.token);
27 | } catch (error: any) {
28 | dispatch({
29 | type: 'userRegisterFailed',
30 | payload: error.response.data.message,
31 | });
32 | }
33 | };
34 |
35 | // load user
36 | export const loadUser = () => async (dispatch: Dispatch) => {
37 | try {
38 | dispatch({
39 | type: 'userLoadRequest',
40 | });
41 |
42 | const token = await AsyncStorage.getItem('token');
43 |
44 | const {data} = await axios.get(`${URI}/me`, {
45 | headers: {Authorization: `Bearer ${token}`},
46 | });
47 |
48 | dispatch({
49 | type: 'userLoadSuccess',
50 | payload: {
51 | user: data.user,
52 | token,
53 | },
54 | });
55 | } catch (error: any) {
56 | dispatch({
57 | type: 'userLoadFailed',
58 | payload: error.response.data.message,
59 | });
60 | }
61 | };
62 |
63 | // login user
64 | export const loginUser =
65 | (email: string, password: string) => async (dispatch: Dispatch) => {
66 | try {
67 | dispatch({
68 | type: 'userLoginRequest',
69 | });
70 |
71 | const config = {headers: {'Content-Type': 'application/json'}};
72 |
73 | const {data} = await axios.post(
74 | `${URI}/login`,
75 | {email, password},
76 | config,
77 | );
78 | dispatch({
79 | type: 'userLoginSuccess',
80 | payload: data.user,
81 | });
82 | if (data.token) {
83 | await AsyncStorage.setItem('token', data.token);
84 | }
85 | } catch (error: any) {
86 | dispatch({
87 | type: 'userLoginFailed',
88 | payload: error.response.data.message,
89 | });
90 | }
91 | };
92 |
93 | // log out user
94 | export const logoutUser = () => async (dispatch: Dispatch) => {
95 | try {
96 | dispatch({
97 | type: 'userLogoutRequest',
98 | });
99 |
100 | await AsyncStorage.setItem('token', '');
101 |
102 | dispatch({
103 | type: 'userLogoutSuccess',
104 | payload: {},
105 | });
106 | } catch (error) {
107 | dispatch({
108 | type: 'userLogoutFailed',
109 | });
110 | }
111 | };
112 |
113 | // get all users
114 | export const getAllUsers = () => async (dispatch: Dispatch) => {
115 | try {
116 | dispatch({
117 | type: 'getUsersRequest',
118 | });
119 |
120 | const token = await AsyncStorage.getItem('token');
121 |
122 | const {data} = await axios.get(`${URI}/users`, {
123 | headers: {Authorization: `Bearer ${token}`},
124 | });
125 |
126 | dispatch({
127 | type: 'getUsersSuccess',
128 | payload: data.users,
129 | });
130 | } catch (error: any) {
131 | dispatch({
132 | type: 'getUsersFailed',
133 | payload: error.response.data.message,
134 | });
135 | }
136 | };
137 |
138 | interface FollowUnfollowParams {
139 | userId: string;
140 | followUserId: string;
141 | users: any;
142 | }
143 |
144 | // follow user
145 | export const followUserAction =
146 | ({userId, users, followUserId}: FollowUnfollowParams) =>
147 | async (dispatch: Dispatch) => {
148 | try {
149 | const token = await AsyncStorage.getItem('token');
150 | const updatedUsers = users.map((userObj: any) =>
151 | userObj._id === followUserId
152 | ? {
153 | ...userObj,
154 | followers: [...userObj.followers, {userId}],
155 | }
156 | : userObj,
157 | );
158 |
159 | // update our users state
160 | dispatch({
161 | type: 'getUsersSuccess',
162 | payload: updatedUsers,
163 | });
164 |
165 | await axios.put(
166 | `${URI}/add-user`,
167 | {followUserId},
168 | {
169 | headers: {
170 | Authorization: `Bearer ${token}`,
171 | },
172 | },
173 | );
174 | } catch (error) {
175 | console.log('Error following user:', error);
176 | }
177 | };
178 |
179 | // unfollow user
180 | export const unfollowUserAction =
181 | ({userId, users, followUserId}: FollowUnfollowParams) =>
182 | async (dispatch: Dispatch) => {
183 | try {
184 | const token = await AsyncStorage.getItem('token');
185 | const updatedUsers = users.map((userObj: any) =>
186 | userObj._id === followUserId
187 | ? {
188 | ...userObj,
189 | followers: userObj.followers.filter(
190 | (follower: any) => follower.userId !== userId,
191 | ),
192 | }
193 | : userObj,
194 | );
195 |
196 | // update our users state
197 | dispatch({
198 | type: 'getUsersSuccess',
199 | payload: updatedUsers,
200 | });
201 |
202 | await axios.put(
203 | `${URI}/add-user`,
204 | {followUserId},
205 | {
206 | headers: {
207 | Authorization: `Bearer ${token}`,
208 | },
209 | },
210 | );
211 | } catch (error) {
212 | console.log('Error following user:', error);
213 | }
214 | };
215 |
--------------------------------------------------------------------------------
/client/redux/reducers/notificationReducer.ts:
--------------------------------------------------------------------------------
1 | import {createReducer} from '@reduxjs/toolkit';
2 |
3 | const initialState = {
4 | isLoading: true,
5 | error: null,
6 | notifications: [],
7 | };
8 |
9 | export const notificationReducer = createReducer(initialState, {
10 | getNotificationRequest: state => {
11 | state.isLoading = true;
12 | },
13 | getNotificationSuccess: (state, action) => {
14 | state.isLoading = false;
15 | state.notifications = action.payload;
16 | },
17 | getNotificationFailed: (state, action) => {
18 | state.isLoading = false;
19 | state.error = action.payload;
20 | },
21 | clearErrors: state => {
22 | state.error = null;
23 | },
24 | });
25 |
--------------------------------------------------------------------------------
/client/redux/reducers/postReducer.ts:
--------------------------------------------------------------------------------
1 | import {createReducer} from '@reduxjs/toolkit';
2 |
3 | const intialState = {
4 | posts:[],
5 | post:{},
6 | error: null,
7 | isSuccess:false,
8 | isLoading: true,
9 | };
10 |
11 | export const postReducer = createReducer(intialState, {
12 | postCreateRequest: state => {
13 | state.isLoading = true;
14 | },
15 | postCreateSuccess: (state, action) => {
16 | state.isLoading = false;
17 | state.post = action.payload;
18 | state.isSuccess = true;
19 | },
20 | postCreateFailed: (state, action) => {
21 | state.isLoading = false;
22 | state.error = action.payload;
23 | },
24 | getAllPostsRequest: state => {
25 | state.isLoading = true;
26 | },
27 | getAllPostsSuccess: (state,action) => {
28 | state.isLoading = false;
29 | state.posts = action.payload;
30 | },
31 | getAllPostsFailed: (state,action) => {
32 | state.isLoading = false;
33 | state.error = action.payload;
34 | },
35 | clearErrors: state => {
36 | state.error = null;
37 | },
38 | });
39 |
--------------------------------------------------------------------------------
/client/redux/reducers/userReducer.ts:
--------------------------------------------------------------------------------
1 | import {createReducer} from '@reduxjs/toolkit';
2 |
3 | const intialState = {
4 | isAuthenticated: false,
5 | loading: false,
6 | isLoading: false,
7 | user: {},
8 | users: [],
9 | token:"",
10 | error: null,
11 | };
12 |
13 | export const userReducer = createReducer(intialState, {
14 | userRegisterRequest: state => {
15 | state.loading = true;
16 | state.isAuthenticated = false;
17 | },
18 | userRegisterSuccess: (state, action) => {
19 | state.loading = false;
20 | state.isAuthenticated = true;
21 | state.user = action.payload;
22 | },
23 | userRegisterFailed: (state, action) => {
24 | state.loading = false;
25 | state.isAuthenticated = false;
26 | state.error = action.payload;
27 | },
28 | userLoadRequest: state => {
29 | state.loading = true;
30 | state.isAuthenticated = false;
31 | },
32 | userLoadSuccess: (state, action) => {
33 | state.loading = false;
34 | state.isAuthenticated = true;
35 | state.user = action.payload.user;
36 | state.token = action.payload.token;
37 | },
38 | userLoadFailed: (state, action) => {
39 | state.loading = false;
40 | state.isAuthenticated = false;
41 | },
42 | userLoginRequest: state => {
43 | state.isAuthenticated = false;
44 | state.loading = true;
45 | },
46 | userLoginSuccess: (state, action) => {
47 | state.isAuthenticated = true;
48 | state.loading = false;
49 | state.user = action.payload;
50 | },
51 | userLoginFailed: (state, action) => {
52 | state.isAuthenticated = false;
53 | state.loading = false;
54 | state.error = action.payload;
55 | state.user = {};
56 | },
57 | userLogoutRequest: state => {
58 | state.loading = true;
59 | },
60 | userLogoutSuccess: state => {
61 | state.loading = false;
62 | state.isAuthenticated = false;
63 | state.user = {};
64 | },
65 | userLogoutFailed: state => {
66 | state.loading = false;
67 | },
68 | getUsersRequest: state => {
69 | state.isLoading = true;
70 | },
71 | getUsersSuccess: (state,action) => {
72 | state.isLoading = false;
73 | state.users = action.payload;
74 | },
75 | getUsersFailed: (state,action) => {
76 | state.isLoading = false;
77 | state.users = action.payload;
78 | },
79 | clearErrors: state => {
80 | state.error = null;
81 | state.isAuthenticated = false;
82 | },
83 | });
84 |
--------------------------------------------------------------------------------
/client/src/assets/animation_lkbqh8co.json:
--------------------------------------------------------------------------------
1 | {"v":"5.12.2","fr":60,"ip":0,"op":181,"w":1200,"h":1200,"nm":"Threads","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"Thread Logo","parent":2,"sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":90,"ix":10},"p":{"a":0,"k":[105.664,-125.889,0],"ix":2,"l":2},"a":{"a":0,"k":[-1907.077,-68.297,0],"ix":1,"l":2},"s":{"a":0,"k":[182,182,100],"ix":6,"l":2}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[40.101,9.532],[19.393,-20.05],[-36.084,-29.877],[-19.556,-0.089],[-6.179,17.641],[22.351,5.588],[3.584,-12.924],[-22.351,15.283],[41.086,2.465],[10.234,-7.519]],"o":[[0,0],[-26.841,-6.381],[-27.976,28.925],[11.804,9.773],[32.569,0.147],[7.601,-21.703],[-44.551,-11.138],[-5.423,19.557],[19.949,-13.642],[-10.584,-0.635],[0,0]],"v":[[-1834.967,-99.973],[-1883.613,-149.934],[-1958.225,-131.856],[-1952.052,2.215],[-1903.992,16.054],[-1845.306,-17.87],[-1871.123,-69.734],[-1932.752,-54.45],[-1886.9,-32.756],[-1903.006,-109.341],[-1934.747,-97.858]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[1,1,1,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":15,"ix":5},"lc":1,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tr","p":{"a":0,"k":[0,0],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Shape 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false},{"ty":"tm","s":{"a":0,"k":100,"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.295],"y":[1]},"o":{"x":[0.707],"y":[0]},"t":36,"s":[100]},{"t":126,"s":[0]}],"ix":2},"o":{"a":0,"k":0,"ix":3},"m":1,"ix":2,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false}],"ip":0,"op":600,"st":0,"ct":1,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"Square","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":1,"k":[{"i":{"x":[0.833],"y":[0.833]},"o":{"x":[0.899],"y":[-0.003]},"t":40,"s":[-180]},{"t":74,"s":[-90]}],"ix":10,"x":"var $bm_rt;\nvar amp, freq, decay, n, n, t, t, v;\namp = 5;\nfreq = 2;\ndecay = 4;\n$bm_rt = n = 0;\nif (numKeys > 0) {\n $bm_rt = n = nearestKey(time).index;\n if (key(n).time > time) {\n n--;\n }\n}\nif (n == 0) {\n $bm_rt = t = 0;\n} else {\n $bm_rt = t = $bm_sub(time, key(n).time);\n}\nif (n > 0 && t < 1) {\n v = velocityAtTime($bm_sub(key(n).time, $bm_div(thisComp.frameDuration, 10)));\n $bm_rt = $bm_sum(value, $bm_div($bm_mul($bm_mul(v, $bm_div(amp, 100)), Math.sin($bm_mul($bm_mul($bm_mul(freq, t), 2), Math.PI))), Math.exp($bm_mul(decay, t))));\n} else {\n $bm_rt = value;\n}"},"p":{"a":0,"k":[600,600,0],"ix":2,"l":2},"a":{"a":0,"k":[105.664,-125.889,0],"ix":1,"l":2},"s":{"a":0,"k":[100,100,100],"ix":6,"l":2}},"ao":0,"shapes":[{"ty":"gr","it":[{"ty":"rc","d":1,"s":{"a":1,"k":[{"i":{"x":[0.403,0.403],"y":[1.546,1.546]},"o":{"x":[0.871,0.871],"y":[-0.248,-0.248]},"t":40,"s":[50,50]},{"t":74,"s":[550,550]}],"ix":2},"p":{"a":0,"k":[0,0],"ix":3},"r":{"a":0,"k":150,"ix":4},"nm":"Rectangle Path 1","mn":"ADBE Vector Shape - Rect","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0,0,1],"ix":4},"o":{"a":0,"k":100,"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[105.664,-125.889],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Rectangle 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":38,"op":468,"st":0,"ct":1,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Line","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[580,710,0],"ix":2,"l":2},"a":{"a":0,"k":[-1637.989,2473.637,0],"ix":1,"l":2},"s":{"a":0,"k":[100,100,100],"ix":6,"l":2}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[252.705,0],[86.103,92.815],[15.943,83.965],[-64.59,73.477],[-68.386,0],[0,-132.073]],"o":[[0,252.705],[-126.608,0],[-58.109,-62.639],[-17.481,-92.065],[45.147,-51.359],[132.073,0],[0,0]],"v":[[-1180.147,2379.535],[-1637.71,2837.098],[-1973.231,2690.649],[-2087.23,2465.4],[-2034.813,2191.501],[-1855.129,2110.176],[-1615.991,2349.315]],"c":false},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"st","c":{"a":0,"k":[0,0,0,1],"ix":3},"o":{"a":0,"k":100,"ix":4},"w":{"a":0,"k":50,"ix":5},"lc":2,"lj":1,"ml":4,"bm":0,"nm":"Stroke 1","mn":"ADBE Vector Graphic - Stroke","hd":false},{"ty":"tm","s":{"a":1,"k":[{"i":{"x":[0.534],"y":[1.008]},"o":{"x":[0.739],"y":[0.584]},"t":10,"s":[0]},{"t":40,"s":[100]}],"ix":1},"e":{"a":1,"k":[{"i":{"x":[0.534],"y":[1.011]},"o":{"x":[0.581],"y":[0.604]},"t":0,"s":[0]},{"t":40,"s":[100]}],"ix":2},"o":{"a":0,"k":0,"ix":3},"m":1,"ix":3,"nm":"Trim Paths 1","mn":"ADBE Vector Filter - Trim","hd":false},{"ty":"tr","p":{"a":0,"k":[-2,14],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":3,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":600,"st":0,"ct":1,"bm":0}],"markers":[],"props":{}}
--------------------------------------------------------------------------------
/client/src/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/client/src/assets/logo.png
--------------------------------------------------------------------------------
/client/src/common/Loader.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {Center, HStack, NativeBaseProvider, Spinner} from 'native-base';
3 |
4 | type Props = {};
5 |
6 | const Loader = (props: Props) => {
7 | return (
8 |
9 |
10 |
11 | );
12 | };
13 |
14 | export default () => {
15 | return (
16 |
17 |
18 |
19 |
20 |
21 | );
22 | };
23 |
--------------------------------------------------------------------------------
/client/src/common/TimeGenerator.tsx:
--------------------------------------------------------------------------------
1 | import moment from 'moment';
2 |
3 | const getTimeDuration = (time: Date): string => {
4 | const createdAt = moment(time);
5 | const now = moment();
6 | const duration = moment.duration(now.diff(createdAt));
7 |
8 | if (duration.asSeconds() < 60) {
9 | return `${Math.floor(duration.asSeconds())}s`;
10 | } else if (duration.asMinutes() < 60) {
11 | return `${Math.floor(duration.asMinutes())}m`;
12 | } else if (duration.asHours() < 24) {
13 | return `${Math.floor(duration.asHours())}h`;
14 | } else if (duration.asDays() < 30) {
15 | return `${Math.floor(duration.asDays())}d`;
16 | } else if (duration.asMonths() < 12) {
17 | return `${Math.floor(duration.asMonths())}mo`;
18 | } else {
19 | return `${Math.floor(duration.asYears())}y`;
20 | }
21 | };
22 |
23 | export default getTimeDuration;
24 |
--------------------------------------------------------------------------------
/client/src/components/EditProfile.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | TouchableOpacity,
6 | TouchableWithoutFeedback,
7 | } from 'react-native';
8 | import React, {useState} from 'react';
9 | import {Image} from 'react-native';
10 | import {useDispatch, useSelector} from 'react-redux';
11 | import {TextInput} from 'react-native';
12 | import ImagePicker, {ImageOrVideo} from 'react-native-image-crop-picker';
13 | import axios from 'axios';
14 | import {URI} from '../../redux/URI';
15 | import {loadUser} from '../../redux/actions/userAction';
16 |
17 | type Props = {
18 | navigation: any;
19 | };
20 |
21 | const EditProfile = ({navigation}: Props) => {
22 | const {user, token} = useSelector((state: any) => state.user);
23 | const [avatar, setAvatar] = useState(user?.avatar?.url);
24 | const dispatch = useDispatch();
25 | const [userData, setUserData] = useState({
26 | name: user.name,
27 | userName: user?.userName,
28 | bio: user?.bio,
29 | });
30 |
31 | const handleSubmitHandler = async () => {
32 | if (userData.name.length !== 0 && userData.userName.length !== 0) {
33 | await axios.put(`${URI}/update-profile`,{
34 | name: userData.name,
35 | userName: userData.userName,
36 | bio: userData.bio,
37 | },{
38 | headers: {
39 | Authorization: `Bearer ${token}`,
40 | },
41 | }).then((res:any) => {
42 | loadUser()(dispatch);
43 | })
44 | }
45 | };
46 |
47 | const ImageUpload = () => {
48 | ImagePicker.openPicker({
49 | width: 300,
50 | height: 300,
51 | cropping: true,
52 | compressImageQuality: 0.8,
53 | includeBase64: true,
54 | }).then((image: ImageOrVideo | null) => {
55 | if (image) {
56 | // setImage('data:image/jpeg;base64,' + image.data);
57 | axios
58 | .put(
59 | `${URI}/update-avatar`,
60 | {
61 | avatar: 'data:image/jpeg;base64,' + image?.data,
62 | },
63 | {
64 | headers: {
65 | Authorization: `Bearer ${token}`,
66 | },
67 | },
68 | )
69 | .then((res: any) => {
70 | loadUser()(dispatch);
71 | });
72 | }
73 | });
74 | };
75 |
76 | return (
77 |
78 |
79 |
80 | navigation.goBack()}>
81 |
88 |
89 |
90 | Edit Profile
91 |
92 |
93 |
94 | Done
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 | Name
103 | setUserData({...userData, name: e})}
106 | placeholder="Enter your name..."
107 | placeholderTextColor={'#000'}
108 | className="text-[16px] text-[#000000b0]"
109 | />
110 | setUserData({...userData, userName: e})}
113 | placeholder="Enter your userName..."
114 | placeholderTextColor={'#000'}
115 | className="text-[16px] mb-2 text-[#000000b0]"
116 | />
117 |
118 |
119 |
125 |
126 |
127 |
128 |
129 | Bio
130 | setUserData({...userData, bio: e})}
133 | placeholder="Enter your bio..."
134 | placeholderTextColor={'#000'}
135 | className="text-[16px] text-[#000000b0]"
136 | multiline={true}
137 | numberOfLines={4}
138 | />
139 |
140 |
141 |
142 |
143 | );
144 | };
145 |
146 | export default EditProfile;
147 |
--------------------------------------------------------------------------------
/client/src/components/FollowerCard.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | TouchableOpacity,
6 | Image,
7 | FlatList,
8 | } from 'react-native';
9 | import React, {useEffect, useState} from 'react';
10 | import {useDispatch, useSelector} from 'react-redux';
11 | import {
12 | followUserAction,
13 | loadUser,
14 | unfollowUserAction,
15 | } from '../../redux/actions/userAction';
16 |
17 | type Props = {
18 | route: any;
19 | navigation: any;
20 | };
21 |
22 | const FollowerCard = ({navigation, route}: Props) => {
23 | const followers = route.params.followers;
24 | const item = route.params.item;
25 | const following = route.params.following;
26 | const [data, setData] = useState(followers);
27 | const [active, setActive] = useState(0);
28 | const {user, users} = useSelector((state: any) => state.user);
29 | const dispatch = useDispatch();
30 |
31 | useEffect(() => {
32 | if (users) {
33 | if (followers) {
34 | const updatedUsers = [...users, user];
35 | const fullUsers = updatedUsers.filter((user: any) =>
36 | followers.some((item: any) => item.userId === user._id),
37 | );
38 | setData(fullUsers);
39 | }
40 | if (active === 1) {
41 | if (following) {
42 | const updatedUsers = [...users, user];
43 | const fullUsers = updatedUsers.filter((user: any) =>
44 | following.some((item: any) => item.userId === user._id),
45 | );
46 | setData(fullUsers);
47 | }
48 | }
49 | }
50 | }, [followers, following, active, users]);
51 |
52 | return (
53 |
54 |
55 |
56 | navigation.goBack()}>
57 |
64 |
65 |
66 | {item?.name}
67 |
68 |
69 |
70 | setActive(0)}>
71 |
74 | Followers
75 |
76 |
77 | setActive(1)}>
78 |
81 | Following
82 |
83 |
84 |
85 | setActive(2)}>
86 |
89 | Pending
90 |
91 |
92 |
93 |
94 | {active === 0 ? (
95 |
96 | ) : active === 1 ? (
97 |
98 | ) : (
99 |
100 | )}
101 |
102 |
103 | {active === 0 && (
104 |
105 | {followers?.length} followers
106 |
107 | )}
108 |
109 | {active === 1 && (
110 |
111 | {following?.length} following
112 |
113 | )}
114 |
115 | {active !== 2 && (
116 | {
119 | const handleFollowUnfollow = async (e: any) => {
120 | try {
121 | if (e.followers.find((i: any) => i.userId === user._id)) {
122 | await unfollowUserAction({
123 | userId: user._id,
124 | users,
125 | followUserId: e._id,
126 | })(dispatch);
127 | } else {
128 | await followUserAction({
129 | userId: user._id,
130 | users,
131 | followUserId: e._id,
132 | })(dispatch);
133 | }
134 | } catch (error) {
135 | console.log(error, 'error');
136 | }
137 | loadUser()(dispatch);
138 | };
139 |
140 | return (
141 |
144 | navigation.navigate('UserProfile', {
145 | item,
146 | })
147 | }>
148 |
149 |
155 |
156 |
157 |
158 | {item?.name}
159 |
160 | {item.role === 'Admin' && (
161 |
169 | )}
170 |
171 |
172 | {item?.userName}
173 |
174 |
175 |
176 | {user._id !== item._id && (
177 | handleFollowUnfollow(item)}>
180 |
181 | {item?.followers?.find((i: any) => i.userId === user._id)
182 | ? 'Following'
183 | : 'Follow'}
184 |
185 |
186 | )}
187 |
188 | );
189 | }}
190 | />
191 | )}
192 |
193 | {active === 2 && (
194 | No Pending
195 | )}
196 |
197 | );
198 | };
199 |
200 | export default FollowerCard;
201 |
--------------------------------------------------------------------------------
/client/src/components/PostLikeCard.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | TouchableOpacity,
6 | Image,
7 | FlatList,
8 | } from 'react-native';
9 | import React from 'react';
10 | import {useDispatch, useSelector} from 'react-redux';
11 | import {
12 | followUserAction,
13 | unfollowUserAction,
14 | } from '../../redux/actions/userAction';
15 |
16 | type Props = {
17 | route: any;
18 | navigation: any;
19 | };
20 |
21 | const PostLikeCard = ({navigation, route}: Props) => {
22 | const data = route.params.item;
23 |
24 | const {user, users} = useSelector((state: any) => state.user);
25 | const dispatch = useDispatch();
26 |
27 | return (
28 |
29 |
30 |
31 | navigation.goBack()}>
32 |
39 |
40 | Likes
41 |
42 | {
45 | const handleFollowUnfollow = async (e: any) => {
46 | try {
47 | if (e.followers.find((i: any) => i.userId === user._id)) {
48 | await unfollowUserAction({
49 | userId: user._id,
50 | users,
51 | followUserId: e._id,
52 | })(dispatch);
53 | } else {
54 | await followUserAction({
55 | userId: user._id,
56 | users,
57 | followUserId: e._id,
58 | })(dispatch);
59 | }
60 | } catch (error) {
61 | console.log(error, 'error');
62 | }
63 | };
64 | return (
65 |
68 | item.userId === user._id
69 | ? navigation.navigate('Profile')
70 | : navigation.navigate('UserProfile', {
71 | item: users.find((i: any) =>
72 | i._id === item.userId ? i : null,
73 | ),
74 | })
75 | }>
76 |
77 |
83 |
84 |
85 |
86 | {item?.name ? item.name : user.name}
87 |
88 | {item.userId === '64ba059336147d4b13bc1a6e' && (
89 |
97 | )}
98 |
99 |
100 |
101 | {item?.userName ? item.userName : user.userName}
102 |
103 |
104 |
105 | {user._id !== item.userId && (
106 |
109 | handleFollowUnfollow(
110 | users.find((i: any) =>
111 | i._id === item.userId ? i : null,
112 | ),
113 | )
114 | }>
115 |
116 | {users.find(
117 | (i: any) =>
118 | item.userId === i._id &&
119 | i.followers.find((i: any) => i.userId === user._id),
120 | )
121 | ? 'Following'
122 | : 'Follow'}
123 |
124 |
125 | )}
126 |
127 | );
128 | }}
129 | />
130 |
131 |
132 | );
133 | };
134 |
135 | export default PostLikeCard;
136 |
--------------------------------------------------------------------------------
/client/src/screens/CreateRepliesScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | Image,
6 | TextInput,
7 | ScrollView,
8 | } from 'react-native';
9 | import React, {useState} from 'react';
10 | import {TouchableOpacity} from 'react-native';
11 | import {useDispatch, useSelector} from 'react-redux';
12 | import ImagePicker, {ImageOrVideo} from 'react-native-image-crop-picker';
13 | import getTimeDuration from '../common/TimeGenerator';
14 | import axios from 'axios';
15 | import {URI} from '../../redux/URI';
16 | import { getAllPosts } from '../../redux/actions/postAction';
17 |
18 | type Props = {
19 | item: any;
20 | navigation: any;
21 | route: any;
22 | postId: string;
23 | };
24 |
25 | const CreateRepliesScreen = ({navigation, route}: Props) => {
26 | const post = route.params.item;
27 | const postId = route.params.postId;
28 | const {user, token} = useSelector((state: any) => state.user);
29 | const [image, setImage] = useState('');
30 | const [title, setTitle] = useState('');
31 | const dispatch = useDispatch();
32 |
33 | const ImageUpload = async () => {
34 | ImagePicker.openPicker({
35 | width: 300,
36 | height: 300,
37 | cropping: true,
38 | compressImageQuality: 0.8,
39 | includeBase64: true,
40 | }).then((image: ImageOrVideo | null) => {
41 | if (image) {
42 | setImage('data:image/jpeg;base64,' + image.data);
43 | }
44 | });
45 | };
46 |
47 | const time = post.createdAt;
48 | const formattedDuration = getTimeDuration(time);
49 |
50 | const createReplies = async () => {
51 | if (!postId) {
52 | await axios
53 | .put(
54 | `${URI}/add-replies`,
55 | {
56 | postId: post._id,
57 | title,
58 | image,
59 | },
60 | {
61 | headers: {
62 | Authorization: `Bearer ${token}`,
63 | },
64 | },
65 | )
66 | .then((res: any) => {
67 | getAllPosts()(dispatch);
68 | navigation.navigate('PostDetails', {
69 | data: res.data.post,
70 | navigation: navigation,
71 | });
72 | setTitle('');
73 | setImage('');
74 | });
75 | } else {
76 | console.log(postId,post._id);
77 | await axios
78 | .put(
79 | `${URI}/add-reply`,
80 | {
81 | postId,
82 | replyId: post._id,
83 | title,
84 | image,
85 | },
86 | {
87 | headers: {
88 | Authorization: `Bearer ${token}`,
89 | },
90 | },
91 | )
92 | .then((res: any) => {
93 | navigation.navigate('PostDetails', {
94 | data: res.data.post,
95 | navigation: navigation,
96 | });
97 | setTitle('');
98 | setImage('');
99 | });
100 | }
101 | };
102 | return (
103 |
104 |
105 | navigation.goBack()}>
106 |
113 |
114 | Reply
115 |
116 |
117 |
118 |
119 |
120 |
126 |
127 |
128 | {post.user.name}
129 |
130 |
131 | {post.title}
132 |
133 |
134 |
135 |
136 | {formattedDuration}
137 |
138 |
139 | ...
140 |
141 |
142 |
143 |
144 |
145 | {post.image && (
146 |
156 | )}
157 |
158 | {post.image ? (
159 |
160 | ) : (
161 |
162 | )}
163 |
164 |
165 |
166 |
172 |
173 |
174 | {user.name}
175 |
176 |
183 |
184 |
193 |
194 |
195 |
196 |
197 | {image && (
198 |
209 | )}
210 |
211 |
212 |
213 |
214 |
215 |
216 | Anyone can reply
217 |
218 | Post
219 |
220 |
221 |
222 |
223 |
224 |
225 | );
226 | };
227 |
228 | export default CreateRepliesScreen;
229 |
--------------------------------------------------------------------------------
/client/src/screens/HomeScreen.tsx:
--------------------------------------------------------------------------------
1 | import {FlatList, Animated, Easing, RefreshControl} from 'react-native';
2 | import React, {useEffect, useRef, useState} from 'react';
3 | import {SafeAreaView} from 'react-native';
4 | import {useDispatch, useSelector} from 'react-redux';
5 | import {getAllPosts} from '../../redux/actions/postAction';
6 | import PostCard from '../components/PostCard';
7 | import Loader from '../common/Loader';
8 | import Lottie from 'lottie-react-native';
9 | import { getAllUsers } from '../../redux/actions/userAction';
10 | import { Platform } from 'react-native';
11 | const loader = require('../assets/animation_lkbqh8co.json');
12 |
13 | type Props = {
14 | navigation: any;
15 | };
16 |
17 | const HomeScreen = (props: Props) => {
18 | const {posts, isLoading} = useSelector((state: any) => state.post);
19 | const dispatch = useDispatch();
20 | const [offsetY, setOffsetY] = useState(0);
21 | const [isRefreshing, setIsRefreshing] = useState(false);
22 | const [refreshing, setRefreshing] = useState(false);
23 | const [extraPaddingTop] = useState(new Animated.Value(0));
24 | const refreshingHeight = 100;
25 | const lottieViewRef = useRef(null);
26 |
27 | let progress = 0;
28 | if (offsetY < 0 && !isRefreshing) {
29 | const maxOffsetY = -refreshingHeight;
30 | progress = Math.min(offsetY / maxOffsetY, 1);
31 | }
32 |
33 | function onScroll(event: any) {
34 | const {nativeEvent} = event;
35 | const {contentOffset} = nativeEvent;
36 | const {y} = contentOffset;
37 | setOffsetY(y);
38 | }
39 |
40 | function onRelease() {
41 | if (offsetY <= -refreshingHeight && !isRefreshing) {
42 | setIsRefreshing(true);
43 | setTimeout(() => {
44 | getAllPosts()(dispatch);
45 | setIsRefreshing(false);
46 | }, 3000);
47 | }
48 | }
49 |
50 | function onScrollEndDrag(event: any) {
51 | const { nativeEvent } = event;
52 | const { contentOffset } = nativeEvent;
53 | const { y } = contentOffset;
54 | setOffsetY(y);
55 |
56 | if (y <= -refreshingHeight && !isRefreshing) {
57 | setIsRefreshing(true);
58 | setTimeout(() => {
59 | getAllPosts()(dispatch);
60 | setIsRefreshing(false);
61 | }, 3000);
62 | }
63 | }
64 |
65 | useEffect(() => {
66 | getAllPosts()(dispatch);
67 | getAllUsers()(dispatch);
68 | }, [dispatch]);
69 |
70 | useEffect(() => {
71 | if (isRefreshing) {
72 | Animated.timing(extraPaddingTop, {
73 | toValue: refreshingHeight,
74 | duration: 0,
75 | useNativeDriver: false,
76 | }).start();
77 | lottieViewRef.current?.play();
78 | } else {
79 | Animated.timing(extraPaddingTop, {
80 | toValue: 0,
81 | duration: 400,
82 | easing: Easing.elastic(1.3),
83 | useNativeDriver: false,
84 | }).start();
85 | }
86 | }, [isRefreshing]);
87 |
88 | return (
89 | <>
90 | {isLoading ? (
91 |
92 | ) : (
93 |
94 |
108 | {/* custom loader not working in android that's why I used here built in loader for android and custom loader for android but both working perfectly */}
109 | {
110 | Platform.OS === 'ios' ? (
111 | (
115 |
116 | )}
117 | onScroll={onScroll}
118 | onScrollEndDrag={onScrollEndDrag}
119 | onResponderRelease={onRelease}
120 | ListHeaderComponent={
121 |
126 | }
127 | />
128 | ) : (
129 | (
133 |
134 | )}
135 | onScroll={onScroll}
136 | onScrollEndDrag={onScrollEndDrag}
137 | refreshControl={
138 | {
141 | setRefreshing(true);
142 | getAllPosts()(dispatch);
143 | getAllUsers()(dispatch).then(() => {
144 | setRefreshing(false);
145 | });
146 | }}
147 | progressViewOffset={refreshingHeight}
148 | />
149 | }
150 | onResponderRelease={onRelease}
151 | ListHeaderComponent={
152 |
157 | }
158 | />
159 | )
160 | }
161 |
162 | )}
163 | >
164 | );
165 | };
166 |
167 | export default HomeScreen;
168 |
--------------------------------------------------------------------------------
/client/src/screens/LoginScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | TextInput,
5 | TouchableOpacity,
6 | Alert,
7 | ToastAndroid,
8 | Platform,
9 | } from 'react-native';
10 | import React, {useEffect, useState} from 'react';
11 | import {loadUser, loginUser} from '../../redux/actions/userAction';
12 | import {useDispatch, useSelector} from 'react-redux';
13 |
14 | type Props = {
15 | navigation: any;
16 | };
17 |
18 | const LoginScreen = ({navigation}: Props) => {
19 | const {error, isAuthenticated} = useSelector((state: any) => state.user);
20 | const [email, setEmail] = useState('');
21 | const [password, setPassword] = useState('');
22 | const dispatch = useDispatch();
23 | const submitHandler = (e: any) => {
24 | loginUser(email, password)(dispatch);
25 | };
26 |
27 | useEffect(() => {
28 | if (error) {
29 | if (Platform.OS === 'android') {
30 | ToastAndroid.show(
31 | 'Email and password not matching!',
32 | ToastAndroid.LONG,
33 | );
34 | } else {
35 | Alert.alert('Email and password not matching!');
36 | }
37 | }
38 | if (isAuthenticated) {
39 | loadUser()(dispatch);
40 | if (Platform.OS === 'android') {
41 | ToastAndroid.show('Login successful!', ToastAndroid.LONG);
42 | } else{
43 | Alert.alert('Login successful!');
44 | }
45 | }
46 | }, [isAuthenticated, error]);
47 |
48 | return (
49 |
50 |
51 |
52 | Login
53 |
54 | setEmail(text)}
59 | className="w-full h-[35px] border border-[#00000072] px-2 my-2 text-black"
60 | />
61 | setPassword(text)}
67 | secureTextEntry={true}
68 | />
69 |
70 |
73 | Login
74 |
75 |
76 | navigation.navigate('Signup')}>
79 | Don't have any account? Sign up
80 |
81 |
82 |
83 | );
84 | };
85 |
86 | export default LoginScreen;
87 |
--------------------------------------------------------------------------------
/client/src/screens/NotificationScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | TouchableOpacity,
6 | FlatList,
7 | Image,
8 | RefreshControl,
9 | } from 'react-native';
10 | import React, {useEffect, useState} from 'react';
11 | import {getNotifications} from '../../redux/actions/notificationAction';
12 | import {useDispatch, useSelector} from 'react-redux';
13 | import getTimeDuration from '../common/TimeGenerator';
14 | import axios from 'axios';
15 | import {URI} from '../../redux/URI';
16 | import Loader from '../common/Loader';
17 |
18 | type Props = {
19 | navigation: any;
20 | };
21 |
22 | const NotificationScreen = ({navigation}: Props) => {
23 | const dispatch = useDispatch();
24 | const {notifications, isLoading} = useSelector(
25 | (state: any) => state.notification,
26 | );
27 | const [refreshing, setRefreshing] = useState(false);
28 | const {posts} = useSelector((state:any) => state.post);
29 | const {token, users} = useSelector((state: any) => state.user);
30 | const [active, setActive] = useState(0);
31 | const refreshingHeight = 100;
32 |
33 | const labels = ['All', 'Replies', 'Mentions'];
34 |
35 | const handleTabPress = (index: number) => {
36 | setActive(index);
37 | };
38 |
39 | useEffect(() => {
40 | getNotifications()(dispatch);
41 | }, []);
42 |
43 |
44 | return (
45 | <>
46 | {isLoading ? (
47 |
48 | ) : (
49 | <>
50 |
51 |
52 | Activity
53 |
54 |
55 | {labels.map((label, index) => (
56 | handleTabPress(index)}>
65 |
69 | {label}
70 |
71 |
72 | ))}
73 |
74 |
75 | {/* All activites */}
76 | {active === 0 && notifications.length === 0 && (
77 |
78 | You have no activity yet!
79 |
80 | )}
81 |
82 | {/* All Replies */}
83 | {active === 1 && (
84 |
85 | You have no replies yet!
86 |
87 | )}
88 |
89 | {/* All Replies */}
90 | {active === 2 && (
91 |
92 | You have no mentions yet!
93 |
94 | )}
95 |
96 | {active === 0 && (
97 | {
103 | setRefreshing(true);
104 | getNotifications()(dispatch).then(() => {
105 | setRefreshing(false);
106 | });
107 | }}
108 | progressViewOffset={refreshingHeight}
109 | />
110 | }
111 | showsVerticalScrollIndicator={false}
112 | renderItem={({item}) => {
113 | const time = item.createdAt;
114 | const formattedDuration = getTimeDuration(time);
115 |
116 |
117 | const handleNavigation = async (e: any) => {
118 | const id = item.creator._id;
119 |
120 | await axios
121 | .get(`${URI}/get-user/${id}`, {
122 | headers: {Authorization: `Bearer ${token}`},
123 | })
124 | .then(res => {
125 | if(item.type === "Follow"){
126 | navigation.navigate('UserProfile', {
127 | item: res.data.user,
128 | });
129 | } else{
130 | navigation.navigate('PostDetails', {
131 | data: posts.find((i:any) => i._id === item.postId)
132 | });
133 | }
134 | });
135 | };
136 |
137 | return (
138 | handleNavigation(item)}>
139 |
140 |
141 | user._id === item.creator._id,
145 | )?.avatar.url,
146 | }}
147 | width={40}
148 | height={40}
149 | borderRadius={100}
150 | />
151 | {item.type === 'Like' && (
152 |
153 |
161 |
162 | )}
163 |
164 | {item.type === 'Follow' && (
165 |
166 |
174 |
175 | )}
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 | {item.creator.name}
185 |
186 |
187 | {formattedDuration}
188 |
189 |
190 |
191 | {item.title}
192 |
193 |
194 |
195 |
196 |
197 |
198 | );
199 | }}
200 | />
201 | )}
202 |
203 |
204 | >
205 | )}
206 | >
207 | );
208 | };
209 |
210 | export default NotificationScreen;
211 |
--------------------------------------------------------------------------------
/client/src/screens/PostDetailsScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | TouchableOpacity,
6 | Image,
7 | ScrollView,
8 | } from 'react-native';
9 | import React, {useEffect, useState} from 'react';
10 | import PostDetailsCard from '../components/PostDetailsCard';
11 | import {useSelector} from 'react-redux';
12 |
13 | type Props = {
14 | navigation: any;
15 | route: any;
16 | };
17 |
18 | const PostDetailsScreen = ({navigation, route}: Props) => {
19 | let item = route.params.data;
20 | const {posts} = useSelector((state: any) => state.post);
21 | const [data, setdata] = useState(item);
22 |
23 | useEffect(() => {
24 | if (posts) {
25 | const d = posts.find((i: any) => i._id === item._id);
26 | setdata(d);
27 | }
28 | }, [posts]);
29 |
30 | return (
31 |
32 |
33 |
34 |
35 | navigation.goBack()}>
36 |
43 |
44 |
45 |
46 |
51 |
52 | {data?.replies?.map((i: any, index: number) => {
53 | return (
54 |
61 | );
62 | })}
63 |
64 |
65 |
66 |
67 |
68 |
71 | navigation.replace('CreateReplies', {
72 | item: item,
73 | navigation: navigation,
74 | })
75 | }>
76 |
83 |
84 | Reply to {item.user.name}{' '}
85 |
86 |
87 |
88 |
89 |
90 | );
91 | };
92 |
93 | export default PostDetailsScreen;
94 |
--------------------------------------------------------------------------------
/client/src/screens/PostScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | Image,
3 | SafeAreaView,
4 | ScrollView,
5 | Text,
6 | TextInput,
7 | TouchableOpacity,
8 | View,
9 | } from 'react-native';
10 | import React, {useEffect, useState} from 'react';
11 | import {useDispatch, useSelector} from 'react-redux';
12 | import ImagePicker, {ImageOrVideo} from 'react-native-image-crop-picker';
13 | import {createPostAction, getAllPosts} from '../../redux/actions/postAction';
14 |
15 | type Props = {
16 | navigation: any;
17 | };
18 |
19 | const PostScreen = ({navigation}: Props) => {
20 | const {user} = useSelector((state: any) => state.user);
21 | const {isSuccess, isLoading} = useSelector((state: any) => state.post);
22 | const [activeIndex, setActiveIndex] = useState(0);
23 | const [active, setActive] = useState(false);
24 | const dispatch = useDispatch();
25 | const [title, setTitle] = useState('');
26 | const [image, setImage] = useState('');
27 |
28 | useEffect(() => {
29 | if (
30 | replies.length === 1 &&
31 | replies[0].title === '' &&
32 | replies[0].image === ''
33 | ) {
34 | setReplies([]);
35 | }
36 | if (isSuccess) {
37 | navigation.goBack();
38 | getAllPosts()(dispatch);
39 | }
40 | setReplies([]);
41 | setTitle('');
42 | setImage('');
43 | }, [isSuccess]);
44 |
45 | const [replies, setReplies] = useState([
46 | {
47 | title: '',
48 | image: '',
49 | user,
50 | },
51 | ]);
52 |
53 | const handleTitleChange = (index: number, text: string) => {
54 | setReplies(prevPost => {
55 | const updatedPost = [...prevPost];
56 | updatedPost[index] = {...updatedPost[index], title: text};
57 | return updatedPost;
58 | });
59 | };
60 |
61 | const uploadImage = (index: number) => {
62 | ImagePicker.openPicker({
63 | width: 300,
64 | height: 300,
65 | cropping: true,
66 | compressImageQuality: 0.9,
67 | includeBase64: true,
68 | }).then((image: ImageOrVideo | null) => {
69 | if (image) {
70 | setReplies(prevPost => {
71 | const updatedPost = [...prevPost];
72 | updatedPost[index] = {
73 | ...updatedPost[index],
74 | image: 'data:image/jpeg;base64,' + image?.data,
75 | };
76 | return updatedPost;
77 | });
78 | }
79 | });
80 | };
81 |
82 | const addNewThread = () => {
83 | if (
84 | replies[activeIndex].title !== '' ||
85 | replies[activeIndex].image !== ''
86 | ) {
87 | setReplies(prevPost => [...prevPost, {title: '', image: '', user}]);
88 | setActiveIndex(replies.length);
89 | }
90 | };
91 |
92 | const removeThread = (index: number) => {
93 | if (replies.length > 0) {
94 | const updatedPost = [...replies];
95 | updatedPost.splice(index, 1);
96 | setReplies(updatedPost);
97 | setActiveIndex(replies.length - 1);
98 | } else {
99 | setReplies([{title: '', image: '', user}]);
100 | }
101 | };
102 |
103 | const addFreshNewThread = () => {
104 | if (title !== '' || image !== '') {
105 | setActive(true);
106 | setReplies(prevPost => [...prevPost, {title: '', image: '', user}]);
107 | setActiveIndex(replies.length);
108 | }
109 | };
110 |
111 | const postImageUpload = () => {
112 | ImagePicker.openPicker({
113 | width: 300,
114 | height: 300,
115 | cropping: true,
116 | compressImageQuality: 0.8,
117 | includeBase64: true,
118 | }).then((image: ImageOrVideo | null) => {
119 | if (image) {
120 | setImage('data:image/jpeg;base64,' + image.data);
121 | }
122 | });
123 | };
124 |
125 | const createPost = () => {
126 | if (title !== '' || (image !== '' && !isLoading)) {
127 | createPostAction(title, image, user, replies)(dispatch);
128 | }
129 | };
130 |
131 | return (
132 |
133 |
134 | navigation.goBack()}>
135 |
144 |
145 |
146 | New Thread
147 |
148 |
149 |
152 |
153 |
154 | {/* create post */}
155 |
156 |
161 |
162 |
163 |
164 | {user?.name}
165 |
166 |
167 |
176 |
177 |
178 | setTitle(text)}
183 | className="mt-1 text-[#000] text-[16px]"
184 | />
185 |
186 |
196 |
197 |
198 |
199 | {image && (
200 |
201 |
208 |
209 | )}
210 | {replies.length === 0 && (
211 |
212 |
217 |
218 | Add to thread ...
219 |
220 |
221 | )}
222 |
223 | {replies.map((item, index) => (
224 |
225 |
226 |
231 |
232 |
233 |
234 | {user?.name}
235 |
236 | removeThread(index)}>
237 |
246 |
247 |
248 | handleTitleChange(index, text)}
253 | className="mt-2 text-[#000] text-[16px]"
254 | />
255 | uploadImage(index)}>
258 |
267 |
268 |
269 |
270 | {item.image && (
271 |
272 |
279 |
280 | )}
281 | {index === activeIndex && (
282 |
283 |
288 |
289 | Add to thread ...
290 |
291 |
292 | )}
293 |
294 | ))}
295 |
296 |
297 |
298 |
299 | Anyone can reply
300 |
301 | Post
302 |
303 |
304 |
305 | );
306 | };
307 |
308 | export default PostScreen;
309 |
--------------------------------------------------------------------------------
/client/src/screens/ProfileScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | ScrollView,
6 | Image,
7 | TouchableOpacity,
8 | } from 'react-native';
9 | import React, {useEffect, useState} from 'react';
10 | import {useDispatch, useSelector} from 'react-redux';
11 | import {Dimensions} from 'react-native';
12 | import {loadUser, logoutUser} from '../../redux/actions/userAction';
13 | import PostCard from '../components/PostCard';
14 |
15 | type Props = {
16 | navigation: any;
17 | };
18 |
19 | const {width} = Dimensions.get('window');
20 |
21 | const ProfileScreen = ({navigation}: Props) => {
22 | const [active, setActive] = useState(0);
23 | const {user} = useSelector((state: any) => state.user);
24 | const {posts} = useSelector((state: any) => state.post);
25 | const [data, setData] = useState([]);
26 | const [repliesData, setRepliesData] = useState([]);
27 | const dispatch = useDispatch();
28 | const logoutHandler = async () => {
29 | logoutUser()(dispatch);
30 | };
31 |
32 | useEffect(() => {
33 | if (posts && user) {
34 | const myPosts = posts.filter((post: any) => post.user._id === user._id);
35 | setData(myPosts);
36 | }
37 | }, [posts, user]);
38 |
39 | useEffect(() => {
40 | if (posts && user) {
41 | const myReplies = posts.filter((post: any) =>
42 | post.replies.some((reply: any) => reply.user._id === user._id),
43 | );
44 | setRepliesData(myReplies.filter((post: any) => post.replies.length > 0));
45 | }
46 | }, [posts, user]);
47 |
48 | return (
49 |
50 |
51 |
52 |
55 |
56 | {user?.name}
57 |
58 | {user?.userName}
59 |
60 |
61 |
62 |
63 |
69 | {user.role === 'Admin' && (
70 |
78 | )}
79 |
80 |
81 |
82 | {user?.bio}
83 |
84 |
85 |
87 | navigation.navigate('FollowerCard', {
88 | followers: user?.followers,
89 | following: user?.following,
90 | })
91 | }>
92 |
93 | {user?.followers.length} followers
94 |
95 |
96 |
97 |
98 | navigation.navigate('EditProfile')}>
100 |
107 | Edit Profile
108 |
109 |
110 |
111 |
118 | Log Out
119 |
120 |
121 |
122 |
125 |
126 | setActive(0)}>
127 |
130 | Threads
131 |
132 |
133 | setActive(1)}>
134 |
137 | Replies
138 |
139 |
140 |
141 |
142 | {active === 0 ? (
143 |
144 | ) : (
145 |
146 | )}
147 |
148 | {active === 0 && (
149 | <>
150 | {data &&
151 | data.map((item: any) => (
152 |
153 | ))}
154 | >
155 | )}
156 |
157 | {active === 1 && (
158 | <>
159 | {repliesData &&
160 | repliesData.map((item: any) => (
161 |
167 | ))}
168 | >
169 | )}
170 |
171 | {active === 0 && (
172 | <>
173 | {data.length === 0 && (
174 |
175 | You have no posts yet!
176 |
177 | )}
178 | >
179 | )}
180 |
181 | {active === 1 && (
182 | <>
183 | {repliesData.length === 0 && (
184 |
185 | You have no replies yet!
186 |
187 | )}
188 | >
189 | )}
190 |
191 |
192 | );
193 | };
194 |
195 | export default ProfileScreen;
196 |
--------------------------------------------------------------------------------
/client/src/screens/SearchScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | Image,
6 | TextInput,
7 | FlatList,
8 | TouchableOpacity,
9 | } from 'react-native';
10 | import React, {useEffect, useState} from 'react';
11 | import {useDispatch, useSelector} from 'react-redux';
12 | import {
13 | followUserAction,
14 | getAllUsers,
15 | unfollowUserAction,
16 | } from '../../redux/actions/userAction';
17 | import Loader from '../common/Loader';
18 |
19 | type Props = {
20 | navigation: any;
21 | };
22 |
23 | const SearchScreen = ({navigation}: Props) => {
24 | const [data, setData] = useState([
25 | {
26 | name: '',
27 | userName: '',
28 | avatar: {url: ''},
29 | followers: [],
30 | },
31 | ]);
32 | const {users, user, isLoading} = useSelector((state: any) => state.user);
33 | const dispatch = useDispatch();
34 |
35 | useEffect(() => {
36 | getAllUsers()(dispatch);
37 | }, [dispatch]);
38 |
39 | useEffect(() => {
40 | if (users) {
41 | setData(users);
42 | }
43 | }, [users]);
44 |
45 | const handleSearchChange = (e: any) => {
46 | if (e.length !== 0) {
47 | const filteredUsers =
48 | users &&
49 | users.filter((i: any) =>
50 | i.name.toLowerCase().includes(e.toLowerCase()),
51 | );
52 | setData(filteredUsers);
53 | } else {
54 | setData(users);
55 | }
56 | };
57 |
58 | return (
59 | <>
60 | {isLoading ? (
61 |
62 | ) : (
63 |
64 |
65 | Search
66 |
67 |
75 | handleSearchChange(e)}
77 | placeholder="Search"
78 | placeholderTextColor={'#000'}
79 | className="w-full h-[38px] bg-[#0000000e] rounded-[8px] pl-8 text-[#000] mt-[10px]"
80 | />
81 |
82 | {
86 | const handleFollowUnfollow = async (e: any) => {
87 | try {
88 | if (e.followers.find((i: any) => i.userId === user._id)) {
89 | await unfollowUserAction({
90 | userId: user._id,
91 | users,
92 | followUserId: e._id,
93 | })(dispatch);
94 | } else {
95 | await followUserAction({
96 | userId: user._id,
97 | users,
98 | followUserId: e._id,
99 | })(dispatch);
100 | }
101 | } catch (error) {
102 | console.log(error, 'error');
103 | }
104 | };
105 | return (
106 |
108 | navigation.navigate('UserProfile', {
109 | item: item,
110 | })
111 | }>
112 |
113 |
119 |
120 |
121 |
122 |
123 | {item.name}
124 |
125 | {item?.role === 'Admin' && (
126 |
134 | )}
135 |
136 |
137 |
138 | {item.userName}
139 |
140 |
141 | {item.followers.length} followers
142 |
143 |
144 |
145 | handleFollowUnfollow(item)}>
148 |
149 | {item.followers.find(
150 | (i: any) => i.userId === user._id,
151 | )
152 | ? 'Following'
153 | : 'Follow'}
154 |
155 |
156 |
157 |
158 |
159 |
160 | );
161 | }}
162 | />
163 |
164 |
165 | )}
166 | >
167 | );
168 | };
169 |
170 | export default SearchScreen;
171 |
--------------------------------------------------------------------------------
/client/src/screens/SignupScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | TextInput,
5 | Button,
6 | TouchableOpacity,
7 | ToastAndroid,
8 | Alert,
9 | Image,
10 | Platform,
11 | } from 'react-native';
12 | import {useEffect, useState} from 'react';
13 | import ImagePicker, {ImageOrVideo} from 'react-native-image-crop-picker';
14 | import {useDispatch, useSelector} from 'react-redux';
15 | import {loadUser, registerUser} from '../../redux/actions/userAction';
16 |
17 | type Props = {
18 | navigation: any;
19 | };
20 |
21 | const SignupScreen = ({navigation}: Props) => {
22 | const [email, setEmail] = useState('');
23 | const [name, setName] = useState('');
24 | const [password, setPassword] = useState('');
25 | const [avatar, setAvatar] = useState('');
26 | const dispatch = useDispatch();
27 | const {error, isAuthenticated} = useSelector((state: any) => state.user);
28 |
29 | useEffect(() => {
30 | if (error) {
31 | if(Platform.OS === 'android'){
32 | ToastAndroid.show(error, ToastAndroid.LONG);
33 | } else{
34 | Alert.alert(error);
35 | }
36 | }
37 | if (isAuthenticated) {
38 | loadUser()(dispatch);
39 | }
40 | }, [error, isAuthenticated]);
41 |
42 | const uploadImage = () => {
43 | ImagePicker.openPicker({
44 | width: 300,
45 | height: 300,
46 | cropping: true,
47 | compressImageQuality: 0.8,
48 | includeBase64: true,
49 | }).then((image: ImageOrVideo | null) => {
50 | if (image) {
51 | setAvatar('data:image/jpeg;base64,' + image.data);
52 | }
53 | });
54 | };
55 |
56 | const submitHandler = (e: any) => {
57 | if(avatar === '' || name === '' || email === ''){
58 | if(Platform.OS === 'android'){
59 | ToastAndroid.show('Please fill the all fields and upload avatar', ToastAndroid.LONG);
60 | } else{
61 | Alert.alert('Please fill the all fields and upload avatar')
62 | }
63 | } else{
64 | registerUser(name, email, password, avatar)(dispatch);
65 | }
66 | };
67 |
68 | return (
69 |
70 |
71 |
72 | Sign Up
73 |
74 | setName(text)}
78 | placeholderTextColor={'#000'}
79 | className="w-full h-[35px] border text-black border-[#00000072] px-2 my-2"
80 | />
81 | setEmail(text)}
85 | placeholderTextColor={'#000'}
86 | className="w-full h-[35px] border border-[#00000072] text-black px-2 my-2"
87 | />
88 | setPassword(text)}
93 | secureTextEntry={true}
94 | placeholderTextColor={'#000'}
95 | />
96 |
99 |
107 | upload image
108 |
109 |
110 |
111 | Sign Up
112 |
113 |
114 | navigation.navigate('Login')}>
117 | Already have an account? Sign in
118 |
119 |
120 |
121 | );
122 | };
123 |
124 | export default SignupScreen;
125 |
--------------------------------------------------------------------------------
/client/src/screens/UserProfileScreen.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | View,
3 | Text,
4 | SafeAreaView,
5 | TouchableOpacity,
6 | Image,
7 | ScrollView,
8 | } from 'react-native';
9 | import React, {useEffect, useState} from 'react';
10 | import {useDispatch, useSelector} from 'react-redux';
11 | import {
12 | followUserAction,
13 | unfollowUserAction,
14 | } from '../../redux/actions/userAction';
15 | import PostCard from '../components/PostCard';
16 |
17 | type Props = {
18 | route: any;
19 | navigation: any;
20 | };
21 |
22 | const UserProfileScreen = ({navigation, route}: Props) => {
23 | const {users, user, isLoading} = useSelector((state: any) => state.user);
24 | const [imagePreview, setImagePreview] = useState(false);
25 | const [active, setActive] = useState(0);
26 | const {posts} = useSelector((state: any) => state.post);
27 | const [postData, setPostsData] = useState([]);
28 | const [repliesData, setRepliesData] = useState([]);
29 | const d = route.params.item;
30 | const [data, setData] = useState(d);
31 | const dispatch = useDispatch();
32 |
33 | useEffect(() => {
34 | if (users) {
35 | const userData = users.find((i: any) => i._id === d?._id);
36 | setData(userData);
37 | }
38 | if (posts) {
39 | const myPosts = posts.filter((post: any) =>
40 | post.replies.some((reply: any) => reply.user._id === d._id),
41 | );
42 |
43 | setRepliesData(myPosts.filter((post: any) => post.replies.length > 0));
44 |
45 | const myUserPosts = posts.filter((post: any) => post.user._id === d._id);
46 | setPostsData(myUserPosts);
47 | }
48 | }, [users, route.params.item, posts, d]);
49 |
50 | const FollowUnfollowHandler = async () => {
51 | try {
52 | if (data.followers.find((i: any) => i.userId === user._id)) {
53 | await unfollowUserAction({
54 | userId: user._id,
55 | users,
56 | followUserId: data._id,
57 | })(dispatch);
58 | } else {
59 | await followUserAction({
60 | userId: user._id,
61 | users,
62 | followUserId: data._id,
63 | })(dispatch);
64 | }
65 | } catch (error) {
66 | console.log(error, 'error');
67 | }
68 | };
69 |
70 | return (
71 | <>
72 | {data && (
73 |
74 | {imagePreview ? (
75 | setImagePreview(!imagePreview)}>
78 |
84 |
85 | ) : (
86 |
87 | navigation.goBack()}>
88 |
95 |
96 |
97 |
98 |
99 |
100 | {data.name}
101 |
102 | {data.userName && (
103 |
104 | {data.userName}
105 |
106 | )}
107 | {data.bio && (
108 |
109 | {data.bio}
110 |
111 | )}
112 |
114 | navigation.navigate('FollowerCard', {
115 | item: data,
116 | followers: data?.followers,
117 | following: data?.following,
118 | })
119 | }>
120 |
121 | {data.followers.length} followers
122 |
123 |
124 |
125 | setImagePreview(!imagePreview)}>
127 |
128 |
134 | {data.role === 'Admin' && (
135 |
143 | )}
144 |
145 |
146 |
147 |
150 |
151 | {data.followers.find((i: any) => i.userId === user._id)
152 | ? 'Following'
153 | : 'Follow'}
154 |
155 |
156 |
157 |
158 | setActive(0)}>
159 |
162 | {' '}
163 | Threads
164 |
165 |
166 | setActive(1)}>
167 |
170 | {' '}
171 | Replies
172 |
173 |
174 |
175 | {active === 0 ? (
176 |
177 | ) : (
178 |
179 | )}
180 |
181 | {active === 0 && (
182 | <>
183 | {postData &&
184 | postData.map((item: any) => (
185 |
190 | ))}
191 | {postData.length === 0 && (
192 |
193 | No Post yet!
194 |
195 | )}
196 | >
197 | )}
198 |
199 | {active === 1 && (
200 | <>
201 | {repliesData &&
202 | repliesData.map((item: any) => (
203 |
209 | ))}
210 | {active !== 1 && postData.length === 0 && (
211 |
212 | No Post yet!
213 |
214 | )}
215 | >
216 | )}
217 |
218 |
219 | )}
220 |
221 | )}
222 | >
223 | );
224 | };
225 |
226 | export default UserProfileScreen;
227 |
--------------------------------------------------------------------------------
/client/tailwind.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('tailwindcss').Config} */
2 | module.exports = {
3 | content: [
4 | './App.{js,jsx,ts,tsx}',
5 | './src/screens/*.{js,jsx,ts,tsx}',
6 | './src/components/*.{js,jsx,ts,tsx}',
7 | ],
8 | theme: {
9 | extend: {},
10 | },
11 | plugins: [],
12 | };
13 |
--------------------------------------------------------------------------------
/client/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "@tsconfig/react-native/tsconfig.json",
3 | "compilerOptions": {
4 | "jsx": "react-native",
5 | "moduleResolution": "node",
6 | },
7 | }
8 |
--------------------------------------------------------------------------------
/server/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shahriarsajeeb/threads-clone/5d9859b899fb2d7e35d5d6cdb33fd768a75ca8a4/server/.DS_Store
--------------------------------------------------------------------------------
/server/.env:
--------------------------------------------------------------------------------
1 | PORT =
2 |
3 | CLOUDINARY_NAME =
4 |
5 | CLOUDINARY_API_KEY =
6 |
7 | CLOUDINARY_API_SECRET =
8 |
9 | DB_URL =
10 |
11 | JWT_EXPIRES = 7d
12 |
13 | JWT_SECRET_KEY = 'TWFzcyBKU09OLkFQSSBTZWNyZXQgS2V5'
--------------------------------------------------------------------------------
/server/app.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const app = express();
3 | const cookieParser = require("cookie-parser");
4 | const bodyParser = require("body-parser");
5 | const ErrorHandler = require("./middleware/error");
6 | app.use(express.json());
7 | app.use(cookieParser());
8 | app.use(bodyParser.urlencoded({ extended: true, limit: "50mb" }));
9 | app.use(express.urlencoded({ limit: "50mb", extended: true }));
10 |
11 | // config
12 | if (process.env.NODE_ENV !== "PRODUCTION") {
13 | require("dotenv").config({
14 | path: ".env",
15 | });
16 | }
17 |
18 | // Route imports
19 | const user = require("./routes/user");
20 | const post = require("./routes/Post");
21 |
22 | app.use("/api/v1", user);
23 | app.use("/api/v1", post);
24 |
25 | // it's for errorHandeling
26 | app.use(ErrorHandler);
27 |
28 | module.exports = app;
29 |
--------------------------------------------------------------------------------
/server/controllers/user.js:
--------------------------------------------------------------------------------
1 | const User = require("../models/UserModel");
2 | const ErrorHandler = require("../utils/ErrorHandler.js");
3 | const catchAsyncErrors = require("../middleware/catchAsyncErrors");
4 | const sendToken = require("../utils/jwtToken.js");
5 | const cloudinary = require("cloudinary");
6 | const Notification = require("../models/NotificationModel");
7 |
8 | // Register user
9 | exports.createUser = catchAsyncErrors(async (req, res, next) => {
10 | try {
11 | const { name, email, password, avatar } = req.body;
12 |
13 | let user = await User.findOne({ email });
14 | if (user) {
15 | return res
16 | .status(400)
17 | .json({ success: false, message: "User already exists" });
18 | }
19 |
20 | let myCloud;
21 |
22 | if (avatar) {
23 | myCloud = await cloudinary.v2.uploader.upload(avatar, {
24 | folder: "avatars",
25 | });
26 | }
27 |
28 | const userNameWithoutSpace = name.replace(/\s/g, "");
29 |
30 | const uniqueNumber = Math.floor(Math.random() * 1000);
31 |
32 | user = await User.create({
33 | name,
34 | email,
35 | password,
36 | userName: userNameWithoutSpace + uniqueNumber,
37 | avatar: avatar
38 | ? { public_id: myCloud.public_id, url: myCloud.secure_url }
39 | : null,
40 | });
41 |
42 | sendToken(user, 201, res);
43 | } catch (error) {
44 | res.status(500).json({
45 | success: false,
46 | message: error.message,
47 | });
48 | }
49 | });
50 |
51 | // Login User
52 | exports.loginUser = catchAsyncErrors(async (req, res, next) => {
53 | const { email, password } = req.body;
54 |
55 | if (!email || !password) {
56 | return next(new ErrorHandler("Please enter the email & password", 400));
57 | }
58 |
59 | const user = await User.findOne({ email }).select("+password");
60 |
61 | if (!user) {
62 | return next(
63 | new ErrorHandler("User is not find with this email & password", 401)
64 | );
65 | }
66 | const isPasswordMatched = await user.comparePassword(password);
67 |
68 | if (!isPasswordMatched) {
69 | return next(
70 | new ErrorHandler("User is not find with this email & password", 401)
71 | );
72 | }
73 |
74 | sendToken(user, 201, res);
75 | });
76 |
77 | // Log out user
78 | exports.logoutUser = catchAsyncErrors(async (req, res, next) => {
79 | res.cookie("token", null, {
80 | expires: new Date(Date.now()),
81 | httpOnly: true,
82 | sameSite: "none",
83 | secure: true,
84 | });
85 |
86 | res.status(200).json({
87 | success: true,
88 | message: "Log out success",
89 | });
90 | });
91 |
92 | // Get user Details
93 | exports.userDetails = catchAsyncErrors(async (req, res, next) => {
94 | const user = await User.findById(req.user.id);
95 | res.status(200).json({
96 | success: true,
97 | user,
98 | });
99 | });
100 |
101 | // get all users
102 | exports.getAllUsers = catchAsyncErrors(async (req, res, next) => {
103 | const loggedInuser = req.user.id;
104 | const users = await User.find({ _id: { $ne: loggedInuser } }).sort({
105 | createdAt: -1,
106 | });
107 |
108 | res.status(201).json({
109 | success: true,
110 | users,
111 | });
112 | });
113 |
114 | // Follow and unfollow user
115 | exports.followUnfollowUser = catchAsyncErrors(async (req, res, next) => {
116 | try {
117 | const loggedInUser = req.user;
118 | const { followUserId } = req.body;
119 |
120 | const isFollowedBefore = loggedInUser.following.find(
121 | (item) => item.userId === followUserId
122 | );
123 | const loggedInUserId = loggedInUser._id;
124 |
125 | if (isFollowedBefore) {
126 | await User.updateOne(
127 | { _id: followUserId },
128 | { $pull: { followers: { userId: loggedInUserId } } }
129 | );
130 |
131 | await User.updateOne(
132 | { _id: loggedInUserId },
133 | { $pull: { following: { userId: followUserId } } }
134 | );
135 |
136 | await Notification.deleteOne({
137 | "creator._id": loggedInUserId,
138 | userId: followUserId,
139 | type: "Follow",
140 | });
141 |
142 | res.status(200).json({
143 | success: true,
144 | message: "User unfollowed successfully",
145 | });
146 | } else {
147 | await User.updateOne(
148 | { _id: followUserId },
149 | { $push: { followers: { userId: loggedInUserId } } }
150 | );
151 |
152 | await User.updateOne(
153 | { _id: loggedInUserId },
154 | { $push: { following: { userId: followUserId } } }
155 | );
156 |
157 | await Notification.create({
158 | creator: req.user,
159 | type: "Follow",
160 | title: "Followed you",
161 | userId: followUserId,
162 | });
163 |
164 | res.status(200).json({
165 | success: true,
166 | message: "User followed successfully",
167 | });
168 | }
169 | } catch (error) {
170 | return next(new ErrorHandler(error.message, 401));
171 | }
172 | });
173 |
174 | // get user notification
175 | exports.getNotification = catchAsyncErrors(async (req, res, next) => {
176 | try {
177 | const notifications = await Notification.find({ userId: req.user.id }).sort(
178 | { createdAt: -1 }
179 | );
180 |
181 | res.status(201).json({
182 | success: true,
183 | notifications,
184 | });
185 | } catch (error) {
186 | return next(new ErrorHandler(error.message, 401));
187 | }
188 | });
189 |
190 | // get signle user
191 | exports.getUser = catchAsyncErrors(async (req, res, next) => {
192 | try {
193 | const user = await User.findById(req.params.id);
194 |
195 | res.status(201).json({ success: true, user });
196 | } catch (error) {
197 | return next(new ErrorHandler(error.message, 401));
198 | }
199 | });
200 |
201 | // update user avatar
202 | exports.updateUserAvatar = catchAsyncErrors(async (req, res, next) => {
203 | try {
204 | let existsUser = await User.findById(req.user.id);
205 |
206 | if (req.body.avatar !== "") {
207 | const imageId = existsUser.avatar.public_id;
208 |
209 | await cloudinary.v2.uploader.destroy(imageId);
210 |
211 | const myCloud = await cloudinary.v2.uploader.upload(req.body.avatar, {
212 | folder: "avatars",
213 | width: 150,
214 | });
215 |
216 | existsUser.avatar = {
217 | public_id: myCloud.public_id,
218 | url: myCloud.secure_url,
219 | };
220 | }
221 | await existsUser.save();
222 |
223 | res.status(200).json({
224 | success: true,
225 | user: existsUser,
226 | });
227 | } catch (error) {
228 | return next(new ErrorHandler(error.message, 401));
229 | }
230 | });
231 |
232 | // update user info
233 | exports.updateUserInfo = catchAsyncErrors(async (req, res, next) => {
234 | try {
235 | const user = await User.findById(req.user.id);
236 |
237 | user.name = req.body.name;
238 | user.userName = req.body.userName;
239 | user.bio = req.body.bio;
240 |
241 | await user.save();
242 |
243 | res.status(201).json({
244 | success: true,
245 | user,
246 | });
247 | } catch (error) {
248 | return next(new ErrorHandler(error.message, 401));
249 | }
250 | });
251 |
--------------------------------------------------------------------------------
/server/db/db.js:
--------------------------------------------------------------------------------
1 | const mongoose = require("mongoose");
2 |
3 | const connectDatabase = () => {
4 | mongoose
5 | .connect(process.env.DB_URL, {
6 | useNewUrlParser: true,
7 | useUnifiedTopology: true,
8 | })
9 | .then((data) => {
10 | console.log(`mongodb is connected with server: ${data.connection.host}`);
11 | });
12 | };
13 |
14 | module.exports = connectDatabase;
15 |
--------------------------------------------------------------------------------
/server/middleware/auth.js:
--------------------------------------------------------------------------------
1 | const ErrorHandler = require("../utils/ErrorHandler.js");
2 | const catchAsyncErrors = require("./catchAsyncErrors.js");
3 | const jwt = require("jsonwebtoken");
4 | const User = require("../models/UserModel.js");
5 |
6 | exports.isAuthenticatedUser = catchAsyncErrors(async (req, res, next) => {
7 | const authHeader = req.headers.authorization;
8 | if(!authHeader || authHeader === 'Bearer undefined' || !authHeader.startsWith("Bearer ")){
9 | return next(new ErrorHandler("Please login to continue",401));
10 | }
11 |
12 | const token = authHeader.split(" ")[1];
13 | const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
14 | req.user = await User.findById(decoded.id);
15 | next();
16 | });
17 |
--------------------------------------------------------------------------------
/server/middleware/catchAsyncErrors.js:
--------------------------------------------------------------------------------
1 | module.exports = (theFunc) => (req,res,next) =>{
2 | Promise.resolve(theFunc(req,res,next)).catch(next);
3 | };
--------------------------------------------------------------------------------
/server/middleware/error.js:
--------------------------------------------------------------------------------
1 | const ErrorHandler = require("../utils/ErrorHandler");
2 |
3 | module.exports = (err,req,res,next) =>{
4 | err.statusCode = err.statusCode || 500
5 | err.message = err.message || "Interval server error"
6 |
7 | // wrong mongodb id error
8 | if(err.name === "CastError"){
9 | const message = `Resources not found with this id..Invalid ${err.path}`;
10 | err = new ErrorHandler(message, 400);
11 | }
12 |
13 |
14 | // Duplicate key error
15 | if (err.code === 11000) {
16 | const message = `Duplicate ${Object.keys(err.keyValue)} Entered`;
17 | err = new ErrorHandler(message, 400);
18 | }
19 |
20 | // Wrong Jwt error
21 | if (err.name === "JsonWebTokenError") {
22 | const message = `Your url is invalid please try again`;
23 | err = new ErrorHandler(message, 400);
24 | }
25 |
26 | //Jwt expired error
27 | if (err.name === "TokenExpiredError") {
28 | const message = `Your url is expired please try again`;
29 | err = new ErrorHandler(message, 400);
30 | }
31 |
32 | res.status(err.statusCode).json({
33 | success: false,
34 | message: err.message
35 | })
36 | }
37 |
--------------------------------------------------------------------------------
/server/models/NotificationModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require("mongoose");
2 |
3 | const notificationSchema = new mongoose.Schema(
4 | {
5 | creator:{
6 | type: Object,
7 | },
8 | type:{
9 | type: String,
10 | },
11 | title:{
12 | type: String,
13 | },
14 | postId:{
15 | type:String,
16 | },
17 | userId:{
18 | type: String,
19 | }
20 | },{timestamps: true}
21 | );
22 |
23 | module.exports = mongoose.model("Notification", notificationSchema);
--------------------------------------------------------------------------------
/server/models/PostModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require("mongoose");
2 |
3 | const postSchema = new mongoose.Schema(
4 | {
5 | title: {
6 | type: String,
7 | },
8 | image: {
9 | public_id: {
10 | type: String,
11 | },
12 | url: {
13 | type: String,
14 | },
15 | },
16 | user: {
17 | type: Object,
18 | },
19 | likes: [
20 | {
21 | name: {
22 | type: String,
23 | },
24 | userName: {
25 | type: String,
26 | },
27 | userId: {
28 | type: String,
29 | },
30 | userAvatar: {
31 | type: String,
32 | },
33 | },
34 | ],
35 | replies: [
36 | {
37 | user: {
38 | type: Object,
39 | },
40 | title: {
41 | type: String,
42 | },
43 | image: {
44 | public_id: {
45 | type: String,
46 | },
47 | url: {
48 | type: String,
49 | },
50 | },
51 | createdAt: {
52 | type: Date,
53 | default: Date.now,
54 | },
55 | likes: [
56 | {
57 | name: {
58 | type: String,
59 | },
60 | userName: {
61 | type: String,
62 | },
63 | userId: {
64 | type: String,
65 | },
66 | userAvatar: {
67 | type: String,
68 | },
69 | },
70 | ],
71 | reply: [
72 | {
73 | user: {
74 | type: Object,
75 | },
76 | title: {
77 | type: String,
78 | },
79 | image: {
80 | public_id: {
81 | type: String,
82 | },
83 | url: {
84 | type: String,
85 | },
86 | },
87 | createdAt: {
88 | type: Date,
89 | default: Date.now,
90 | },
91 | likes: [
92 | {
93 | name: {
94 | type: String,
95 | },
96 | userName: {
97 | type: String,
98 | },
99 | userId: {
100 | type: String,
101 | },
102 | userAvatar: {
103 | type: String,
104 | },
105 | },
106 | ],
107 | },
108 | ],
109 | },
110 | ],
111 | },
112 | { timestamps: true }
113 | );
114 |
115 | module.exports = mongoose.model("Post", postSchema);
116 |
--------------------------------------------------------------------------------
/server/models/UserModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require("mongoose");
2 | const bcrypt = require("bcryptjs");
3 | const jwt = require("jsonwebtoken");
4 |
5 |
6 | const userSchema = new mongoose.Schema(
7 | {
8 | name: {
9 | type: String,
10 | required: [true, "Please enter your Name"],
11 | },
12 | userName: {
13 | type: String,
14 | },
15 | bio: {
16 | type: String,
17 | },
18 | email: {
19 | type: String,
20 | required: [true, "Please enter your email"],
21 | },
22 | password: {
23 | type: String,
24 | required: [true, "Please enter your password"],
25 | },
26 | avatar: {
27 | public_id: {
28 | type: String,
29 | required: [true, "Please upload one profile picture"],
30 | },
31 | url: {
32 | type: String,
33 | required: [true, "Please upload one profile picture"],
34 | },
35 | },
36 | followers: [
37 | {
38 | userId: {
39 | type: String,
40 | },
41 | },
42 | ],
43 | following: [
44 | {
45 | userId: {
46 | type: String,
47 | },
48 | },
49 | ],
50 | },
51 | { timestamps: true }
52 | );
53 |
54 | // Hash password
55 | userSchema.pre("save", async function (next) {
56 | if (!this.isModified("password")) {
57 | next();
58 | }
59 | this.password = await bcrypt.hash(this.password, 10);
60 | });
61 |
62 | // jwt token
63 | userSchema.methods.getJwtToken = function () {
64 | return jwt.sign({ id: this._id }, process.env.JWT_SECRET_KEY, {
65 | expiresIn: process.env.JWT_EXPIRES,
66 | });
67 | };
68 |
69 | // compare password
70 | userSchema.methods.comparePassword = async function (enteredPassword) {
71 | return await bcrypt.compare(enteredPassword, this.password);
72 | };
73 |
74 | module.exports = mongoose.model("User", userSchema);
75 |
--------------------------------------------------------------------------------
/server/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "server",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "server.js",
6 | "engines": {
7 | "node": "18.x"
8 | },
9 | "scripts": {
10 | "test": "echo \"Error: no test specified\" && exit 1",
11 | "dev": "nodemon server.js",
12 | "start": "node server.js"
13 | },
14 | "author": "shahriar sajeeb",
15 | "license": "ISC",
16 | "dependencies": {
17 | "bcryptjs": "^2.4.3",
18 | "body-parser": "^1.20.2",
19 | "cloudinary": "^1.37.3",
20 | "cookie-parser": "^1.4.6",
21 | "cors": "^2.8.5",
22 | "dotenv": "^16.3.1",
23 | "express": "^4.18.2",
24 | "jsonwebtoken": "^9.0.1",
25 | "mongoose": "^7.3.2",
26 | "nodemon": "^2.0.22"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/server/routes/Post.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const {
3 | createPost,
4 | getAllPosts,
5 | updateLikes,
6 | addReplies,
7 | updateReplyLikes,
8 | addReply,
9 | updateRepliesReplyLike,
10 | deletePost,
11 | } = require("../controllers/post");
12 | const { isAuthenticatedUser } = require("../middleware/auth");
13 |
14 | const router = express.Router();
15 |
16 | router.route("/create-post").post(isAuthenticatedUser, createPost);
17 |
18 | router.route("/get-all-posts").get(isAuthenticatedUser, getAllPosts);
19 |
20 | router.route("/update-likes").put(isAuthenticatedUser, updateLikes);
21 |
22 | router.route("/add-replies").put(isAuthenticatedUser, addReplies);
23 |
24 | router.route("/add-reply").put(isAuthenticatedUser, addReply);
25 |
26 | router
27 | .route("/update-replies-react")
28 | .put(isAuthenticatedUser, updateReplyLikes);
29 |
30 | router
31 | .route("/update-reply-react")
32 | .put(isAuthenticatedUser, updateRepliesReplyLike);
33 |
34 | router.route("/delete-post/:id").delete(isAuthenticatedUser, deletePost);
35 |
36 |
37 | module.exports = router;
38 |
--------------------------------------------------------------------------------
/server/routes/user.js:
--------------------------------------------------------------------------------
1 | const express = require("express");
2 | const {
3 | createUser,
4 | loginUser,
5 | logoutUser,
6 | userDetails,
7 | getAllUsers,
8 | followUnfollowUser,
9 | getNotification,
10 | getUser,
11 | updateUserAvatar,
12 | updateUserInfo,
13 | } = require("../controllers/user");
14 | const { isAuthenticatedUser } = require("../middleware/auth");
15 | const router = express.Router();
16 |
17 | router.route("/registration").post(createUser);
18 |
19 | router.route("/login").post(loginUser);
20 |
21 | router.route("/logout").get(logoutUser);
22 |
23 | router.route("/users").get(isAuthenticatedUser, getAllUsers);
24 |
25 | router.route("/add-user").put(isAuthenticatedUser, followUnfollowUser);
26 |
27 | router.route("/get-notifications").get(isAuthenticatedUser, getNotification);
28 |
29 | router.route("/get-user/:id").get(isAuthenticatedUser, getUser);
30 |
31 | router.route("/update-avatar").put(isAuthenticatedUser, updateUserAvatar);
32 |
33 | router.route("/update-profile").put(isAuthenticatedUser, updateUserInfo);
34 |
35 | router.route("/me").get(isAuthenticatedUser, userDetails);
36 |
37 | module.exports = router;
38 |
--------------------------------------------------------------------------------
/server/server.js:
--------------------------------------------------------------------------------
1 | const app = require("./app");
2 | const cloudinary = require("cloudinary");
3 | const connectDatabase = require("./db/db");
4 |
5 | // Handling uncaught Exception
6 | process.on("uncaughtException",(err) =>{
7 | console.log(`Error: ${err.message}`);
8 | console.log(`Shutting down the server for Handling uncaught Exception`);
9 | })
10 |
11 | // config
12 | if(process.env.NODE_ENV!=="PRODUCTION"){
13 | require("dotenv").config({
14 | path:".env"
15 | })}
16 |
17 | // connect database
18 | connectDatabase();
19 |
20 | cloudinary.config({
21 | cloud_name: process.env.CLOUDINARY_NAME,
22 | api_key: process.env.CLOUDINARY_API_KEY,
23 | api_secret: process.env.CLOUDINARY_API_SECRET
24 | })
25 |
26 | // create server
27 | const server = app.listen(process.env.PORT,() =>{
28 | console.log(`Server is working on http://localhost:${process.env.PORT}`)
29 | })
30 |
31 |
32 | // Unhandled promise rejection
33 | process.on("unhandledRejection", (err) =>{
34 | console.log(`Shutting down server for ${err.message}`);
35 | console.log(`Shutting down the server due to Unhandled promise rejection`);
36 | server.close(() =>{
37 | process.exit(1);
38 | });
39 | });
--------------------------------------------------------------------------------
/server/utils/ErrorHandler.js:
--------------------------------------------------------------------------------
1 | class ErrorHandler extends Error{
2 | constructor(message,statusCode){
3 | super(message);
4 | this.statusCode = statusCode
5 |
6 | Error.captureStackTrace(this,this.constructor);
7 |
8 | }
9 |
10 | }
11 | module.exports = ErrorHandler
--------------------------------------------------------------------------------
/server/utils/jwtToken.js:
--------------------------------------------------------------------------------
1 | // create token and saving that in cookies
2 | const sendToken = (user,statusCode,res) =>{
3 |
4 | const token = user.getJwtToken();
5 |
6 | // Options for cookies
7 | const options = {
8 | expires: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
9 | httpOnly: true,
10 | sameSite: "none",
11 | secure: true,
12 | };
13 |
14 | res.status(statusCode).cookie("token",token,options).json({
15 | success: true,
16 | user,
17 | token
18 | });
19 | }
20 |
21 | module.exports = sendToken;
--------------------------------------------------------------------------------
/server/vercel.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": 2,
3 | "name":"threads-tutorial",
4 | "builds":[
5 | {"src":"server.js","use":"@vercel/node"}
6 | ],
7 | "routes":[
8 | {"src":"/(.*)","dest":"/server.js"}
9 | ]
10 | }
--------------------------------------------------------------------------------