├── src ├── logo.png ├── index.css ├── components │ ├── Notifier │ │ ├── Notifier.css │ │ └── index.js │ └── ClCamera │ │ ├── ClCamera.css │ │ └── index.js ├── App.css ├── index.js ├── App.test.js ├── App.js ├── webcam.js └── registerServiceWorker.js ├── public ├── favicon.ico ├── manifest.json └── index.html ├── images ├── demo_offline.gif └── demo_online.gif ├── .env.example ├── .gitignore ├── manifest.json ├── package.json └── README.md /src/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oreHGA/cl-react-pwa/HEAD/src/logo.png -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oreHGA/cl-react-pwa/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | } 6 | -------------------------------------------------------------------------------- /images/demo_offline.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oreHGA/cl-react-pwa/HEAD/images/demo_offline.gif -------------------------------------------------------------------------------- /images/demo_online.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oreHGA/cl-react-pwa/HEAD/images/demo_online.gif -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | REACT_APP_CLOUD_NAME="CLOUDINARY_CLOUDNAME" 2 | REACT_APP_CLOUD_PRESET="CLOUDINARY_UPLOAD_PRESET" -------------------------------------------------------------------------------- /src/components/Notifier/Notifier.css: -------------------------------------------------------------------------------- 1 | .notify{ 2 | background-color: #0066B2; 3 | padding: 20px; 4 | text-align: center; 5 | color: white; 6 | margin-bottom: 20px; 7 | } 8 | 9 | .danger{ 10 | background-color: #D77623; 11 | } -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 80px; 7 | } 8 | 9 | .App-header { 10 | height: 150px; 11 | } 12 | 13 | .App-title { 14 | font-size: 1.5em; 15 | } 16 | 17 | .App-intro { 18 | font-size: large; 19 | } 20 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import registerServiceWorker from './registerServiceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | registerServiceWorker(); 9 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | .env 19 | 20 | npm-debug.log* 21 | yarn-debug.log* 22 | yarn-error.log* 23 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "CloudyCame", 3 | "name": "Cloudinary PWA Camera", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "512x512 192x192 64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "CloudyCam", 3 | "name": "Clodinary Offline PWA Camera", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "512x512 192x192 64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cl-pwa", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "axios": "^0.18.0", 7 | "classnames": "^2.2.6", 8 | "cloudinary-react": "^1.0.6", 9 | "react": "^16.4.2", 10 | "react-dom": "^16.4.2", 11 | "react-scripts": "1.1.5" 12 | }, 13 | "scripts": { 14 | "start": "react-scripts start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test --env=jsdom", 17 | "eject": "react-scripts eject" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/components/ClCamera/ClCamera.css: -------------------------------------------------------------------------------- 1 | .captureButton{ 2 | margin-top: 20px; 3 | padding: 10px; 4 | padding-left: 20px; 5 | padding-right: 20px; 6 | background-color: #0066B2; 7 | color: white; 8 | border-radius: 5px; 9 | } 10 | 11 | .deleteButton{ 12 | margin-top: 20px; 13 | padding: 10px; 14 | padding-left: 20px; 15 | padding-right: 20px; 16 | background-color: #D77623; 17 | color: white; 18 | border-radius: 5px; 19 | } 20 | 21 | .imageCanvas{ 22 | margin-top: 20px; 23 | width: 100%; 24 | height: 200px; 25 | /* object-fit: cover; */ 26 | display: flex; 27 | justify-content: center; 28 | } -------------------------------------------------------------------------------- /src/components/Notifier/index.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import "./Notifier.css"; 3 | import classnames from 'classnames'; 4 | 5 | class Notifier extends Component { 6 | render() { 7 | const notifyclass = classnames('notify', { 8 | danger: this.props.offline 9 | }); 10 | const message = this.props.offline ? 11 | ` 12 | CloudyCam is offline! Your images will be saved now and then uploaded to 13 | your Cloudinary Media Library once your internet connection is back up. 14 | ` : 15 | ` 16 | Take a picture and it will be uploaded to your Cloudinary Media Library. 17 | `; 18 | return ( 19 |
20 |

21 | {message} 22 |

23 |
24 | ); 25 | } 26 | } 27 | 28 | export default Notifier; 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cloudy Cam 2 | 3 | An offline Progressive Web Application (PWA) camera app with React and Cloudinary 4 | 5 | - ![Cloudy Cam - Online Mode](./images/demo_online.gif) 6 | 7 | - ![Cloudy Cam - Offline Mode](./images/demo_offline.gif) 8 | 9 | [Link to Tutorial](https://dev.to/ore/building-an-offline-pwa-camera-app-with-react-and-cloudinary-5b9k) 10 | 11 | ## Setup 12 | 13 | ### Clone the repository 14 | ``` 15 | git clone https://github.com/oreHGA/cl-react-pwa.git 16 | ``` 17 | 18 | ### Install node modules 19 | ``` 20 | yarn 21 | ``` 22 | 23 | ### Update Env 24 | ``` 25 | cp .env.example .env 26 | ``` 27 | 28 | - Edit the `.env` file with your Cloudinary Credentials. Sign Up for a Cloudinary account [here](https://cloudinary.com/signup) 29 | 30 | ### Run - Development 31 | ``` 32 | yarn start 33 | ``` 34 | 35 | - Navigate to local developement server (usually `https://localhost:3000`) 36 | 37 | ### Run - Production 38 | ``` 39 | yarn build 40 | yarn global add serve 41 | serve -s build 42 | ``` 43 | 44 | - Navigate to static production server (usually `http://localhost:5000`) 45 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import logo from './logo.png'; 3 | import './App.css'; 4 | import ClCamera from './components/ClCamera'; 5 | import Notifier from './components/Notifier'; 6 | class App extends Component { 7 | constructor() { 8 | super(); 9 | this.state = { 10 | offline: false 11 | } 12 | } 13 | componentDidMount() { 14 | window.addEventListener('online', () => { 15 | this.setState({ offline: false }); 16 | }); 17 | 18 | window.addEventListener('offline', () => { 19 | this.setState({ offline: true }); 20 | }); 21 | } 22 | 23 | componentDidUpdate() { 24 | let offlineStatus = !navigator.onLine; 25 | if (this.state.offline !== offlineStatus) { 26 | this.setState({ offline: offlineStatus }); 27 | } 28 | } 29 | 30 | render() { 31 | return ( 32 |
33 | 34 |
35 | Cloudinary Logo 36 |

CloudyCam

37 |
38 | 39 |
40 | ); 41 | } 42 | } 43 | 44 | export default App; 45 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 22 | React App 23 | 24 | 25 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/webcam.js: -------------------------------------------------------------------------------- 1 | export class Webcam { 2 | constructor(webcamElement, canvasElement) { 3 | this.webcamElement = webcamElement; 4 | this.canvasElement = canvasElement; 5 | } 6 | 7 | adjustVideoSize(width, height) { 8 | const aspectRatio = width / height; 9 | if (width >= height) { 10 | this.webcamElement.width = aspectRatio * this.webcamElement.height; 11 | } else if (width < height) { 12 | this.webcamElement.height = this.webcamElement.width / aspectRatio; 13 | } 14 | } 15 | 16 | async setup() { 17 | return new Promise((resolve, reject) => { 18 | if (navigator.mediaDevices.getUserMedia !== undefined) { 19 | navigator.mediaDevices.getUserMedia({ audio: false, video: { facingMode: 'environment' } }) 20 | .then((mediaStream) => { 21 | if ("srcObject" in this.webcamElement) { 22 | this.webcamElement.srcObject = mediaStream; 23 | console.log('here'); 24 | } else { 25 | // For older browsers withouth the srcObject. 26 | this.webcamElement.src = window.URL.createObjectURL(mediaStream); 27 | } 28 | this.webcamElement.onloadedmetadata = (e) => { 29 | this.webcamElement.play(); 30 | }; 31 | }); 32 | } else { 33 | reject(); 34 | } 35 | }); 36 | } 37 | 38 | _drawImage() { 39 | const imageWidth = this.webcamElement.videoWidth; 40 | const imageHeight = this.webcamElement.videoHeight; 41 | 42 | const context = this.canvasElement.getContext('2d'); 43 | this.canvasElement.width = imageWidth; 44 | this.canvasElement.height = imageHeight; 45 | 46 | context.drawImage(this.webcamElement, 0, 0, imageWidth, imageHeight); 47 | 48 | return { imageHeight, imageWidth }; 49 | } 50 | 51 | takeBlobPhoto() { 52 | const { imageWidth, imageHeight } = this._drawImage(); 53 | return new Promise((resolve, reject) => { 54 | this.canvasElement.toBlob((blob) => { 55 | resolve({ blob, imageHeight, imageWidth }); 56 | }); 57 | }); 58 | } 59 | 60 | takeBase64Photo({ type, quality } = { type: 'png', quality: 1 }) { 61 | const { imageHeight, imageWidth } = this._drawImage(); 62 | const base64 = this.canvasElement.toDataURL('image/' + type, quality); 63 | return { base64, imageHeight, imageWidth }; 64 | } 65 | } -------------------------------------------------------------------------------- /src/registerServiceWorker.js: -------------------------------------------------------------------------------- 1 | // In production, we register a service worker to serve assets from local cache. 2 | 3 | // This lets the app load faster on subsequent visits in production, and gives 4 | // it offline capabilities. However, it also means that developers (and users) 5 | // will only see deployed updates on the "N+1" visit to a page, since previously 6 | // cached resources are updated in the background. 7 | 8 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy. 9 | // This link also includes instructions on opting out of this behavior. 10 | 11 | const isLocalhost = Boolean( 12 | window.location.hostname === 'localhost' || 13 | // [::1] is the IPv6 localhost address. 14 | window.location.hostname === '[::1]' || 15 | // 127.0.0.1/8 is considered localhost for IPv4. 16 | window.location.hostname.match( 17 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 18 | ) 19 | ); 20 | 21 | export default function register() { 22 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 23 | // The URL constructor is available in all browsers that support SW. 24 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location); 25 | if (publicUrl.origin !== window.location.origin) { 26 | // Our service worker won't work if PUBLIC_URL is on a different origin 27 | // from what our page is served on. This might happen if a CDN is used to 28 | // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 29 | return; 30 | } 31 | 32 | window.addEventListener('load', () => { 33 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 34 | 35 | if (isLocalhost) { 36 | // This is running on localhost. Lets check if a service worker still exists or not. 37 | checkValidServiceWorker(swUrl); 38 | 39 | // Add some additional logging to localhost, pointing developers to the 40 | // service worker/PWA documentation. 41 | navigator.serviceWorker.ready.then(() => { 42 | console.log( 43 | 'This web app is being served cache-first by a service ' + 44 | 'worker. To learn more, visit https://goo.gl/SC7cgQ' 45 | ); 46 | }); 47 | } else { 48 | // Is not local host. Just register service worker 49 | registerValidSW(swUrl); 50 | } 51 | }); 52 | } 53 | } 54 | 55 | function registerValidSW(swUrl) { 56 | navigator.serviceWorker 57 | .register(swUrl) 58 | .then(registration => { 59 | registration.onupdatefound = () => { 60 | const installingWorker = registration.installing; 61 | installingWorker.onstatechange = () => { 62 | if (installingWorker.state === 'installed') { 63 | if (navigator.serviceWorker.controller) { 64 | // At this point, the old content will have been purged and 65 | // the fresh content will have been added to the cache. 66 | // It's the perfect time to display a "New content is 67 | // available; please refresh." message in your web app. 68 | console.log('New content is available; please refresh.'); 69 | } else { 70 | // At this point, everything has been precached. 71 | // It's the perfect time to display a 72 | // "Content is cached for offline use." message. 73 | console.log('Content is cached for offline use.'); 74 | } 75 | } 76 | }; 77 | }; 78 | }) 79 | .catch(error => { 80 | console.error('Error during service worker registration:', error); 81 | }); 82 | } 83 | 84 | function checkValidServiceWorker(swUrl) { 85 | // Check if the service worker can be found. If it can't reload the page. 86 | fetch(swUrl) 87 | .then(response => { 88 | // Ensure service worker exists, and that we really are getting a JS file. 89 | if ( 90 | response.status === 404 || 91 | response.headers.get('content-type').indexOf('javascript') === -1 92 | ) { 93 | // No service worker found. Probably a different app. Reload the page. 94 | navigator.serviceWorker.ready.then(registration => { 95 | registration.unregister().then(() => { 96 | window.location.reload(); 97 | }); 98 | }); 99 | } else { 100 | // Service worker found. Proceed as normal. 101 | registerValidSW(swUrl); 102 | } 103 | }) 104 | .catch(() => { 105 | console.log( 106 | 'No internet connection found. App is running in offline mode.' 107 | ); 108 | }); 109 | } 110 | 111 | export function unregister() { 112 | if ('serviceWorker' in navigator) { 113 | navigator.serviceWorker.ready.then(registration => { 114 | registration.unregister(); 115 | }); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/components/ClCamera/index.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { Webcam } from '../../webcam'; 3 | import './ClCamera.css'; 4 | import axios from 'axios'; 5 | 6 | class ClCamera extends Component { 7 | constructor() { 8 | super(); 9 | this.webcam = null; 10 | this.state = { 11 | capturedImage: null, 12 | captured: false, 13 | uploading: false 14 | } 15 | } 16 | 17 | componentDidMount() { 18 | // initialize the camera 19 | this.canvasElement = document.createElement('canvas'); 20 | this.webcam = new Webcam( 21 | document.getElementById('webcam'), 22 | this.canvasElement 23 | ); 24 | this.webcam.setup().catch(() => { 25 | alert('Error getting access to your camera'); 26 | }); 27 | } 28 | 29 | componentDidUpdate(prevProps) { 30 | if (!this.props.offline && (prevProps.offline === true)) { 31 | // if its online, 32 | this.batchUploads(); 33 | } 34 | } 35 | 36 | render() { 37 | const imageDisplay = this.state.capturedImage ? 38 | captured 39 | : 40 | ; 41 | 42 | const buttons = this.state.captured ? 43 |
44 | 45 | 46 |
: 47 | 48 | 49 | const uploading = this.state.uploading ? 50 |

Uploading Image, please wait ...

51 | : 52 | 53 | 54 | return ( 55 |
56 | {uploading} 57 |
64 | ) 65 | } 66 | 67 | captureImage = async () => { 68 | const capturedData = this.webcam.takeBase64Photo({ type: 'jpeg', quality: 0.8 }); 69 | console.log(capturedData); 70 | this.setState({ 71 | captured: true, 72 | capturedImage: capturedData.base64 73 | }); 74 | } 75 | 76 | discardImage = () => { 77 | this.setState({ 78 | captured: false, 79 | capturedImage: null 80 | }) 81 | } 82 | 83 | uploadImage = () => { 84 | if (this.props.offline) { 85 | console.log("you're using in offline mode sha"); 86 | // create a random string with a prefix 87 | const prefix = 'cloudy_pwa_'; 88 | // create random string 89 | const rs = Math.random().toString(36).substr(2, 5); 90 | localStorage.setItem(`${prefix}${rs}`, this.state.capturedImage); 91 | alert('Image saved locally, it will be uploaded to your Cloudinary media library once internet connection is detected'); 92 | this.discardImage(); 93 | // save image to local storage 94 | } else { 95 | this.setState({ 'uploading': true }); 96 | axios.post( 97 | `https://api.cloudinary.com/v1_1/${process.env.REACT_APP_CLOUD_NAME}/image/upload`, 98 | { 99 | file: this.state.capturedImage, 100 | upload_preset: process.env.REACT_APP_CLOUD_PRESET 101 | } 102 | ).then( 103 | (data) => this.checkUploadStatus(data) 104 | ) 105 | .catch((error) => { 106 | alert('Sorry, we encountered an error uploading your image'); 107 | this.setState({ 'uploading': false }); 108 | }); 109 | } 110 | } 111 | 112 | findLocalItems = (query) => { 113 | var i, results = []; 114 | for (i in localStorage) { 115 | if (localStorage.hasOwnProperty(i)) { 116 | if (i.match(query) || (!query && typeof i === 'string')) { 117 | const value = localStorage.getItem(i); 118 | results.push({ key: i, val: value }); 119 | } 120 | } 121 | } 122 | return results; 123 | } 124 | 125 | checkUploadStatus = (data) => { 126 | this.setState({ 'uploading': false }); 127 | if (data.status === 200) { 128 | alert('Image Uploaded to Cloudinary Media Library'); 129 | this.discardImage(); 130 | } else { 131 | alert('Sorry, we encountered an error uploading your image'); 132 | } 133 | } 134 | batchUploads = () => { 135 | // this is where all the images saved can be uploaded as batch uploads 136 | const images = this.findLocalItems(/^cloudy_pwa_/); 137 | let error = false; 138 | if (images.length > 0) { 139 | this.setState({ 'uploading': true }); 140 | for (let i = 0; i < images.length; i++) { 141 | // upload 142 | axios.post( 143 | `https://api.cloudinary.com/v1_1/${process.env.REACT_APP_CLOUD_NAME}/image/upload`, 144 | { 145 | file: images[i].val, 146 | upload_preset: process.env.REACT_APP_CLOUD_PRESET 147 | } 148 | ).then((data) => this.checkUploadStatus(data)).catch((error) => { 149 | error = true; 150 | }) 151 | } 152 | this.setState({ 'uploading': false }); 153 | if (!error) { 154 | alert("All saved images have been uploaded to your Cloudinary Media Library"); 155 | } 156 | } 157 | } 158 | } 159 | export default ClCamera; 160 | --------------------------------------------------------------------------------