diff --git a/client/.gitignore b/client/.gitignore
new file mode 100755
index 0000000..bdee10e
--- /dev/null
+++ b/client/.gitignore
@@ -0,0 +1,24 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+node_modules
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
diff --git a/client/README.md b/client/README.md
new file mode 100755
index 0000000..9d9614c
--- /dev/null
+++ b/client/README.md
@@ -0,0 +1,68 @@
+This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
+
+## Available Scripts
+
+In the project directory, you can run:
+
+### `npm start`
+
+Runs the app in the development mode.
+Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
+
+The page will reload if you make edits.
+You will also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
+
+### `npm run build`
+
+Builds the app for production to the `build` folder.
+It correctly bundles React in production mode and optimizes the build for the best performance.
+
+The build is minified and the filenames include the hashes.
+Your app is ready to be deployed!
+
+See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
+
+If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
+
+Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
+
+You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
+
+## Learn More
+
+You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
+
+To learn React, check out the [React documentation](https://reactjs.org/).
+
+### Code Splitting
+
+This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
+
+### Analyzing the Bundle Size
+
+This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
+
+### Making a Progressive Web App
+
+This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
+
+### Advanced Configuration
+
+This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
+
+### Deployment
+
+This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
+
+### `npm run build` fails to minify
+
+This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
diff --git a/README.md b/client/README.old.md
similarity index 100%
rename from README.md
rename to client/README.old.md
diff --git a/client/package.json b/client/package.json
new file mode 100644
index 0000000..de29899
--- /dev/null
+++ b/client/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "react-challenge",
+ "version": "0.1.0",
+ "private": true,
+ "dependencies": {
+ "@fortawesome/fontawesome-svg-core": "^1.2.15",
+ "@fortawesome/free-solid-svg-icons": "^5.7.2",
+ "@fortawesome/react-fontawesome": "^0.1.4",
+ "@material-ui/core": "^3.9.2",
+ "axios": "^0.18.0",
+ "bootstrap": "^4.3.1",
+ "i": "^0.3.6",
+ "movie-trailer": "^2.0.3",
+ "npm": "^6.8.0",
+ "react": "^16.8.3",
+ "react-dom": "^16.8.3",
+ "react-redux": "^6.0.1",
+ "react-router-dom": "^4.3.1",
+ "react-scripts": "2.1.5",
+ "redux": "^4.0.1",
+ "redux-devtools-extension": "^2.13.8",
+ "redux-thunk": "^2.3.0"
+ },
+ "scripts": {
+ "start": "react-scripts start",
+ "build": "react-scripts build",
+ "test": "react-scripts test",
+ "eject": "react-scripts eject"
+ },
+ "eslintConfig": {
+ "extends": "react-app"
+ },
+ "browserslist": [
+ ">0.2%",
+ "not dead",
+ "not ie <= 11",
+ "not op_mini all"
+ ]
+}
diff --git a/client/public/favicon.ico b/client/public/favicon.ico
new file mode 100755
index 0000000..a11777c
Binary files /dev/null and b/client/public/favicon.ico differ
diff --git a/client/public/index.html b/client/public/index.html
new file mode 100755
index 0000000..bf1ac51
--- /dev/null
+++ b/client/public/index.html
@@ -0,0 +1,48 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+ React App
+
+
+ You need to enable JavaScript to run this app.
+
+
+
+
+
+
+
+
diff --git a/client/public/manifest.json b/client/public/manifest.json
new file mode 100755
index 0000000..1f2f141
--- /dev/null
+++ b/client/public/manifest.json
@@ -0,0 +1,15 @@
+{
+ "short_name": "React App",
+ "name": "Create React App Sample",
+ "icons": [
+ {
+ "src": "favicon.ico",
+ "sizes": "64x64 32x32 24x24 16x16",
+ "type": "image/x-icon"
+ }
+ ],
+ "start_url": ".",
+ "display": "standalone",
+ "theme_color": "#000000",
+ "background_color": "#ffffff"
+}
diff --git a/client/src/App.css b/client/src/App.css
new file mode 100755
index 0000000..db09c29
--- /dev/null
+++ b/client/src/App.css
@@ -0,0 +1,37 @@
+.App {
+ text-align: center;
+}
+
+.App-logo {
+ animation: App-logo-spin infinite 20s linear;
+ height: 40vmin;
+ pointer-events: none;
+}
+
+ul {
+ list-style-type: none;
+}
+
+/* .App-header {
+ background-color: #282c34;
+ min-height: 100vh;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ font-size: calc(10px + 2vmin);
+ color: white;
+} */
+
+.App-link {
+ color: #61dafb;
+}
+
+@keyframes App-logo-spin {
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+}
diff --git a/client/src/App.js b/client/src/App.js
new file mode 100755
index 0000000..d01d4a9
--- /dev/null
+++ b/client/src/App.js
@@ -0,0 +1,44 @@
+import React, { Component } from 'react';
+import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
+import './App.css';
+
+//store
+import { Provider } from 'react-redux'
+import store from './store'
+
+//components
+import Home from './components/Home'
+import Register from './components/Register'
+import Login from './components/Login'
+import NotFound from './components/NotFound'
+
+
+//fontawesome
+import { library } from '@fortawesome/fontawesome-svg-core'
+import { faSearch, faHome } from '@fortawesome/free-solid-svg-icons'
+
+library.add(faSearch, faHome)
+
+class App extends Component {
+
+ render() {
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ );
+ }
+}
+
+export default App;
diff --git a/client/src/App.test.js b/client/src/App.test.js
new file mode 100755
index 0000000..a754b20
--- /dev/null
+++ b/client/src/App.test.js
@@ -0,0 +1,9 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import App from './App';
+
+it('renders without crashing', () => {
+ const div = document.createElement('div');
+ ReactDOM.render( , div);
+ ReactDOM.unmountComponentAtNode(div);
+});
diff --git a/client/src/components/Home.jsx b/client/src/components/Home.jsx
new file mode 100644
index 0000000..da69fcc
--- /dev/null
+++ b/client/src/components/Home.jsx
@@ -0,0 +1,48 @@
+import React, { Component } from 'react'
+import { Route, Switch } from 'react-router-dom'
+import { connect } from 'react-redux'
+
+//actions
+import { authenticateToken } from '../store/actions/UsersAction'
+
+//containers
+import FilmList from '../containers/film/FilmList'
+import FilmDetails from '../containers/film/FilmDetails'
+import Navbar from '../containers/Navbar'
+import PrivateRoute from '../containers/PrivateWatchList'
+
+class Home extends Component {
+ componentDidMount() {
+ if (localStorage.getItem('token')) {
+ this.props.authenticateToken()
+ }
+ }
+
+ render() {
+ const { isLoggedIn } = this.props
+
+ return (
+
+ )
+ }
+}
+
+const mapDispatchToProps = (dispatch) => ({
+ authenticateToken: () => (dispatch(authenticateToken()))
+})
+
+const mapStateToProps = (state) => ({
+ isLoggedIn: state.Users.isLoggedIn
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(Home)
+
+
diff --git a/client/src/components/Login.jsx b/client/src/components/Login.jsx
new file mode 100644
index 0000000..2416fa1
--- /dev/null
+++ b/client/src/components/Login.jsx
@@ -0,0 +1,83 @@
+import React, { Component } from 'react'
+import { Link, Redirect } from 'react-router-dom'
+import { connect } from 'react-redux'
+
+//actions
+import { login } from '../store/actions/UsersAction'
+
+class Login extends Component {
+ constructor(props) {
+ super(props)
+ this.state = {
+ email: '',
+ password: ''
+ }
+
+ this.handleChange = this.handleChange.bind(this)
+ this.handleSubmit = this.handleSubmit.bind(this)
+ }
+
+ handleChange(event) {
+ this.setState({ [event.target.name]: event.target.value })
+ }
+
+ handleSubmit(event) {
+ var objUser = {
+ email: this.state.email,
+ password: this.state.password
+ }
+
+ this.props.login(objUser)
+ event.preventDefault()
+ }
+
+ render() {
+ const { errors, isLoggedIn } = this.props
+ if (isLoggedIn) {
+ return
+ }
+
+ return (
+
+
+
+
Sign In To Your Account
+
+
+ Don't have an account?
Sign Up
+
+
+
+
+
+
+
+ )
+ }
+}
+
+const mapDispatchToProps = (dispatch) => ({
+ login: (user) => dispatch(login(user))
+})
+
+const mapStateToProps = (state) => ({
+ errors: state.Users.errors,
+ isLoggedIn: state.Users.isLoggedIn
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(Login)
\ No newline at end of file
diff --git a/client/src/components/NotFound.jsx b/client/src/components/NotFound.jsx
new file mode 100644
index 0000000..ef9929d
--- /dev/null
+++ b/client/src/components/NotFound.jsx
@@ -0,0 +1,13 @@
+import React, { Component } from 'react'
+import { Link } from'react-router-dom'
+
+export default class NotFound extends Component {
+ render() {
+ return (
+
+
No Results Found
+ Back To Home
+
+ )
+ }
+}
diff --git a/client/src/components/Register.jsx b/client/src/components/Register.jsx
new file mode 100644
index 0000000..b5f3b10
--- /dev/null
+++ b/client/src/components/Register.jsx
@@ -0,0 +1,88 @@
+import React, { Component } from 'react'
+import { connect } from 'react-redux'
+import { Link, Redirect } from 'react-router-dom'
+
+//actions
+import { register } from '../store/actions/UsersAction'
+
+class Register extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ email: '',
+ password: ''
+ }
+
+ this.handleChange = this.handleChange.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this)
+ }
+
+ handleChange(event) {
+ this.setState({ [event.target.name]: event.target.value })
+ }
+
+ handleSubmit(event) {
+ var objUser = {
+ email: this.state.email,
+ password: this.state.password
+ }
+
+ event.preventDefault()
+ this.props.register(objUser)
+ }
+
+ render() {
+ const { isLoggedIn, errors } = this.props
+
+ if (isLoggedIn) {
+ return
+ }
+
+ return (
+
+
+
+
Create An Account
+
+
+ Already have an account?
Sign In
+
+
+
+
+
+
+
+
+
+ )
+ }
+}
+
+const mapDispatchToProps = (dispatch) => ({
+ register: (user) => dispatch(register(user))
+})
+
+const mapStateToProps = (state) => ({
+ errors: state.Users.errors,
+ isLoggedIn: state.Users.isLoggedIn
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(Register)
diff --git a/client/src/containers/Navbar.jsx b/client/src/containers/Navbar.jsx
new file mode 100644
index 0000000..87f78b2
--- /dev/null
+++ b/client/src/containers/Navbar.jsx
@@ -0,0 +1,84 @@
+import React, { Component } from 'react'
+import { Link, withRouter } from 'react-router-dom'
+import { connect } from 'react-redux'
+import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
+
+//actions
+import { logout } from '../store/actions/UsersAction'
+
+class Navbar extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ search: ''
+ }
+
+ this.logout = this.logout.bind(this)
+ this.handleChange = this.handleChange.bind(this)
+ this.handleSubmit = this.handleSubmit.bind(this)
+ }
+
+
+ logout(event) {
+ this.props.logout()
+ event.preventDefault()
+ }
+
+ handleChange(event) {
+ this.setState({ [event.target.name]: event.target.value })
+ }
+
+ handleSubmit(event) {
+ event.preventDefault()
+ let q = new RegExp(this.state.search.toLowerCase());
+
+ var list = this.props.allFilms.filter(function (el) {
+ return el.title.toLowerCase().match(q);
+ });
+
+ if (list.length) {
+ this.props.history.push(`/details/${list[0].id}`)
+ } else {
+ this.props.history.push('*')
+ }
+
+ }
+
+
+ render() {
+ const { isLoggedIn } = this.props
+
+ return (
+
+
+ GhibliDB
+
+
+
+
+ )
+ }
+}
+
+const mapDispatchToProps = (dispatch) => ({
+ logout: () => dispatch(logout())
+})
+
+const mapStateToProps = (state) => ({
+ allFilms: state.FilmsApi.allFilms,
+ isLoggedIn: state.Users.isLoggedIn
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Navbar))
+
+
+
diff --git a/client/src/containers/PrivateWatchList.jsx b/client/src/containers/PrivateWatchList.jsx
new file mode 100644
index 0000000..3b555ab
--- /dev/null
+++ b/client/src/containers/PrivateWatchList.jsx
@@ -0,0 +1,30 @@
+import React from 'react'
+import { Route, Redirect} from 'react-router-dom'
+import { connect } from 'react-redux'
+
+
+const PrivateRoute = ({ component: Component, ...rest }) => (
+
+
+ localStorage.getItem('token') ? (
+
+ ) : (
+
+ )
+ }
+ />
+
+)
+
+const mapStateToProps = (state) => ({
+ isLoggedIn: state.Users.isLoggedIn
+})
+
+export default connect(mapStateToProps, null)(PrivateRoute)
diff --git a/client/src/containers/film/FilmDetails.jsx b/client/src/containers/film/FilmDetails.jsx
new file mode 100644
index 0000000..a5b708d
--- /dev/null
+++ b/client/src/containers/film/FilmDetails.jsx
@@ -0,0 +1,74 @@
+import React, { Component } from 'react'
+import { connect } from 'react-redux'
+//actions
+import { FetchFilmById } from '../../store/actions/FilmsApiActions'
+
+class FilmDetails extends Component {
+
+ componentDidMount() {
+ this.props.FetchFilmById(this.props.match.params.id)
+ }
+
+ render() {
+ const { film, isLoading, hasErrored } = this.props
+
+ if (hasErrored) {
+ return (
+ Sorry! There was an error loading the this page. Please try again later!
+ )
+ }
+
+ if (isLoading) {
+ return (
+
+
This may take a few seconds...
+
+
+ )
+ }
+
+ return (
+
+ {
+ film &&
+
+
{film.title}
+
+
+
+
+
+
+
+
Release Date: {film.release_date}
+
Director: {film.director}
+
Producer: {film.producer}
+
Rotten Tomatoes Score: {film.rt_score}/100
+
Description:{film.description}
+
+
+
+
+
Trailer
+
+
+
+
+ }
+
+ )
+ }
+}
+
+const MapDispatchToProps = (dispatch) => ({
+ FetchFilmById: (filmId) => dispatch(FetchFilmById(filmId))
+})
+
+const MapStateToProps = (state) => ({
+ film: state.FilmsApi.film,
+ hasErrored: state.FilmsApi.hasErrored,
+ isLoading: state.FilmsApi.isLoading
+})
+
+export default connect(MapStateToProps, MapDispatchToProps)(FilmDetails)
diff --git a/client/src/containers/film/FilmList.jsx b/client/src/containers/film/FilmList.jsx
new file mode 100644
index 0000000..60d82e6
--- /dev/null
+++ b/client/src/containers/film/FilmList.jsx
@@ -0,0 +1,64 @@
+import React, { Component } from 'react'
+import { connect } from 'react-redux'
+
+//actions
+import { FetchAllFilms, GetWatchList } from '../../store/actions/FilmsApiActions'
+
+//components
+import SingleFilm from './SingleFilm'
+
+class FilmList extends Component {
+
+ componentDidMount() {
+ this.props.FetchAllFilms()
+ this.props.GetWatchList()
+ }
+
+ render() {
+ const { allFilms, isLoading, hasErrored, watchList } = this.props
+
+ if (hasErrored) {
+ return (
+ <>
+ Sorry! There was an error loading the this page. Please try again later!
+ >
+ )
+ }
+
+ if (isLoading) {
+ return (
+
+
+
+ )
+ }
+
+ return (
+
+ {window.location.pathname === '/watchlist' ?
+ (
Your WatchList ):
+ (
Studio Ghibli Film Database )
+ }
+
+ {window.location.pathname !== '/watchlist' ? allFilms.map(film => ) : watchList.map(film => )}
+
+
+
+ )
+ }
+
+}
+
+const mapDispatchToProps = (dispatch) => ({
+ FetchAllFilms: () => dispatch(FetchAllFilms()),
+ GetWatchList: () => dispatch(GetWatchList())
+})
+
+const mapStateToProps = (state) => ({
+ allFilms: state.FilmsApi.allFilms,
+ watchList: state.FilmsApi.watchList,
+ isLoading: state.FilmsApi.isLoading,
+ hasErrored: state.FilmsApi.hasErrored
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(FilmList)
\ No newline at end of file
diff --git a/client/src/containers/film/SingleFilm.jsx b/client/src/containers/film/SingleFilm.jsx
new file mode 100644
index 0000000..53df8bb
--- /dev/null
+++ b/client/src/containers/film/SingleFilm.jsx
@@ -0,0 +1,61 @@
+import React, { Component } from 'react'
+import { Link, withRouter } from 'react-router-dom'
+import { connect } from 'react-redux'
+
+//actions
+import { AddToWatchList, RemoveFromWatchList } from '../../store/actions/FilmsApiActions'
+
+class SingleFilm extends Component {
+ constructor(props) {
+ super(props)
+ this.handleWatchList = this.handleWatchList.bind(this)
+ this.handleRemoveWatchList = this.handleRemoveWatchList.bind(this)
+ }
+
+ handleWatchList() {
+ if (localStorage.getItem('token')) {
+ this.props.AddToWatchList(this.props.film)
+ } else {
+ this.props.history.push("/login")
+ }
+ }
+
+ handleRemoveWatchList() {
+ if (localStorage.getItem('token')) {
+ this.props.RemoveFromWatchList(this.props.film)
+ } else {
+ this.props.history.push("/login")
+ }
+ }
+
+ render() {
+ const { film, watchList, isLoggedIn } = this.props
+
+ return (
+
+
+
+
+
{film.title}
+
{film.description.slice(0, 120)}...
+
+
View Details
+ {watchList.map(film => film.title).includes(film.title) && isLoggedIn?
+ (
Remove From Watchlist ) :
+ (
Add to Watchlist )
+ }
+
+ )
+ }
+}
+
+const mapDispatchToProps = (dispatch) => ({
+ AddToWatchList: (film) => dispatch(AddToWatchList(film)),
+ RemoveFromWatchList: (film) => dispatch(RemoveFromWatchList(film))
+})
+
+const mapStateToProps = (state) => ({
+ isLoggedIn: state.Users.isLoggedIn
+})
+
+export default connect(mapStateToProps, mapDispatchToProps)(withRouter(SingleFilm))
diff --git a/client/src/index.css b/client/src/index.css
new file mode 100755
index 0000000..40e52d2
--- /dev/null
+++ b/client/src/index.css
@@ -0,0 +1,16 @@
+body {
+ margin: 0;
+ padding: 0;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
+ "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
+ sans-serif;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+ font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
+ monospace;
+}
+
+
diff --git a/client/src/index.js b/client/src/index.js
new file mode 100755
index 0000000..e9880a2
--- /dev/null
+++ b/client/src/index.js
@@ -0,0 +1,13 @@
+import React from 'react';
+import ReactDOM from 'react-dom';
+import './index.css';
+import App from './App';
+import * as serviceWorker from './serviceWorker';
+import 'bootstrap/dist/css/bootstrap.min.css';
+
+ReactDOM.render( , document.getElementById('root'));
+
+// If you want your app to work offline and load faster, you can change
+// unregister() to register() below. Note this comes with some pitfalls.
+// Learn more about service workers: http://bit.ly/CRA-PWA
+serviceWorker.unregister();
diff --git a/client/src/logo.svg b/client/src/logo.svg
new file mode 100755
index 0000000..6b60c10
--- /dev/null
+++ b/client/src/logo.svg
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/client/src/serviceWorker.js b/client/src/serviceWorker.js
new file mode 100755
index 0000000..2283ff9
--- /dev/null
+++ b/client/src/serviceWorker.js
@@ -0,0 +1,135 @@
+// This optional code is used to register a service worker.
+// register() is not called by default.
+
+// This lets the app load faster on subsequent visits in production, and gives
+// it offline capabilities. However, it also means that developers (and users)
+// will only see deployed updates on subsequent visits to a page, after all the
+// existing tabs open on the page have been closed, since previously cached
+// resources are updated in the background.
+
+// To learn more about the benefits of this model and instructions on how to
+// opt-in, read http://bit.ly/CRA-PWA
+
+const isLocalhost = Boolean(
+ window.location.hostname === 'localhost' ||
+ // [::1] is the IPv6 localhost address.
+ window.location.hostname === '[::1]' ||
+ // 127.0.0.1/8 is considered localhost for IPv4.
+ window.location.hostname.match(
+ /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
+ )
+);
+
+export function register(config) {
+ if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
+ // The URL constructor is available in all browsers that support SW.
+ const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
+ if (publicUrl.origin !== window.location.origin) {
+ // Our service worker won't work if PUBLIC_URL is on a different origin
+ // from what our page is served on. This might happen if a CDN is used to
+ // serve assets; see https://github.com/facebook/create-react-app/issues/2374
+ return;
+ }
+
+ window.addEventListener('load', () => {
+ const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
+
+ if (isLocalhost) {
+ // This is running on localhost. Let's check if a service worker still exists or not.
+ checkValidServiceWorker(swUrl, config);
+
+ // Add some additional logging to localhost, pointing developers to the
+ // service worker/PWA documentation.
+ navigator.serviceWorker.ready.then(() => {
+ console.log(
+ 'This web app is being served cache-first by a service ' +
+ 'worker. To learn more, visit http://bit.ly/CRA-PWA'
+ );
+ });
+ } else {
+ // Is not localhost. Just register service worker
+ registerValidSW(swUrl, config);
+ }
+ });
+ }
+}
+
+function registerValidSW(swUrl, config) {
+ navigator.serviceWorker
+ .register(swUrl)
+ .then(registration => {
+ registration.onupdatefound = () => {
+ const installingWorker = registration.installing;
+ if (installingWorker == null) {
+ return;
+ }
+ installingWorker.onstatechange = () => {
+ if (installingWorker.state === 'installed') {
+ if (navigator.serviceWorker.controller) {
+ // At this point, the updated precached content has been fetched,
+ // but the previous service worker will still serve the older
+ // content until all client tabs are closed.
+ console.log(
+ 'New content is available and will be used when all ' +
+ 'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
+ );
+
+ // Execute callback
+ if (config && config.onUpdate) {
+ config.onUpdate(registration);
+ }
+ } else {
+ // At this point, everything has been precached.
+ // It's the perfect time to display a
+ // "Content is cached for offline use." message.
+ console.log('Content is cached for offline use.');
+
+ // Execute callback
+ if (config && config.onSuccess) {
+ config.onSuccess(registration);
+ }
+ }
+ }
+ };
+ };
+ })
+ .catch(error => {
+ console.error('Error during service worker registration:', error);
+ });
+}
+
+function checkValidServiceWorker(swUrl, config) {
+ // Check if the service worker can be found. If it can't reload the page.
+ fetch(swUrl)
+ .then(response => {
+ // Ensure service worker exists, and that we really are getting a JS file.
+ const contentType = response.headers.get('content-type');
+ if (
+ response.status === 404 ||
+ (contentType != null && contentType.indexOf('javascript') === -1)
+ ) {
+ // No service worker found. Probably a different app. Reload the page.
+ navigator.serviceWorker.ready.then(registration => {
+ registration.unregister().then(() => {
+ window.location.reload();
+ });
+ });
+ } else {
+ // Service worker found. Proceed as normal.
+ registerValidSW(swUrl, config);
+ }
+ })
+ .catch(() => {
+ console.log(
+ 'No internet connection found. App is running in offline mode.'
+ );
+ });
+}
+
+export function unregister() {
+ if ('serviceWorker' in navigator) {
+ navigator.serviceWorker.ready.then(registration => {
+ registration.unregister();
+ });
+ }
+}
diff --git a/client/src/store/actions/FilmsApiActions.js b/client/src/store/actions/FilmsApiActions.js
new file mode 100644
index 0000000..555df62
--- /dev/null
+++ b/client/src/store/actions/FilmsApiActions.js
@@ -0,0 +1,121 @@
+import axios from 'axios'
+
+const baseURL = "http://35.198.198.237"
+
+export function FetchAllFilms() {
+ return dispatch => {
+ dispatch({ type: 'GET_FILMS_LOADING' })
+ var films = []
+ axios
+ .get('https://ghibliapi.herokuapp.com/films')
+ .then(({ data }) => {
+ films = data.reverse()
+
+ var promises = []
+ data.forEach(film => {
+ promises.push(axios.get(`https://api.themoviedb.org/3/search/movie?api_key=54742c232ad56eb16eb9a776e0c431c2&language=id&query=${film.title}`))
+ })
+
+ return Promise.all(promises)
+ })
+ .then(res => {
+
+ res.forEach((film, index) => {
+ films[index].poster = 'http://image.tmdb.org/t/p/w500/' + film.data.results[0].poster_path;
+ })
+
+ dispatch({ type: 'GET_FILMS_SUCCESS', payload: films })
+
+ })
+ .catch(({ response }) => {
+ dispatch({ type: 'GET_FILMS_ERROR' })
+ })
+ }
+}
+
+export function FetchFilmById(filmId) {
+ return dispatch => {
+ dispatch({ type: 'GET_FILM_BY_ID_LOADING' })
+ var film
+
+ axios
+ .get(`https://ghibliapi.herokuapp.com/films/${filmId}`)
+ .then(({ data }) => {
+ film = data
+
+ return axios
+ .get(`https://api.themoviedb.org/3/search/movie?api_key=54742c232ad56eb16eb9a776e0c431c2&language=id&query=${data.title}`)
+
+ })
+ .then(res => {
+ film.poster = 'http://image.tmdb.org/t/p/w500/' + res.data.results[0].poster_path;
+
+ return axios
+ .get(`${baseURL}/trailer/${film.title}`)
+
+ })
+ .then(({ data }) => {
+ film.trailer = data.data
+ dispatch({ type: 'GET_FILM_BY_ID_SUCCESS', payload: film })
+ })
+ .catch(() => {
+ dispatch({ type: 'GET_FILM_BY_ID_ERROR' })
+ })
+ }
+}
+
+export function AddToWatchList(movie) {
+ return dispatch => {
+ axios
+ .put(`${baseURL}/addToWatchlist`, {movie}, {
+ headers: {
+ token: localStorage.getItem('token')
+ }
+ })
+ .then(({ data }) => {
+ dispatch({ type: 'ADD_TO_WATCHLIST_SUCCESS', payload: movie })
+ })
+ .catch(({ response }) => {
+ console.error(response)
+ dispatch({ type: 'ADD_TO_WATCHLIST_ERROR' })
+ })
+ }
+}
+
+export function RemoveFromWatchList(movie){
+ return dispatch => {
+ axios
+ .put(`${baseURL}/removeFromWatchlist/${movie.id}`, {}, {
+ headers: {
+ token: localStorage.getItem('token')
+ }
+ })
+ .then(({data}) => {
+
+ dispatch({ type: 'REMOVE_FROM_WATCHLIST_SUCCESS', payload: data.data.WatchList })
+ })
+ .catch(({response}) => {
+ console.error(response)
+ })
+ }
+}
+
+export function GetWatchList(){
+ return dispatch => {
+ dispatch({type: 'GET_FILMS_LOADING'})
+ axios
+ .get(`${baseURL}/user`, {
+ headers: {
+ token: localStorage.getItem('token')
+ }
+ })
+ .then(({data}) => {
+ dispatch({type: 'GET_WATCHLIST_SUCCESS', payload: data.data.WatchList})
+ })
+ .catch(({response}) => {
+ console.error(response)
+ })
+ }
+}
+
+
diff --git a/client/src/store/actions/UsersAction.js b/client/src/store/actions/UsersAction.js
new file mode 100644
index 0000000..4b01569
--- /dev/null
+++ b/client/src/store/actions/UsersAction.js
@@ -0,0 +1,64 @@
+import axios from 'axios'
+
+const baseURL = 'http://35.198.198.237'
+
+export function register(user) {
+ return dispatch => {
+ axios
+ .post(`${baseURL}/register`, {
+ email: user.email,
+ password: user.password
+ })
+ .then(({ data }) => {
+ localStorage.setItem('token', data.token)
+ dispatch({ type: 'REGISTER_SUCCESS', payload: data.data.email })
+ })
+ .catch(({ response }) => {
+ console.error(response.data.err.errors)
+ response.data.err.errors ? dispatch({ type: 'REGISTER_ERROR', payload: response.data.err.errors }) : dispatch({ type: 'REGISTER_ERROR', payload: response.data.message })
+ })
+ }
+}
+
+export function login(user){
+ return dispatch => {
+ axios
+ .post(`${baseURL}/login`, {
+ email: user.email,
+ password: user.password
+ })
+ .then(({data}) => {
+ localStorage.setItem('token', data.token)
+ dispatch({type: 'LOGIN_SUCCESS', payload: data.data.email})
+ })
+ .catch(({response}) => {
+ console.error(response)
+ dispatch({type: 'LOGIN_ERROR', payload: {message: response.data.message}})
+ })
+ }
+}
+
+export function authenticateToken(){
+ return dispatch => {
+ axios
+ .get(`${baseURL}/authToken`, {
+ headers: {
+ token: localStorage.getItem('token')
+ }
+ })
+ .then(({data}) => {
+ dispatch({type: 'LOGIN_SUCCESS', payload: data.data})
+ })
+ .catch((err) => {
+ console.error(err)
+ dispatch({type: 'LOGIN_ERROR'})
+ })
+ }
+}
+
+export function logout() {
+ return dispatch => {
+ localStorage.removeItem('token')
+ dispatch({ type: 'LOGOUT' })
+ }
+}
\ No newline at end of file
diff --git a/client/src/store/index.js b/client/src/store/index.js
new file mode 100644
index 0000000..cdd7d08
--- /dev/null
+++ b/client/src/store/index.js
@@ -0,0 +1,15 @@
+import { createStore, combineReducers, applyMiddleware } from 'redux'
+import { composeWithDevTools } from 'redux-devtools-extension'
+import thunk from 'redux-thunk'
+
+//reducers
+import FilmsApi from './reducers/FilmsApi'
+import Users from './reducers/Users'
+
+const store = createStore(
+ combineReducers({FilmsApi, Users}),
+ composeWithDevTools(applyMiddleware(thunk))
+)
+
+export default store
+
diff --git a/client/src/store/reducers/FilmsApi.js b/client/src/store/reducers/FilmsApi.js
new file mode 100644
index 0000000..6e21c6c
--- /dev/null
+++ b/client/src/store/reducers/FilmsApi.js
@@ -0,0 +1,42 @@
+const defaultState = {
+ allFilms: [],
+ watchList: [],
+ film: '',
+ hasErrored: false,
+ isLoading: false
+}
+
+export default function (state = defaultState, action) {
+ const { type, payload } = action
+
+ switch (type) {
+ case 'GET_FILMS_SUCCESS':
+ return { ...state, allFilms: payload, isLoading: false }
+ case 'GET_FILMS_ERROR':
+ return { ...state, hasErrored: true, isLoading: false }
+ case 'GET_FILMS_LOADING':
+ return { ...state, isLoading: true }
+
+ case "GET_FILM_BY_ID_SUCCESS":
+ return { ...state, film: payload, isLoading: false }
+ case 'GET_FILM_BY_ID_ERROR':
+ return { ...state, hasErrored: true, isLoading: false }
+ case 'GET_FILM_BY_ID_LOADING':
+ return { ...state, isLoading: true }
+
+ case 'ADD_TO_WATCHLIST_SUCCESS':
+ return {...state, watchList: state.watchList.concat(payload)}
+ case 'ADD_TO_WATCHLIST_ERROR':
+ return {...state, hasErrored:true}
+
+ case 'GET_WATCHLIST_SUCCESS':
+ return {...state, watchList: payload }
+ case 'GET_WATCHLIST_ERROR':
+ return{...state, hasErrored:true}
+
+ case 'REMOVE_FROM_WATCHLIST_SUCCESS':
+ return {...state, watchList: payload}
+ default:
+ return state
+ }
+}
\ No newline at end of file
diff --git a/client/src/store/reducers/Users.js b/client/src/store/reducers/Users.js
new file mode 100644
index 0000000..29b6a2e
--- /dev/null
+++ b/client/src/store/reducers/Users.js
@@ -0,0 +1,27 @@
+const defaultState = {
+ isLoggedIn : false,
+ email: '',
+ errors: {}
+}
+
+export default function (state = defaultState, action){
+ const { type, payload } = action
+
+ switch (type) {
+ case 'REGISTER_SUCCESS':
+ return {...state, email: payload.email, isLoggedIn:true, errors: {}}
+ case 'REGISTER_ERROR':
+ return {...state, errors: payload}
+ case 'LOGIN_SUCCESS':
+ return {...state, email: payload.email, isLoggedIn: true, errors: {}}
+ case 'LOGIN_ERROR':
+ return {...state, errors: payload}
+ case 'AUTH_ERROR':
+ return {...state, errors: 'auth token fail', isLoggedIn: false}
+ case 'LOGOUT':
+ return {...state, isLoggedIn: false}
+ default:
+ return state
+ }
+}
+
diff --git a/server/.env-template b/server/.env-template
new file mode 100644
index 0000000..1541de4
--- /dev/null
+++ b/server/.env-template
@@ -0,0 +1 @@
+JWT_SECRET=aditsecret
\ No newline at end of file
diff --git a/server/.gitignore b/server/.gitignore
new file mode 100644
index 0000000..7074700
--- /dev/null
+++ b/server/.gitignore
@@ -0,0 +1,3 @@
+node_modules
+.env
+film-seed.txt
\ No newline at end of file
diff --git a/server/app.js b/server/app.js
new file mode 100644
index 0000000..638a710
--- /dev/null
+++ b/server/app.js
@@ -0,0 +1,18 @@
+require('dotenv').config()
+const express = require('express')
+const app = express()
+const port = process.env.PORT || 3001
+const mongoose = require('mongoose')
+const cors = require('cors')
+const indexRoute = require('./routes/index')
+
+app.use(express.json())
+app.use(express.urlencoded({extended: false}))
+app.use(cors())
+app.use('/', indexRoute)
+
+mongoose.connect('mongodb+srv://AdityaRespati:office2office2@mini-overflow-l1mdr.gcp.mongodb.net/test?retryWrites=true', {useNewUrlParser: true})
+
+app.listen(port, () => {
+ console.log('listening on port', port)
+})
diff --git a/server/controllers/TrailerController.js b/server/controllers/TrailerController.js
new file mode 100644
index 0000000..455380c
--- /dev/null
+++ b/server/controllers/TrailerController.js
@@ -0,0 +1,35 @@
+const movieTrailer = require('movie-trailer');
+
+class TrailerController {
+ static findByName(req, res) {
+ var movieName = req.params.movie
+
+ function getId(url) {
+ var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
+ var match = url.match(regExp);
+
+ if (match && match[2].length == 11) {
+ return match[2];
+ } else {
+ return 'error';
+ }
+ }
+
+ movieTrailer(movieName)
+ .then((response) => {
+ var videoId = getId(response);
+ var embed = "http://www.youtube.com/embed/" + videoId + ""
+ res
+ .status(200)
+ .json({
+ msg: "fetch success",
+ data: embed
+ })
+ })
+ .catch(err => {
+ console.log(err)
+ })
+ }
+}
+
+module.exports = TrailerController
\ No newline at end of file
diff --git a/server/controllers/UserController.js b/server/controllers/UserController.js
new file mode 100644
index 0000000..442d5a3
--- /dev/null
+++ b/server/controllers/UserController.js
@@ -0,0 +1,169 @@
+const { comparePW } = require('../helpers/bcrypt')
+const { jwtSign } = require('../helpers/jwt')
+const User = require('../models/User')
+
+class UserController {
+ static register(req, res, next) {
+ var payload
+
+ User
+ .create({
+ email: req.body.email,
+ password: req.body.password,
+ source: 'manual'
+ })
+ .then(user => {
+ payload = {
+ _id: user._id,
+ email: user.email,
+ }
+
+ res
+ .status(201)
+ .json({
+ msg: "registration success",
+ data: payload,
+ token: jwtSign(payload),
+ })
+
+ })
+ .catch(err => {
+ res
+ .status(400)
+ .json({
+ message: "registration fail",
+ err
+ })
+ })
+ }
+
+ static login(req, res) {
+ User
+ .findOne({
+ email: req.body.email
+ })
+ .then(user => {
+ if (user) {
+ if (comparePW(req.body.password, user.password)) {
+ var userInfo = {
+ _id: user._id,
+ email: user.email
+ }
+
+ res
+ .status(200)
+ .json({
+ message: "sign in success",
+ data: userInfo,
+ token: jwtSign(userInfo)
+ })
+ } else {
+ res
+ .status(404)
+ .json({
+ message: "email/password not found"
+ })
+ }
+ } else {
+ res
+ .status(404)
+ .json({
+ message: "email not registered"
+ })
+ }
+ })
+ .catch(err => {
+ res
+ .status(400)
+ .json({
+ message: "Login failed",
+ err
+ })
+ })
+ }
+
+ static findById(req, res) {
+ User
+ .findById(req.user.id)
+ .then(user => {
+ res
+ .status(200)
+ .json({
+ msg: 'feth success',
+ data: user
+ })
+ })
+ .catch(err => {
+ res
+ .status(400)
+ .json({
+ msg: 'fetch fail',
+ err
+ })
+ })
+ }
+
+ static addToWatchList(req, res) {
+ User
+ .findById(req.user.id)
+ .then(user => {
+ user.WatchList.push(req.body.movie)
+ user.hookEnabled = false
+ return user.save({ validateBeforeSave: false })
+ })
+ .then(updatedUser => {
+ res
+ .status(200)
+ .json({
+ msg: 'add to watchlists success',
+ data: updatedUser
+ })
+ })
+ .catch(err => {
+ res
+ .status(400)
+ .json({
+ msg: 'Add to watchlist fail',
+ err
+ })
+ })
+
+ }
+
+ static removeFromWatchList(req, res) {
+ User
+ .findById(req.user.id)
+ .then(user => {
+ user.WatchList = user.WatchList.filter(film => film.id !== req.params.movieId)
+ user.hookEnabled = false
+ return user.save({ validateBeforeSave: false })
+ })
+ .then(updatedUser => {
+ res
+ .status(200)
+ .json({
+ msg: 'remove from watchlists success',
+ data: updatedUser
+ })
+ })
+ .catch(err => {
+ res
+ .status(400)
+ .json({
+ msg: 'remove from watchlist fail',
+ err
+ })
+ })
+ }
+
+ static authToken(req, res) {
+ res
+ .status(200)
+ .json({
+ msg: 'auth token success',
+ data: req.user.email
+ })
+ }
+}
+
+module.exports = UserController
\ No newline at end of file
diff --git a/server/helpers/bcrypt.js b/server/helpers/bcrypt.js
new file mode 100644
index 0000000..fdae98f
--- /dev/null
+++ b/server/helpers/bcrypt.js
@@ -0,0 +1,14 @@
+const bcrypt = require('bcryptjs')
+
+function comparePW(inputPassword, userPassword){
+ return bcrypt.compareSync(inputPassword, userPassword)
+}
+
+function hashPW(user){
+ var salt = bcrypt.genSaltSync(6)
+ var hash = bcrypt.hashSync(user.password, salt)
+
+ return hash
+}
+
+module.exports = {comparePW, hashPW}
\ No newline at end of file
diff --git a/server/helpers/jwt.js b/server/helpers/jwt.js
new file mode 100644
index 0000000..92d457a
--- /dev/null
+++ b/server/helpers/jwt.js
@@ -0,0 +1,12 @@
+require('dotenv').config()
+const jwt = require('jsonwebtoken')
+
+function jwtSign(payload) {
+ return jwt.sign(payload, process.env.JWT_SECRET)
+}
+
+function jwtVerify(token) {
+ return jwt.verify(token, process.env.JWT_SECRET)
+}
+
+module.exports = { jwtSign, jwtVerify }
\ No newline at end of file
diff --git a/server/middlewares/isLogin.js b/server/middlewares/isLogin.js
new file mode 100644
index 0000000..346db0c
--- /dev/null
+++ b/server/middlewares/isLogin.js
@@ -0,0 +1,40 @@
+const User = require('../models/User')
+const {jwtVerify} = require('../helpers/jwt')
+
+module.exports = (req, res, next) => {
+ try {
+ let token = req.headers.token
+
+ if (token) {
+ let decoded = jwtVerify(token)
+
+ User
+ .findOne({ email: decoded.email })
+ .then(user => {
+ if (user) {
+ req.user = user
+ next()
+ } else {
+ res
+ .status(400)
+ .json({
+ msg: "wrong username/password",
+ decoded
+ })
+ }
+ })
+ } else {
+ res
+ .status(400)
+ .json({ msg: "invalid token" })
+ }
+
+ } catch (error) {
+ res
+ .status(400)
+ .json({
+ msg: "bad request (on middleware)",
+ error
+ })
+ }
+ }
\ No newline at end of file
diff --git a/server/middlewares/isOwner.js b/server/middlewares/isOwner.js
new file mode 100644
index 0000000..e69de29
diff --git a/server/models/User.js b/server/models/User.js
new file mode 100644
index 0000000..1423c4a
--- /dev/null
+++ b/server/models/User.js
@@ -0,0 +1,76 @@
+const mongoose = require('mongoose')
+const Schema = mongoose.Schema
+const { hashPW } = require('../helpers/bcrypt')
+
+const UserSchema = new Schema({
+ email: {
+ type: String,
+ required: [true, 'email cant be empty'],
+ validate: [
+ {
+ validator: function (value) {
+ return /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/.test(value)
+ },
+ msg: "invalid email format"
+ },
+ {
+ isAsync: true,
+ validator: (value, callback) => {
+ User
+ .findOne({
+ email: value
+ })
+ .then(user => {
+
+ if (user) {
+ callback(false)
+ } else {
+ callback(true)
+ }
+ })
+ .catch(err => {
+ console.log(err)
+ })
+ },
+ message: "this email is taken. please use another email."
+ }
+ ]
+ },
+ password: {
+ type: String,
+ required: [true, 'password cant be empty'],
+ minlength: [6, "password must be at least 6 character long"]
+ },
+ source: {
+ type: String,
+ default: 'manual'
+ },
+ WatchList: [{
+ id: String,
+ title: String,
+ description: String,
+ director: String,
+ producer: String,
+ release_date: String,
+ rt_score: String,
+ poster: String
+ }],
+ hookEnabled: {
+ type: Boolean,
+ default: true
+ }
+})
+
+UserSchema.pre('save', function (next) {
+ self = this
+ if(self.hookEnabled){
+ this.password = hashPW(this)
+ next()
+ } else{
+ next()
+ }
+})
+
+const User = mongoose.model('User', UserSchema)
+
+module.exports = User
\ No newline at end of file
diff --git a/server/package.json b/server/package.json
new file mode 100644
index 0000000..ea71a94
--- /dev/null
+++ b/server/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "server",
+ "version": "1.0.0",
+ "description": "",
+ "main": "index.js",
+ "scripts": {
+ "start": "nodemon app.js",
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "dependencies": {
+ "axios": "^0.18.0",
+ "bcryptjs": "^2.4.3",
+ "cors": "^2.8.5",
+ "dotenv": "^6.2.0",
+ "express": "^4.16.4",
+ "jsonwebtoken": "^8.5.0",
+ "mongoose": "^5.4.17",
+ "movie-trailer": "^2.0.3"
+ }
+}
diff --git a/server/routes/index.js b/server/routes/index.js
new file mode 100644
index 0000000..a90ea3c
--- /dev/null
+++ b/server/routes/index.js
@@ -0,0 +1,19 @@
+const express = require('express')
+const router = express.Router()
+const UserController = require('../controllers/UserController')
+const TrailerController = require('../controllers/TrailerController')
+const isLogin = require('../middlewares/isLogin')
+
+router.get('/', (req, res) => {
+ res.send('success get basic route')
+})
+
+router.post('/register', UserController.register)
+router.post('/login', UserController.login)
+router.get('/user', isLogin, UserController.findById)
+router.get('/authToken', isLogin, UserController.authToken)
+router.get('/trailer/:movie', TrailerController.findByName)
+router.put('/addToWatchlist', isLogin, UserController.addToWatchList)
+router.put('/removeFromWatchlist/:movieId', isLogin, UserController.removeFromWatchList)
+
+module.exports = router
\ No newline at end of file