Skip to content

Commit

Permalink
Chapter11 and 12/mern-mediastream
Browse files Browse the repository at this point in the history
  • Loading branch information
shamahoque committed Apr 14, 2020
1 parent 9c6f0a8 commit 4f3e16d
Show file tree
Hide file tree
Showing 51 changed files with 8,774 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Chapter11 and 12/mern-mediastream/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"presets": [
["@babel/preset-env",
{
"targets": {
"node": "current"
}
}
],
"@babel/preset-react"
],
"plugins": [
"react-hot-loader/babel"
]
}
4 changes: 4 additions & 0 deletions Chapter11 and 12/mern-mediastream/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/node_modules/
/dist/
/data/
npm-debug.log
21 changes: 21 additions & 0 deletions Chapter11 and 12/mern-mediastream/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Shama Hoque

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
18 changes: 18 additions & 0 deletions Chapter11 and 12/mern-mediastream/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# MERN Mediastream

A media streaming application with media upload and stream features - developed using React, Node, Express and MongoDB.

### [Live Demo](http://mediastream2.mernbook.com/ "MERN Mediastream")

#### What you need to run this code
1. Node (13.12.0)
2. NPM (6.14.4)
3. MongoDB (4.2.0)

#### How to run this code
1. Clone this repository
2. Open command line in the cloned folder,
- To install dependencies, run ``` npm install ``` or ``` yarn ```
- To run the application for development, run ``` npm run development ``` or ``` yarn development ```
4. Open [localhost:3000](http://localhost:3000/) in the browser
----
23 changes: 23 additions & 0 deletions Chapter11 and 12/mern-mediastream/client/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react'
import MainRouter from './MainRouter'
import {BrowserRouter} from 'react-router-dom'
import { ThemeProvider } from '@material-ui/styles'
import theme from './theme'
import { hot } from 'react-hot-loader'

const App = () => {
React.useEffect(() => {
const jssStyles = document.querySelector('#jss-server-side')
if (jssStyles) {
jssStyles.parentNode.removeChild(jssStyles)
}
}, [])
return (
<BrowserRouter>
<ThemeProvider theme={theme}>
<MainRouter/>
</ThemeProvider>
</BrowserRouter>
)}

export default hot(module)(App)
35 changes: 35 additions & 0 deletions Chapter11 and 12/mern-mediastream/client/MainRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React, {Component} from 'react'
import {Route, Switch} from 'react-router-dom'
import Home from './core/Home'
import Users from './user/Users'
import Signup from './user/Signup'
import Signin from './auth/Signin'
import EditProfile from './user/EditProfile'
import Profile from './user/Profile'
import PrivateRoute from './auth/PrivateRoute'
import Menu from './core/Menu'
import NewMedia from './media/NewMedia'
import PlayMedia from './media/PlayMedia'
import EditMedia from './media/EditMedia'

const MainRouter = ({data}) => {
return (<div>
<Menu/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/users" component={Users}/>
<Route path="/signup" component={Signup}/>
<Route path="/signin" component={Signin}/>
<PrivateRoute path="/user/edit/:userId" component={EditProfile}/>
<Route path="/user/:userId" component={Profile}/>

<PrivateRoute path="/media/new" component={NewMedia}/>
<PrivateRoute path="/media/edit/:mediaId" component={EditMedia}/>
<Route path="/media/:mediaId" render={(props) => (
<PlayMedia {...props} data={data} />
)} />
</Switch>
</div>)
}

export default MainRouter
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions Chapter11 and 12/mern-mediastream/client/auth/PrivateRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React, { Component } from 'react'
import { Route, Redirect } from 'react-router-dom'
import auth from './auth-helper'

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
auth.isAuthenticated() ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/signin',
state: { from: props.location }
}}/>
)
)}/>
)

export default PrivateRoute
100 changes: 100 additions & 0 deletions Chapter11 and 12/mern-mediastream/client/auth/Signin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import React, {useState} from 'react'
import Card from '@material-ui/core/Card'
import CardActions from '@material-ui/core/CardActions'
import CardContent from '@material-ui/core/CardContent'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
import Typography from '@material-ui/core/Typography'
import Icon from '@material-ui/core/Icon'
import { makeStyles } from '@material-ui/core/styles'
import auth from './../auth/auth-helper'
import {Redirect} from 'react-router-dom'
import {signin} from './api-auth.js'

