Commit 84df3758 authored by kavinduchamiran's avatar kavinduchamiran

initial commit

parents
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/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*
/public/env-config.js
env-config.js
\ No newline at end of file
CLOUDL_SERVER=localhost
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/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*
/public/env-config.js
env-config.js
\ No newline at end of file
stages:
- build
- deploy
variables:
CONTAINER_IMAGE: kavinduchamiran/${CI_COMMIT_REF_NAME}:${CI_COMMIT_SHORT_SHA}
docker_build:
image: docker:stable
services:
- docker:dind
stage: build
only:
- cloudl-server
- cloudl-client
script:
- docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
- docker build -t ${CONTAINER_IMAGE} .
- docker tag ${CONTAINER_IMAGE} kavinduchamiran/${CI_COMMIT_REF_NAME}:latest
- docker push ${CONTAINER_IMAGE}
kube_deploy:
image: lwolf/kubectl_deployer:latest
stage: deploy
only:
- cloudl-server
- cloudl-client
script:
- kubectl config set-cluster cloudl --server="${KUBE_URL}" --certificate-authority="${KUBE_CA_PEM}"
- kubectl config set-credentials admin --username="${KUBE_USERNAME}" --password="${KUBE_PASSWORD}"
- kubectl config set-context default --cluster=cloudl --user=${KUBE_USERNAME}
- kubectl config use-context default
- kubectl apply -f k8s/cloudl-client-deployment.yml
# - kubectl set image deployment/${CI_COMMIT_REF_NAME}-deployment ${CI_COMMIT_REF_NAME}=kavinduchamiran/${CI_COMMIT_REF_NAME}:latest
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with NO BOM" />
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="JSX" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/cloudl.iml" filepath="$PROJECT_DIR$/.idea/cloudl.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/cloudl-client.iml" filepath="$PROJECT_DIR$/.idea/cloudl-client.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
This diff is collapsed.
# => Build container
FROM node:10 as build
WORKDIR /cloudl-client
COPY package.json /cloudl-client/package.json
RUN npm install
RUN npm install react-scripts -g
COPY . /cloudl-client
RUN npm run build
# => Run container
FROM nginx:1.16.0
COPY --from=build /cloudl-client/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80
# Start Nginx server
CMD ["nginx -g \"daemon off;\""]
\ No newline at end of file
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.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br>
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br>
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.<br>
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.<br>
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
This diff is collapsed.
This diff is collapsed.
apiVersion: apps/v1
kind: Deployment
metadata:
name: cloudl-client-deployment
spec:
replicas: 1
template:
metadata:
labels:
app: cloudl-client
spec:
containers:
- name: cloudl-client
image: kavinduchamiran/cloudl-client:v1
ports:
- containerPort: 80
name: http-port
selector:
matchLabels:
app: cloudl-client
\ No newline at end of file
apiVersion: v1
kind: Service
metadata:
name: cloudl-client-service
spec:
ports:
- port: 80
protocol: TCP
targetPort: http-port
selector:
app: cloudl-client
type: LoadBalancer
\ No newline at end of file
server {
listen 80;
location /socket/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_pass http://cloudl-server-service:5000/;
}
location /api/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_pass http://cloudl-server-service:5000/;
}
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html {
root /usr/share/nginx/html;
}
}
\ No newline at end of file
This diff is collapsed.
{
"name": "cloudl",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.3.3",
"axios": "^0.19.0",
"classnames": "^2.2.6",
"is-empty": "^1.2.0",
"jwt-decode": "^2.2.0",
"material-table": "^1.50.0",
"mongoose": "^5.6.10",
"react": "^16.9.0",
"react-bootstrap": "^0.32.4",
"react-dom": "^16.9.0",
"react-file-drop": "^0.2.8",
"react-redux": "^7.1.0",
"react-router-bootstrap": "^0.25.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.1.1",
"redux": "^4.0.4",
"redux-thunk": "^2.3.0",
"socket.io-client": "^2.2.0"
},
"scripts": {
"start": "chmod +x ./env.sh && ./env.sh && cp env-config.js ./public/ && react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"proxy": "http://localhost:5000"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="%PUBLIC_URL%/env-config.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>ClouDL - Online file and torrent downloader</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
# https://www.robotstxt.org/robotstxt.html
User-agent: *
.App {
margin-top: 15px;
}
.App .navbar-brand {
font-weight: bold;
}
\ No newline at end of file
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import jwt_decode from "jwt-decode";
import setAuthToken from "./utils/setAuthToken";
import { setCurrentUser, logoutUser } from "./actions/authActions";
import { Provider } from "react-redux";
import store from "./store";
import NavBar from "./containers/NavBar";
import Home from "./containers/Home";
import Register from "./containers/Register";
import Login from "./containers/Login";
import PrivateRoute from "./utils/PrivateRoute";
import Dashboard from "./containers/Dashboard";
import Jobs from "./containers/Jobs";
// Check for token to keep user logged in
if (localStorage.jwtToken) {
// Set auth token header auth
const token = localStorage.jwtToken;
setAuthToken(token);
// Decode token and get user info and exp
const decoded = jwt_decode(token);
// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
// Check for expired token
const currentTime = Date.now() / 1000; // to get in milliseconds
if (decoded.exp < currentTime) {
// Logout user
store.dispatch(logoutUser());
// Redirect to login
window.location.href = "./login";
}
}
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div className="App">
<NavBar />
<Route exact path="/" component={Home} />
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<Switch>
<PrivateRoute exact path="/dashboard" component={Dashboard} />
<PrivateRoute exact path="/jobs" component={Jobs} />
</Switch>
</div>
</Router>
</Provider>
);
}
}
export default App;
\ No newline at end of file
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
import axios from "axios";
import setAuthToken from "../utils/setAuthToken";
import jwt_decode from "jwt-decode";
import {
GET_ERRORS,
SET_CURRENT_USER,
USER_LOADING
} from "./types";
// Register User
export const registerUser = (userData, history) => dispatch => {
axios
.post("/api/users/register", userData)
.then(res => history.push("/login")) // re-direct to login on successful register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
// Login - get user token
export const loginUser = userData => dispatch => {
axios
.post("/api/users/login", userData)
.then(res => {
// Save to localStorage
// Set token to localStorage
const { token } = res.data;
localStorage.setItem("jwtToken", token);
// Set token to Auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
// Set logged in user
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded
};
};
// User loading
export const setUserLoading = () => {
return {
type: USER_LOADING
};
};
// Log user out
export const logoutUser = () => dispatch => {
// Remove token from local storage
localStorage.removeItem("jwtToken");
// Remove auth header for future requests
setAuthToken(false);
// Set current user to empty object {} which will set isAuthenticated to false
dispatch(setCurrentUser({}));
};
import socket from '../utils/webSocket.js'
import {
GET_ERRORS,
} from "./types";
export const addNewJob = (jobData, history) => dispatch => {
socket.emit('newJob', jobData);
socket.on('err', err => {
dispatch({
type: GET_ERRORS,
payload: err
})
});
socket.on('job_add_success', () => history.push('/jobs'));
};
\ No newline at end of file
export const GET_ERRORS = "GET_ERRORS";
export const USER_LOADING = "USER_LOADING";
export const SET_CURRENT_USER = "SET_CURRENT_USER";
\ No newline at end of file
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { logoutUser } from "../actions/authActions";
import { addNewJob } from "../actions/jobActions";
// import {DragDrop} from './DragDrop';
// import FileDrop from 'react-file-drop';
import classnames from "classnames";
import socket from '../utils/webSocket.js'
class Dashboard extends Component {
constructor() {
super();
this.state = {
link: "",
errors: {}
};
}
// handleDrop = (files, event) => {
// console.log(files, event);
// };
onLogoutClick = e => {
e.preventDefault();
this.props.logoutUser();
};
onMyJobsClick = e => {
e.preventDefault();
this.props.history.push("/jobs");
};
onDownloadClick = e => {
e.preventDefault();
const jobData = {
id: this.props.auth.user.id,
link: this.state.link
};
this.props.addNewJob(jobData, this.props.history);
};
onChange = e => {
this.setState({ [e.target.id]: e.target.value , errors: {}});
};
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({
errors: nextProps.errors
});
}
}
render() {
const { user } = this.props.auth;
const { errors } = this.state;
return (
<div style={{ height: "75vh" }} className="container valign-wrapper">
<div className="row">
<div className="row">
<div className="col l6 left-align">
<button
style={{
width: "150px",
borderRadius: "3px",
letterSpacing: "1.5px",
marginTop: "1rem",
bottom: '9rem'
}}
onClick={this.onMyJobsClick}
className="btn btn-large waves-effect waves-light hoverable blue accent-3"
>
My Jobs
</button>
</div>
<div className="col l6 right-align">
<button
style={{
width: "150px",
borderRadius: "3px",
letterSpacing: "1.5px",
marginTop: "1rem",
bottom: '9rem'
}}
onClick={this.onLogoutClick}
className="btn btn-large waves-effect waves-light hoverable red accent-3"
>
Logout
</button>
</div>
</div>
<div className="row">
<div className="col s12 center-align">
<h4>
<b>Hey there,</b> {user.name.split(" ")[0]}!
<p className="flow-text grey-text text-darken-1">
What do you need me to download today?
</p>
</h4>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.link}
error={errors.link}
id="link"
placeholder="paste your link here"
className={classnames("", {
invalid: errors.error
})}
/>
<span className="red-text">
{errors.error}
</span>
</div>
<button
style={{
width: "150px",
borderRadius: "3px",
letterSpacing: "1.5px",
marginTop: "1rem",
}}
onClick={this.onDownloadClick}
className="btn btn-large waves-effect waves-light hoverable green accent-3"
>
Download
</button>
</div>
</div>
</div>
</div>
);
}
componentDidMount() {
socket.on("connect", () => {
socket.emit("userId", {userId: this.props.auth.user.id})
});
}
}
Dashboard.propTypes = {
logoutUser: PropTypes.func.isRequired,
addNewJob: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
export default connect(
mapStateToProps,
{ logoutUser, addNewJob }
)(Dashboard);
\ No newline at end of file
import React, { Component } from 'react';
class DragAndDrop extends Component {
dropRef = React.createRef();
state = {
dragging: false
};
handleDrag = (e) => {
e.preventDefault()
e.stopPropagation()
}
handleDragIn = (e) => {
e.preventDefault()
e.stopPropagation()
this.dragCounter++
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
this.setState({dragging: true})
}
}
handleDragOut = (e) => {
e.preventDefault()
e.stopPropagation()
this.dragCounter--
if (this.dragCounter > 0) return
this.setState({dragging: false})
}
handleDrop = (e) => {
e.preventDefault()
e.stopPropagation()
this.setState({drag: false})
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
this.props.handleDrop(e.dataTransfer.files)
e.dataTransfer.clearData()
this.dragCounter = 0
}
}
componentDidMount() {
let div = this.dropRef.current;
div.addEventListener('dragenter', this.handleDragIn);
div.addEventListener('dragleave', this.handleDragOut);
div.addEventListener('dragover', this.handleDrag);
div.addEventListener('drop', this.handleDrop);
}
componentWillUnmount() {
let div = this.dropRef.current;
div.removeEventListener('dragenter', this.handleDragIn);
div.removeEventListener('dragleave', this.handleDragOut);
div.removeEventListener('dragover', this.handleDrag);
div.removeEventListener('drop', this.handleDrop);
}
render() {
return (
<div
style={{display: 'inline-block', position: 'relative'}}
ref={this.dropRef}
>
{this.state.dragging &&
<div
style={{
border: 'dashed grey 4px',
backgroundColor: 'rgba(255,255,255,.8)',
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
zIndex: 9999
}}
>
<div
style={{
position: 'absolute',
top: '50%',
right: 0,
left: 0,
textAlign: 'center',
color: 'grey',
fontSize: 36
}}
>
<div>drop here :)</div>
</div>
</div>
}
{this.props.children}
</div>
)
}
}
export default DragAndDrop;
.Home .lander {
padding: 80px 0;
text-align: center;
}
.Home .lander h1 {
font-family: "Open Sans", sans-serif;
font-weight: 600;
}
.Home .lander p {
color: #999;
}
\ No newline at end of file
import React, { Component } from "react";
import { Link } from "react-router-dom";
import {connect} from "react-redux";
class Home extends Component {
render() {
return (
<div style={{ height: "75vh" }} className="container valign-wrapper">
<div className="row">
<div className="col s12 center-align">
<h4>
The <b>online</b> file downloader
</h4>
<p className="flow-text grey-text text-darken-1">
Let me handle your slow downloads and torrents!
</p>
<br />
<div className="col s6">
<Link
to="/register"
style={{
width: "140px",
borderRadius: "3px",
letterSpacing: "1.5px"
}}
className="btn btn-large waves-effect waves-light hoverable blue accent-3"
>
Register
</Link>
</div>
<div className="col s6">
<Link
to="/login"
style={{
width: "140px",
borderRadius: "3px",
letterSpacing: "1.5px"
}}
className="btn btn-large btn-flat waves-effect light-green black-text"
>
Log In
</Link>
</div>
</div>
</div>
</div>
);
}
componentDidMount() {
// If logged in and user navigates to Login page, should redirect them to dashboard
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
}
// Home.propTypes = {
// loginUser: PropTypes.func.isRequired,
// auth: PropTypes.object.isRequired,
// errors: PropTypes.object.isRequired
// };
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
export default connect(
mapStateToProps
)(Home);
\ No newline at end of file
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import {Link} from "react-router-dom";
import { logoutUser } from "../actions/authActions";
import MaterialTable from "material-table";
import CircularProgress from '@material-ui/core/CircularProgress';
import socket from '../utils/webSocket.js'
import {Button, Dialog, DialogActions,DialogContent, DialogTitle, DialogContentText} from "@material-ui/core";
class Jobs extends Component {
constructor() {
super();
this.state = {
jobs: [],
showDelete: false
};
}
handleDeleteConfirm = () => {
socket.emit('deleteJob', this.state.deleteId);
this.setState({
showDelete: false,
deleteId: null,
deleteName: null,
deleteProgress: 0
})
};
handleDeleteCancel = () => {
this.setState({
showDelete: false,
deleteId: null,
deleteName: null,
deleteProgress: 0
})
};
changeData = () => socket.emit('initial data');
renderConfirm = () => {
return (
<Dialog open={this.state.showDelete} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description">
<DialogTitle id="alert-dialog-title">Delete this job?</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
{`Do you really want to delete the download '${this.state.deleteName}' ? It has already completed ${parseInt(this.state.deleteProgress)}%.`}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleDeleteCancel} color="primary">
Cancel
</Button>
<Button onClick={this.handleDeleteConfirm} color="primary">
Delete
</Button>
</DialogActions>
</Dialog>
);
};
render() {
return (
<div className="container">
{this.renderConfirm()}
<div style={{ marginTop: "4rem" }} className="row">
<div className="col s8 offset-s2">
<Link to="/" className="btn-flat waves-effect">
<i className="material-icons left">keyboard_backspace</i> Back to home
</Link>
</div>
</div>
<div style={{ marginTop: "4rem" }} className="row">
<MaterialTable
columns={[
{ title: "Date added", field: "date", type: 'datetime'},
{ title: "Name", field: "name", searchable: true, cellStyle: {height: '10px'}},
{ title: "Status", field: "status"},
{ title: "Download Speed", field: "download_speed", type: 'string'},
{ title: "Progress", field: "progress", render: rowData => rowData.progress ?
<CircularProgress variant="static" value={rowData.progress} />:
<CircularProgress variant="static" color={'secondary'} value={100} />
}
]}
data={this.state.jobs}
title="Your downloads"
actions={[
rowData => ({
icon: 'pause',
tooltip: 'Resume Job',
onClick: (event, rowData) => socket.emit('pauseJob', rowData.id),
hidden: rowData.status !== 'active'
}),
rowData => ({
icon: 'play_arrow',
tooltip: 'Resume Job',
onClick: (event, rowData) => socket.emit('resumeJob', rowData.id),
hidden: rowData.status !== 'paused'
}),
rowData => ({
icon: 'save_alt',
tooltip: 'Download',
onClick: (event, rowData) => socket.emit('downloadJob', rowData.id),
hidden: rowData.status !== 'complete' && rowData.status !== 'zipping' && rowData.status !== 'ready'
}),
{
icon: 'clear',
tooltip: 'Remove Job',
onClick: (event, rowData) => this.setState({
showDelete: true,
deleteId: rowData.id,
deleteName: rowData.name,
deleteProgress: rowData.progress
})
}
]}
/>
</div>
</div>
);
}
componentDidMount() {
this.fetchJob = setInterval(() => {
socket.emit('getJobs', {userId: this.props.auth.user.id});
}, 1000);
socket.on("get_jobs_res", data => this.setState({
jobs: data.map(e => {
// console.log(e);
return {
id: e.id,
date: new Date(e.date),
name: e.name,
status: e.progress < 100.00 ? e.status : 'complete',
download_speed: parseInt(e.download_speed / 1000) + ' KB/s',
progress: e.progress,
dir: e.dir,
}
})
}));
socket.on("download_ready", data => console.log(data));
}
componentWillUnmount() {
clearInterval(this.fetchJob);
socket.off('get_jobs_res');
socket.off('download_ready');
}
}
Jobs.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{ logoutUser }
)(Jobs);
\ No newline at end of file
@media all and (min-width: 480px) {
.Login {
padding: 60px 0;
}
.Login form {
margin: 0 auto;
max-width: 320px;
}
}
import React, { Component } from "react";
import { Link } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { loginUser } from "../actions/authActions";
import classnames from "classnames";
class Login extends Component {
constructor() {
super();
this.state = {
email: "",
password: "",
errors: {}
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.auth.isAuthenticated) {
this.props.history.push("/dashboard"); // push user to dashboard when they login
}
if (nextProps.errors) {
this.setState({
errors: nextProps.errors
});
}
}
onChange = e => {
this.setState({ [e.target.id]: e.target.value });
};
onSubmit = e => {
e.preventDefault();
const userData = {
email: this.state.email,
password: this.state.password
};
this.props.loginUser(userData); // since we handle the redirect within our component, we don't need to pass in this.props.history as a parameter
};
render() {
const { errors } = this.state;
return (
<div className="container">
<div style={{ marginTop: "4rem" }} className="row">
<div className="col s8 offset-s2">
<Link to="/" className="btn-flat waves-effect">
<i className="material-icons left">keyboard_backspace</i> Back to
home
</Link>
<div className="col s12" style={{ paddingLeft: "11.250px" }}>
<h4>
<b>Login</b> below
</h4>
<p className="grey-text text-darken-1">
Don't have an account? <Link to="/register">Register</Link>
</p>
</div>
<form noValidate onSubmit={this.onSubmit}>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.email}
error={errors.email}
id="email"
type="email"
className={classnames("", {
invalid: errors.email || errors.emailnotfound
})}
/>
<label htmlFor="email">Email</label>
<span className="red-text">
{errors.email}
{errors.emailnotfound}
</span>
</div>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.password}
error={errors.password}
id="password"
type="password"
className={classnames("", {
invalid: errors.password || errors.passwordincorrect
})}
/>
<label htmlFor="password">Password</label>
<span className="red-text">
{errors.password}
{errors.passwordincorrect}
</span>
</div>
<div className="col s12" style={{ paddingLeft: "11.250px" }}>
<button
style={{
width: "150px",
borderRadius: "3px",
letterSpacing: "1.5px",
marginTop: "1rem"
}}
type="submit"
className="btn btn-large waves-effect waves-light hoverable blue accent-3"
>
Login
</button>
</div>
</form>
</div>
</div>
</div>
);
}
componentDidMount() {
// If logged in and user navigates to Login page, should redirect them to dashboard
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
}
Login.propTypes = {
loginUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
export default connect(
mapStateToProps,
{ loginUser }
)(Login);
\ No newline at end of file
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Navbar extends Component {
render() {
return (
<div className="navbar-fixed">
<nav className="z-depth-0">
<div className="nav-wrapper white">
<Link
to="/"
style={{
fontFamily: "monospace"
}}
className="col s5 brand-logo center black-text"
>
<i className="material-icons">archive</i>
ClouDL
</Link>
</div>
</nav>
</div>
);
}
}
export default Navbar;
\ No newline at end of file
.NotFound {
padding-top: 100px;
text-align: center;
}
\ No newline at end of file
import React from "react";
import "./NotFound.css";
export default () =>
<div className="NotFound">
<h3>Sorry, page not found!</h3>
</div>;
\ No newline at end of file
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { registerUser } from "../actions/authActions";
import classnames from "classnames";
class Register extends Component {
constructor() {
super();
this.state = {
name: "",
email: "",
password: "",
password2: "",
errors: {}
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({
errors: nextProps.errors
});
}
}
onChange = e => {
this.setState({ [e.target.id]: e.target.value });
};
onSubmit = e => {
e.preventDefault();
const newUser = {
name: this.state.name,
email: this.state.email,
password: this.state.password,
password2: this.state.password2
};
this.props.registerUser(newUser, this.props.history);
};
render() {
const { errors } = this.state;
return (
<div className="container">
<div className="row">
<div className="col s8 offset-s2" style={{marginTop: '59px'}}>
<Link to="/" className="btn-flat waves-effect">
<i className="material-icons left">keyboard_backspace</i> Back to
home
</Link>
<div className="col s12" style={{ paddingLeft: "11.250px" }}>
<h4>
<b>Register</b> below
</h4>
<p className="grey-text text-darken-1">
Already have an account? <Link to="/login">Log in</Link>
</p>
</div>
<form noValidate onSubmit={this.onSubmit}>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.name}
error={errors.name}
id="name"
type="text"
className={classnames("", {
invalid: errors.name
})}
/>
<label htmlFor="name">Name</label>
<span className="red-text">{errors.name}</span>
</div>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.email}
error={errors.email}
id="email"
type="email"
className={classnames("", {
invalid: errors.email
})}
/>
<label htmlFor="email">Email</label>
<span className="red-text">{errors.email}</span>
</div>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.password}
error={errors.password}
id="password"
type="password"
className={classnames("", {
invalid: errors.password
})}
/>
<label htmlFor="password">Password</label>
<span className="red-text">{errors.password}</span>
</div>
<div className="input-field col s12">
<input
onChange={this.onChange}
value={this.state.password2}
error={errors.password2}
id="password2"
type="password"
className={classnames("", {
invalid: errors.password2
})}
/>
<label htmlFor="password2">Confirm Password</label>
<span className="red-text">{errors.password2}</span>
</div>
<div className="col s12" style={{ paddingLeft: "11.250px" }}>
<button
style={{
width: "150px",
borderRadius: "3px",
letterSpacing: "1.5px",
marginTop: "1rem"
}}
type="submit"
className="btn btn-large waves-effect waves-light hoverable blue accent-3"
>
Sign up
</button>
</div>
</form>
</div>
</div>
</div>
);
}
componentDidMount() {
// If logged in and user navigates to Register page, should redirect them to dashboard
if (this.props.auth.isAuthenticated) {
this.props.history.push("/dashboard");
}
}
}
Register.propTypes = {
registerUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth,
errors: state.errors
});
export default connect(
mapStateToProps,
{ registerUser }
)(withRouter(Register));
\ No newline at end of file
body {
margin: 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;
}
select.form-control,
textarea.form-control,
input.form-control {
font-size: 16px;
}
input[type=file] {
width: 100%;
}
\ No newline at end of file
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);
import {
SET_CURRENT_USER,
USER_LOADING
} from "../actions/types";
const isEmpty = require("is-empty");
const initialState = {
isAuthenticated: false,
user: {},
loading: false
};
export default function(state = initialState, action) {
switch (action.type) {
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: !isEmpty(action.payload),
user: action.payload
};
case USER_LOADING:
return {
...state,
loading: true
};
default:
return state;
}
}
\ No newline at end of file
import { GET_ERRORS } from "../actions/types";
const initialState = {};
export default function(state = initialState, action) {
switch (action.type) {
case GET_ERRORS:
return action.payload;
default:
return state;
}
}
\ No newline at end of file
import { combineReducers } from "redux";
import authReducer from "./authReducers";
import errorReducer from "./errorReducers";
export default combineReducers({
auth: authReducer,
errors: errorReducer
});
\ No newline at end of file
// 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 https://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 https://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 https://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();
});
}
}
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const initialState = {};
const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middleware))
);
export default store;
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
<Route
{...rest}
render={props =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps)(PrivateRoute);
\ No newline at end of file
import axios from "axios";
const setAuthToken = token => {
if (token) {
// Apply authorization token to every request if logged in
axios.defaults.headers.common["Authorization"] = token;
} else {
// Delete auth header
delete axios.defaults.headers.common["Authorization"];
}
};
export default setAuthToken;
\ No newline at end of file
import socketIOClient from 'socket.io-client';
let socket = socketIOClient('/', {path: '/socket/', transports: ['websocket', 'polling', 'flashsocket']});
export default socket;
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment