├── functions ├── .gitignore ├── package.json └── index.js ├── README.md ├── firebase.json ├── liff ├── index.html ├── 404.html ├── index.css └── index.js ├── .gitignore └── LICENSE /functions/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LIFF x WebRTC 2 | A demo how to create a camera app in LIFF using WebRTC 3 | -------------------------------------------------------------------------------- /firebase.json: -------------------------------------------------------------------------------- 1 | { 2 | "hosting": { 3 | "public": "liff", 4 | "ignore": [ 5 | "firebase.json", 6 | "**/.*", 7 | "**/node_modules/**" 8 | ] 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /functions/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "functions", 3 | "description": "Cloud Functions for Firebase", 4 | "scripts": { 5 | "serve": "firebase emulators:start --only functions", 6 | "shell": "firebase functions:shell", 7 | "start": "npm run shell", 8 | "deploy": "firebase deploy --only functions", 9 | "logs": "firebase functions:log" 10 | }, 11 | "engines": { 12 | "node": "16" 13 | }, 14 | "main": "index.js", 15 | "dependencies": { 16 | "firebase-admin": "^9.8.0", 17 | "firebase-functions": "^3.14.1", 18 | "@google-cloud/vision": "^2.4.2" 19 | }, 20 | "devDependencies": { 21 | "firebase-functions-test": "^0.2.0" 22 | }, 23 | "private": true 24 | } 25 | -------------------------------------------------------------------------------- /liff/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Open Camera using WebRTC 8 | 9 | 10 | 11 | 12 |
13 |
14 | 15 |
16 | 17 | 18 | 19 |
20 |
21 | 22 | 23 |
24 | 25 |
26 | 27 |
28 | 29 | 30 | 31 |
32 |
33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /functions/index.js: -------------------------------------------------------------------------------- 1 | const functions = require("firebase-functions"); 2 | 3 | exports.myCallable = functions.https.onCall(async (data, context) => { 4 | const base64 = data.base64.split(",") 5 | 6 | const vision = require('@google-cloud/vision') 7 | const client = new vision.ImageAnnotatorClient({ keyFilename: './service-account.json' }) 8 | const request = { image: { content: base64[1] } } 9 | const [result] = await client.textDetection(request) 10 | const detections = result.fullTextAnnotation.text 11 | const datas = {} 12 | 13 | detections.split('\n').forEach((row) => { 14 | let items = row.split(' ') 15 | 16 | const thaiid = items.join('') 17 | if (isThaiNationalID(thaiid)) { 18 | datas.cardNumber = thaiid 19 | } 20 | 21 | if (row.includes('ชื่อตัวและชื่อสกุล')) { 22 | datas.prename = items[1] 23 | datas.firstname = items[2] 24 | datas.lastname = items[3] 25 | } 26 | 27 | if (row.includes('Date of Birth')) { 28 | datas.birthDate = `${items[3]} ${items[4]} ${items[5]}` 29 | } 30 | }) 31 | if (datas.prename) { 32 | datas.gender = 'M' 33 | if (['น.ส.', 'นางสาว', 'นาง', 'เด็กหญิง'].includes(datas.prename)) { 34 | datas.gender = 'F' 35 | } 36 | } 37 | 38 | return { 39 | result: datas 40 | } 41 | }) 42 | 43 | function isThaiNationalID(id) { 44 | if (!/^[0-9]{13}$/g.test(id)) { 45 | return false 46 | } 47 | let i; let sum = 0 48 | for ((i = 0), (sum = 0); i < 12; i++) { 49 | sum += Number.parseInt(id.charAt(i)) * (13 - i) 50 | } 51 | const checkSum = (11 - sum % 11) % 10 52 | if (checkSum === Number.parseInt(id.charAt(12))) { 53 | return true 54 | } 55 | return false 56 | } -------------------------------------------------------------------------------- /liff/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Page Not Found 7 | 8 | 23 | 24 | 25 |
26 |

404

27 |

Page Not Found

28 |

The specified file was not found on this website. Please check the URL for mistakes and try again.

29 |

Why am I seeing this?

30 |

This page was generated by the Firebase Command-Line Interface. To modify it, edit the 404.html file in your project's configured public directory.

31 |
32 | 33 | 34 | -------------------------------------------------------------------------------- /liff/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 0; 3 | margin: 0; 4 | } 5 | 6 | #container { 7 | padding: 16px; 8 | } 9 | 10 | #canvas, #camera, input[type=file] { 11 | display: none 12 | } 13 | 14 | .label { 15 | display: inline-block; 16 | margin: 4px 17 | } 18 | 19 | .button { 20 | width: 100%; 21 | background-color: #06c755; 22 | color: white; 23 | padding: 14px 20px; 24 | margin: 8px 0; 25 | border: none; 26 | border-radius: 4px; 27 | cursor: pointer; 28 | font-size: 16px; 29 | font-weight: bold; 30 | height: 58px; 31 | } 32 | 33 | .button-group button { 34 | width: 49.4% 35 | } 36 | 37 | .disable { 38 | background-color: #efefef; 39 | color: #777; 40 | } 41 | 42 | #stream, #snapshot img, #canvas { 43 | width: 100%; 44 | height: 360px; 45 | } 46 | 47 | .custom-file-upload { 48 | width: 49.4%; 49 | border-radius: 4px; 50 | background-color: #06c755; 51 | padding: 20px 0; 52 | cursor: pointer; 53 | margin: 8px 0; 54 | color: white; 55 | font-weight: bold; 56 | font-size: 16px; 57 | text-align: center 58 | } 59 | 60 | #camera { 61 | position: relative; 62 | } 63 | 64 | #camera div { 65 | cursor: pointer; 66 | } 67 | 68 | #camera span { 69 | position: absolute; 70 | border-radius: 50%; 71 | bottom: 20px; 72 | left: 0; 73 | right: 0; 74 | margin-left: auto; 75 | margin-right: auto; 76 | display: flex; 77 | align-items: center; 78 | justify-content: center; 79 | } 80 | 81 | #camera span:first-of-type { 82 | background: white; 83 | width: 80px; 84 | height: 80px; 85 | } 86 | 87 | #camera span:nth-of-type(2) { 88 | background: black; 89 | bottom: 24px; 90 | width: 72px; 91 | height: 72px; 92 | } 93 | 94 | #camera span:last-of-type { 95 | background: white; 96 | bottom: 28px; 97 | width: 64px; 98 | height: 64px; 99 | } 100 | 101 | @media only screen and (min-width: 960px) { 102 | #container { 103 | width: 36%; 104 | margin: 0 auto 105 | } 106 | 107 | #stream, #snapshot img, #canvas { 108 | height: 450px; 109 | } 110 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | */npm-debug.log 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | firebase-debug.log* 9 | firebase-debug.*.log* 10 | **/firebase-debug.log 11 | **/ui-debug.log 12 | **/database-debug.log 13 | **/pubsub-debug.log 14 | 15 | # Diagnostic reports (https://nodejs.org/api/report.html) 16 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 17 | 18 | # Firebase cache 19 | **/.firebase 20 | 21 | # Firebase config 22 | **/.firebaserc 23 | 24 | # Runtime data 25 | pids 26 | *.pid 27 | *.seed 28 | *.pid.lock 29 | 30 | # Directory for instrumented libs generated by jscoverage/JSCover 31 | lib-cov 32 | 33 | # Coverage directory used by tools like istanbul 34 | coverage 35 | *.lcov 36 | 37 | # nyc test coverage 38 | .nyc_output 39 | 40 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 41 | .grunt 42 | 43 | # Bower dependency directory (https://bower.io/) 44 | bower_components 45 | 46 | # node-waf configuration 47 | .lock-wscript 48 | 49 | # Compiled binary addons (http://nodejs.org/api/addons.html) 50 | build/Release 51 | 52 | # Dependency directories 53 | **/node_modules/* 54 | **/jspm_packages/* 55 | 56 | # TypeScript v1 declaration files 57 | typings/ 58 | 59 | # TypeScript cache 60 | *.tsbuildinfo 61 | 62 | # Optional npm cache directory 63 | .npm 64 | 65 | # Optional eslint cache 66 | .eslintcache 67 | 68 | # Microbundle cache 69 | .rpt2_cache/ 70 | .rts2_cache_cjs/ 71 | .rts2_cache_es/ 72 | .rts2_cache_umd/ 73 | 74 | # Optional REPL history 75 | .node_repl_history 76 | 77 | # Output of 'npm pack' 78 | *.tgz 79 | 80 | # Yarn Integrity file 81 | .yarn-integrity 82 | yarn.lock 83 | 84 | # dotenv environment variables file 85 | .env 86 | .env.test 87 | 88 | # parcel-bundler cache (https://parceljs.org/) 89 | .cache 90 | 91 | # Next.js build output 92 | .next 93 | 94 | # Nuxt.js build / generate output 95 | .nuxt 96 | dist 97 | 98 | # Gatsby files 99 | .cache/ 100 | 101 | # vuepress build output 102 | .vuepress/dist 103 | 104 | # Serverless directories 105 | .serverless/ 106 | 107 | # FuseBox cache 108 | .fusebox/ 109 | 110 | # DynamoDB Local files 111 | .dynamodb/ 112 | 113 | # TernJS port file 114 | .tern-port 115 | 116 | .idea 117 | **/.runtimeconfig.json 118 | **/package-lock.json 119 | **/tsconfig-compile.json 120 | service-account.json 121 | service-account-credentials.json 122 | 123 | .DS_Store 124 | Thumbs.db 125 | -------------------------------------------------------------------------------- /liff/index.js: -------------------------------------------------------------------------------- 1 | // BEGIN DOM BINDING 2 | var cameraStream = null 3 | const canvas = document.querySelector('#canvas') 4 | const stream = document.querySelector('#stream') 5 | const camera = document.querySelector('#camera') 6 | const fileInput = document.querySelector('#file') 7 | const btnStream = document.querySelector('#btnStream') 8 | const btnCapture = document.querySelector('#camera div') 9 | const snapshot = document.querySelector('#snapshot') 10 | const previewImage = document.querySelector('#snapshot img') 11 | // END DOM BINDING 12 | 13 | liff.init({ liffId: "" }, () => { 14 | // Do something with LIFF functions 15 | }) 16 | 17 | const startStreaming = () => { 18 | const mediaSupport = 'mediaDevices' in navigator 19 | if (mediaSupport && null == cameraStream) { 20 | navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }).then(function (mediaStream) { 21 | cameraStream = mediaStream 22 | stream.srcObject = mediaStream 23 | stream.play() 24 | }).catch(function (err) { 25 | console.log("Unable to access camera: " + err) 26 | }) 27 | } else { 28 | alert('Your browser does not support media devices.') 29 | return 30 | } 31 | } 32 | 33 | const captureSnapshot = () => { 34 | if (null != cameraStream) { 35 | var ctx = canvas.getContext('2d') 36 | ctx.drawImage(stream, 0, 0, canvas.width, canvas.height) 37 | previewImage.src = canvas.toDataURL("image/png") 38 | ocr(canvas.toDataURL("image/png")) 39 | } 40 | } 41 | 42 | const stopStreaming = () => { 43 | if (null != cameraStream) { 44 | const track = cameraStream.getTracks()[0] 45 | track.stop() 46 | stream.load() 47 | cameraStream = null 48 | } 49 | } 50 | 51 | const getBase64 = (file) => { 52 | var reader = new FileReader() 53 | reader.readAsDataURL(file) 54 | reader.onload = function () { 55 | previewImage.src = reader.result 56 | ocr(reader.result) 57 | } 58 | reader.onerror = function (error) { 59 | console.log("Error: ", error) 60 | } 61 | } 62 | 63 | // BEGIN EVENT LISTENERS 64 | fileInput.onchange = (event) => { 65 | const file = event.target.files[0] 66 | const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'] 67 | if (file) { 68 | if (validImageTypes.includes(file.type)) { 69 | previewImage.style.objectFit = "contain" 70 | if (liff.isInClient()) { 71 | previewImage.style.objectFit = "cover" 72 | } 73 | camera.style.display = "none" 74 | snapshot.style.display = "block" 75 | getBase64(file) 76 | stopStreaming() 77 | } 78 | } 79 | } 80 | 81 | btnStream.onclick = () => { 82 | startStreaming() 83 | camera.style.display = "block" 84 | snapshot.style.display = "none" 85 | } 86 | 87 | btnCapture.onclick = () => { 88 | captureSnapshot() 89 | camera.style.display = "none" 90 | snapshot.style.display = "block" 91 | stopStreaming() 92 | } 93 | // END EVENT LISTENERS 94 | 95 | 96 | // BEGIN FIREBASE 97 | import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js"; 98 | import { getFunctions, httpsCallable } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-functions.js"; 99 | 100 | const firebaseConfig = { 101 | apiKey: "### FIREBASE API KEY ###", 102 | authDomain: "### FIREBASE AUTH DOMAIN ###", 103 | projectId: "### CLOUD FUNCTIONS PROJECT ID ###" 104 | }; 105 | const app = initializeApp(firebaseConfig); 106 | const functions = getFunctions(app); 107 | 108 | function ocr(base64encoded) { 109 | const myCallable = httpsCallable(functions, 'myCallable'); 110 | myCallable({ base64: base64encoded }).then((result) => { 111 | console.log(result.data); 112 | }).catch((error) => { 113 | console.error(error.code, error.message); 114 | }); 115 | } 116 | // END FIREBASE -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------