const useStyles = makeStyles(theme => ({
card: {
maxWidth: 600,
margin: 'auto',
textAlign: 'center',
marginTop: theme.spacing(5),
paddingBottom: theme.spacing(2)
},
error: {
verticalAlign: 'middle'
},
title: {
marginTop: theme.spacing(2),
color: theme.palette.openTitle
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 300
},
submit: {
margin: 'auto',
marginBottom: theme.spacing(2)
}
}))

export default function Signin(props) {
const classes = useStyles()
const [values, setValues] = useState({
email: '',
password: '',
error: '',
redirectToReferrer: false
})

const clickSubmit = () => {
const user = {
email: values.email || undefined,
password: values.password || undefined
}

signin(user).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error})
} else {
auth.authenticate(data, () => {
setValues({ ...values, error: '',redirectToReferrer: true})
})
}
})
}

const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value })
}

const {from} = props.location.state || {
from: {
pathname: '/'
}
}
const {redirectToReferrer} = values
if (redirectToReferrer) {
return (<Redirect to={from}/>)
}

return (
<Card className={classes.card}>
<CardContent>
<Typography variant="h6" className={classes.title}>
Sign In
</Typography>
<TextField id="email" type="email" label="Email" className={classes.textField} value={values.email} onChange={handleChange('email')} margin="normal"/><br/>
<TextField id="password" type="password" label="Password" className={classes.textField} value={values.password} onChange={handleChange('password')} margin="normal"/>
<br/> {
values.error && (<Typography component="p" color="error">
<Icon color="error" className={classes.error}>error</Icon>
{values.error}
</Typography>)
}
</CardContent>
<CardActions>
<Button color="primary" variant="contained" onClick={clickSubmit} className={classes.submit}>Submit</Button>
</CardActions>
</Card>
)
}
30 changes: 30 additions & 0 deletions Chapter11 and 12/mern-mediastream/client/auth/api-auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const signin = async (user) => {
try {
let response = await fetch('/auth/signin/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify(user)
})
return await response.json()
} catch(err) {
console.log(err)
}
}

const signout = async () => {
try {
let response = await fetch('/auth/signout/', { method: 'GET' })
return await response.json()
} catch(err) {
console.log(err)
}
}

export {
signin,
signout
}
29 changes: 29 additions & 0 deletions Chapter11 and 12/mern-mediastream/client/auth/auth-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { signout } from './api-auth.js'

const auth = {
isAuthenticated() {
if (typeof window == "undefined")
return false

if (sessionStorage.getItem('jwt'))
return JSON.parse(sessionStorage.getItem('jwt'))
else
return false
},
authenticate(jwt, cb) {
if (typeof window !== "undefined")
sessionStorage.setItem('jwt', JSON.stringify(jwt))
cb()
},
clearJWT(cb) {
if (typeof window !== "undefined")
sessionStorage.removeItem('jwt')
cb()
//optional
signout().then((data) => {
document.cookie = "t=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"
})
}
}

export default auth
48 changes: 48 additions & 0 deletions Chapter11 and 12/mern-mediastream/client/core/Home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import React, {useState, useEffect} from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Card from '@material-ui/core/Card'
import Typography from '@material-ui/core/Typography'
import MediaList from '../media/MediaList'
import {listPopular} from '../media/api-media.js'

const useStyles = makeStyles(theme => ({
card: {
margin: `${theme.spacing(5)}px 30px`
},
title: {
padding:`${theme.spacing(3)}px ${theme.spacing(2.5)}px 0px`,
color: theme.palette.text.secondary,
fontSize: '1em'
},
media: {
minHeight: 330
}
}))

export default function Home(){
const classes = useStyles()
const [media, setMedia] = useState([])

useEffect(() => {
const abortController = new AbortController()
const signal = abortController.signal
listPopular(signal).then((data) => {
if (data.error) {
console.log(data.error)
} else {
setMedia(data)
}
})
return function cleanup(){
abortController.abort()
}
}, [])
return (
<Card className={classes.card}>
<Typography variant="h2" className={classes.title}>
Popular Videos
</Typography>
<MediaList media={media}/>
</Card>
)
}
Loading

0 comments on commit 4f3e16d

Please sign in to comment.