├── icons └── ui_image.png ├── images ├── example_pic.png ├── example_create_category_1.png ├── example_create_category_2.png ├── example_create_category_3.png ├── example_create_category_4.png └── example_create_category_5.png ├── package.json ├── .gitignore ├── locales └── en-US │ └── ui_media.json ├── README.md ├── LICENSE ├── ui_media.js └── ui_media.html /icons/ui_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/st-one-io/node-red-contrib-ui-media/HEAD/icons/ui_image.png -------------------------------------------------------------------------------- /images/example_pic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/st-one-io/node-red-contrib-ui-media/HEAD/images/example_pic.png -------------------------------------------------------------------------------- /images/example_create_category_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/st-one-io/node-red-contrib-ui-media/HEAD/images/example_create_category_1.png -------------------------------------------------------------------------------- /images/example_create_category_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/st-one-io/node-red-contrib-ui-media/HEAD/images/example_create_category_2.png -------------------------------------------------------------------------------- /images/example_create_category_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/st-one-io/node-red-contrib-ui-media/HEAD/images/example_create_category_3.png -------------------------------------------------------------------------------- /images/example_create_category_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/st-one-io/node-red-contrib-ui-media/HEAD/images/example_create_category_4.png -------------------------------------------------------------------------------- /images/example_create_category_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/st-one-io/node-red-contrib-ui-media/HEAD/images/example_create_category_5.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-red-contrib-ui-media", 3 | "version": "2.0.0", 4 | "description": "A simple NODE to allow images and videos on the dashboard", 5 | "main": "ui_image.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "Igor Steuck Lopes, Diego Rampim", 10 | "keywords": [ 11 | "node-red", 12 | "media", 13 | "ui" 14 | ], 15 | "license": "Apache-2.0", 16 | "node-red": { 17 | "nodes": { 18 | "ui_media": "ui_media.js" 19 | } 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "https://github.com/netsmarttech/node-red-contrib-ui-media.git" 24 | }, 25 | "dependencies": { 26 | "formidable": "^1.2.2", 27 | "mime-types": "^2.1.27", 28 | "mkdirp": "^1.0.4" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # Visual Studio Code config folder 61 | .vscode 62 | -------------------------------------------------------------------------------- /locales/en-US/ui_media.json: -------------------------------------------------------------------------------- 1 | { 2 | "ui_media": { 3 | "config": { 4 | "label": { 5 | "name": "Name", 6 | "group": "Group", 7 | "size": "Size", 8 | "link": "Link", 9 | "configuration": "Configuration", 10 | "alttext": "Alt" 11 | }, 12 | "layouts": { 13 | "layout": "Layout", 14 | "center": "Center", 15 | "expand": "Expand", 16 | "adjust": "Adjust", 17 | "side-by-side": "Side by side" 18 | } 19 | }, 20 | "files": { 21 | "label": { 22 | "files": "Files", 23 | "category": "Category", 24 | "file": "File", 25 | "video-options": "Video Options", 26 | "run-on-start": "Autoplay", 27 | "show-controls": "Show controls", 28 | "loop": "Loop", 29 | "muted": "Muted", 30 | "preview": "Preview", 31 | "add-new": "Add new...", 32 | "remove-category": "Remove category...", 33 | "remove-media": "Remove media...", 34 | "tooltip": "Tooltip" 35 | } 36 | }, 37 | "error": { 38 | "no-config": "Invalid node configuration", 39 | "no-mimetype": "Missing mimetype information", 40 | "undefined-media-type": "Could not determine the media's type" 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | node-red-contrib-ui-media 2 | ===================== 3 | A Node-RED UI node to show media files (image and video) on the dashboard. 4 | 5 | This node was created as part of the [ST-One](https://st-one.io) project. 6 | 7 | Install 8 | ----------- 9 | 10 | You can install this node directly from the "Manage Palette" menu in the Node-RED interface. For now, the required modules are on this repository, but we'll be listed here 11 | in the future. 12 | 13 | Alternatively, run the following command in your Node-RED user directory - typically `~/.node-red` on Linux or `%HOMEPATH%\.nodered` on Windows 14 | 15 | npm install node-red-contrib-ui-media 16 | 17 | Usage 18 | ----------- 19 | 20 | Each media node can show one media item at a time. 21 | ![](/images/example_pic.png) 22 | To upload an image or a video you first must go to the File tab. Then you 'll click the icon to the right of the Category dropdown menu (left pic) and will give it a name like on the example (right pic). Finally, click on the check icon to create a new media category. Categories don't discriminate between file types, so you might have an image and a video on the same category. 23 | 24 | | ![](/images/example_create_category_1.png) | ![](/images/example_create_category_2.png) | 25 | |:--------------------------------------:|:----------------------------:| 26 | 27 | After creatilng, or selecting the category that you want, click on the icon right to the File dropdown menu (left pic). Click on "Browse" to navigate through your directories, select a file and click Open. An upload icon will appear, click on it to upload your file to your category folder. 28 | 29 | | ![](/images/example_create_category_3.png) | ![](/images/example_create_category_4.png)| 30 | |:--------------------------------------:|:----------------------------:| 31 | 32 | In general, categories and files will be saved at `/lib/`. When the project resource is enabled on your Node RED settings, they will be saved on the project directory. Finally, you can select an image from the dropdown menu and preview it on the edit tab. 33 | 34 | ![](/images/example_create_category_5.png) 35 | 36 | Bugs and enhancements 37 | ----------- 38 | 39 | Please share your ideas and experiences on the [Node-RED forum](https://discourse.nodered.org/), or open an issue on the [page of the project on GitHub](https://github.com/netsmarttech/node-red-contrib-ui-media) 40 | 41 | License 42 | ----------- 43 | Copyright 2016-2020 ST-One Ltda., [Apache 2.0 license](LICENSE). 44 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /ui_media.js: -------------------------------------------------------------------------------- 1 | //@ts-check 2 | /* 3 | Copyright 2016-2020 ST-One Ltda. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | */ 17 | 18 | "use strict"; 19 | 20 | var formidable = require('formidable'); 21 | var fs = require('fs'); 22 | var path = require('path'); 23 | var urlPath = path.posix; 24 | var mkdirp = require('mkdirp'); 25 | var mime = require('mime-types'); 26 | 27 | module.exports = function (RED) { 28 | 29 | var pathDir, pathUpload, httpRoot; 30 | 31 | /** 32 | * Checks if projects are enabled in the settings and create a path for it if 33 | * it is. In case projects are disabled, the old path to the lib is created 34 | */ 35 | function updateDirs() { 36 | let editorTheme = RED.settings.get("editorTheme"); 37 | let projects = RED.settings.get("projects"); 38 | let userDir = RED.settings.userDir; 39 | 40 | if (editorTheme && projects && editorTheme.projects && editorTheme.projects.enabled && projects.activeProject) { 41 | // create the paths 42 | pathDir = path.resolve(userDir, "projects", String(projects.activeProject), "ui-media", "lib"); 43 | pathUpload = path.resolve(userDir, "projects", String(projects.activeProject), "ui-media", "upload"); 44 | } else { 45 | // create paths without the projects directory 46 | pathDir = path.resolve(userDir, "lib", "ui-media", "lib"); 47 | pathUpload = path.resolve(userDir, "lib", "ui-media", "upload"); 48 | } 49 | 50 | httpRoot = RED.settings.get('httpAdminRoot') || RED.settings.get('httpRoot') || '/'; 51 | 52 | mkdirp(pathDir).catch((err) => { 53 | if (err) { 54 | RED.log.error(`Could not create library directory [${pathDir}]: ${err}`); 55 | } 56 | }); 57 | 58 | mkdirp(pathUpload).catch((err) => { 59 | if (err) { 60 | RED.log.error(`Could not create upload directory [${pathUpload}]: ${err}`); 61 | } 62 | }); 63 | } 64 | 65 | // initialize directories with current project settings 66 | updateDirs(); 67 | // Subscribe to a project change 68 | if (RED.events) { 69 | RED.events.on('runtime-event', evt => { 70 | if (evt && evt.id === 'project-update' && evt.payload.action == 'loaded') { 71 | // Update directories when loading a project only 72 | updateDirs(); 73 | } 74 | }) 75 | } 76 | 77 | 78 | ///------> API 79 | 80 | function uploadMedia(req, res) { 81 | 82 | var error = []; 83 | var success = []; 84 | 85 | var form = new formidable.IncomingForm(); 86 | form.multiples = true; 87 | form.uploadDir = pathUpload; 88 | 89 | form.parse(req, function (err, fields, files) { 90 | 91 | var filesUpload = form.openedFiles.length; 92 | let category = sanitizeInput(req.params.category); 93 | let name; 94 | let extension; 95 | 96 | var pathBase = path.join(pathDir, category); 97 | 98 | var controlFiles = filesUpload; 99 | 100 | mkdirp(pathBase).then(() => { 101 | 102 | for (var i = 0; i < filesUpload; i++) { 103 | 104 | name = files[i].name; 105 | 106 | if (!(/\.(gif|jpg|jpeg|tiff|png|svg|mp4|webm|ogv)$/i).test(name)) { 107 | 108 | error.push({ 109 | cod: 400, 110 | msg: 'incompatible files' 111 | }); 112 | 113 | controlFiles--; 114 | 115 | return; 116 | } 117 | 118 | if (controlFiles == 0) { 119 | if (error.length > 0) { 120 | error.forEach(err => { 121 | res.status(err.cod).send(err.msg).end(); 122 | }); 123 | 124 | return; 125 | } //https://nodered.org/docs/api/runtime/api#getNode 126 | res.status(201).send(success[0]).end(); 127 | } 128 | 129 | let oldpath = files[i].path; 130 | let newpath = path.join(pathBase, sanitizeInput(files[i].name)); 131 | 132 | fs.rename(oldpath, newpath, function (err) { 133 | 134 | controlFiles--; 135 | 136 | if (err) { 137 | 138 | error.push({ 139 | cod: 500, 140 | msg: err 141 | }); 142 | return; 143 | } 144 | 145 | let pathExtern = urlPath.join(httpRoot, 'uimedia', category, name); 146 | let reference = category + "/" + name; 147 | 148 | let obj = { 149 | path: pathExtern, 150 | ref: reference 151 | }; 152 | 153 | success.push(obj); 154 | 155 | if (controlFiles == 0) { 156 | if (error.length > 0) { 157 | error.forEach(err => { 158 | res.status(err.cod).send(err.msg).end(); 159 | }); 160 | 161 | return; 162 | } 163 | res.status(201).send(success[0]).end(); 164 | } 165 | }); 166 | } 167 | }).catch(err => { 168 | res.status(500).send(err).end(); 169 | }); 170 | }); 171 | } 172 | 173 | /** 174 | * Creates a category and returns the list of current categories 175 | */ 176 | function createCategory(req, res) { 177 | let dirCategory = path.join(pathDir, sanitizeInput(req.params.category)); 178 | mkdirp(dirCategory).then(() => { 179 | restListCategories(req, res); 180 | }).catch(err => { 181 | res.status(500).send(err); 182 | }); 183 | 184 | } 185 | 186 | /** 187 | * Returns a list of categories 188 | */ 189 | function restListCategories(req, res) { 190 | 191 | let responseDone = false 192 | 193 | function doResponse(code, data) { 194 | if (responseDone) return; 195 | responseDone = true; 196 | 197 | res.status(code).json(data).end(); 198 | } 199 | 200 | fs.readdir(pathDir, 'utf-8', (err, files) => { 201 | 202 | if (err) { 203 | doResponse(500, err); 204 | return; 205 | } 206 | 207 | var response = []; 208 | var listCategory = []; 209 | 210 | var numFiles = files.length; 211 | 212 | if (!numFiles) { 213 | doResponse(200, response); 214 | return; 215 | } 216 | 217 | files.forEach(file => { 218 | 219 | var dirFile = path.join(pathDir, file); 220 | 221 | fs.stat(dirFile, (err, stat) => { 222 | if (err) { 223 | doResponse(500, err); 224 | return; 225 | } 226 | 227 | numFiles--; 228 | 229 | if (stat.isDirectory()) { 230 | response.push(file); 231 | } 232 | 233 | if (numFiles === 0) { 234 | doResponse(200, response); 235 | } 236 | }); 237 | }); 238 | }); 239 | } 240 | 241 | /** 242 | * Gets a JSON with the content of a category 243 | */ 244 | function listCategoryContents(req, res) { 245 | let pathCategory = path.join(pathDir, sanitizeInput(req.params.category)); 246 | 247 | listFilesDir(pathCategory, (err, files) => { 248 | if (err) { 249 | if (err.code === 'ENOENT') { 250 | res.status(404).end(); 251 | } else { 252 | res.status(500).json(err).end(); 253 | } 254 | return; 255 | } 256 | 257 | res.status(200).json(files).end(); 258 | }); 259 | } 260 | 261 | /** 262 | * Gets the specified media 263 | */ 264 | function getMedia(req, res) { 265 | let id = sanitizeInput(req.params.id); 266 | let category = sanitizeInput(req.params.category); 267 | 268 | var pathImage = path.join(pathDir, category, id); 269 | 270 | fs.access(pathImage, (err) => { 271 | if (err) { 272 | res.status(404).json(err).end(); 273 | return; 274 | } 275 | 276 | try { 277 | res.sendFile(pathImage); 278 | } catch (e) { 279 | /* handles errors of sendFile "gracefully" instead of 280 | potentially crashing node-red */ 281 | res.status(500).json(e).end(); 282 | } 283 | }); 284 | } 285 | 286 | /** 287 | * Deletes an media inside a category 288 | */ 289 | function deleteMedia(req, res) { 290 | let id = sanitizeInput(req.params.id); 291 | let category = sanitizeInput(req.params.category); 292 | 293 | var file = path.join(pathDir, category, id); 294 | 295 | fs.unlink(file, (err) => { 296 | if (err) { 297 | if (err.code === 'ENOENT') { 298 | res.status(404).end(); 299 | } else { 300 | res.status(500).json(err).end(); 301 | } 302 | } else { 303 | res.status(204).end(); 304 | } 305 | }); 306 | } 307 | 308 | /** 309 | * Deletes a category, and all medias that it may contain 310 | * Status codes: 204 - OK, 404 - category not found 311 | * 500 - system error 312 | */ 313 | function deleteCategory(req, res) { 314 | let categoryPath = path.join(pathDir, sanitizeInput(req.params.category)); 315 | let responseDone = false; 316 | 317 | function doResponse(code, data) { 318 | if (responseDone) return; 319 | responseDone = true; 320 | 321 | res.status(code).end(data); 322 | } 323 | 324 | function removeFolder() { 325 | fs.rmdir(categoryPath, (err) => { 326 | if (err) { 327 | RED.log.error("Error removing category: " + err); 328 | doResponse(500, err); 329 | } else { 330 | doResponse(204); 331 | } 332 | }); 333 | } 334 | 335 | fs.readdir(categoryPath, 'utf-8', (err, files) => { 336 | 337 | if (err) { 338 | if (err.code === 'ENOENT') { 339 | doResponse(404); 340 | } else { 341 | doResponse(500, err); 342 | } 343 | return; 344 | } 345 | 346 | let contFiles = files.length; 347 | 348 | // remove folder if empty 349 | if (contFiles === 0) return removeFolder(); 350 | 351 | files.forEach(file => { 352 | fs.unlink(path.join(categoryPath, file), err => { 353 | 354 | contFiles--; 355 | if (err) return doResponse(500, err); 356 | 357 | if (contFiles === 0) removeFolder(); 358 | }); 359 | }); 360 | }); 361 | } 362 | 363 | // "public" endpoint 364 | RED.httpAdmin.get('/uimedia/:category/:id', getMedia); 365 | // "private" endpoints that need permissions 366 | RED.httpAdmin.post('/uimedia/:category/:id', RED.auth.needsPermission('ui.ui_media'), uploadMedia); 367 | RED.httpAdmin.post('/uimedia/:category', RED.auth.needsPermission('ui.ui_media'), createCategory); 368 | RED.httpAdmin.get('/uimedia', RED.auth.needsPermission('ui.ui_media'), restListCategories); 369 | RED.httpAdmin.get('/uimedia/:category', RED.auth.needsPermission('ui.ui_media'), listCategoryContents); 370 | RED.httpAdmin.delete('/uimedia/:category/:id', RED.auth.needsPermission('ui.ui_media'), deleteMedia); 371 | RED.httpAdmin.delete('/uimedia/:category', RED.auth.needsPermission('ui.ui_media'), deleteCategory); 372 | 373 | ///------> API 374 | 375 | // holds reference to node-red-dashboard module 376 | var ui = undefined; 377 | 378 | /** 379 | * 380 | * @param {object} config 381 | */ 382 | function ImageNode(config) { 383 | 384 | // load the necessary module 385 | if (ui === undefined) { 386 | ui = RED.require("node-red-dashboard")(RED); 387 | } 388 | RED.nodes.createNode(this, config); 389 | 390 | let node = this; 391 | let group, tab, link; 392 | let layout = config.layout || 'adjust'; 393 | // whether we need to re-render/update the HTML template 394 | let updateHTML = true; 395 | 396 | group = RED.nodes.getNode(config.group); 397 | if (!group) { 398 | node.error(RED._("ui_media.error.no-config")); 399 | return; 400 | } 401 | 402 | tab = RED.nodes.getNode(group.config.tab); 403 | if (!tab) { 404 | node.error(RED._("ui_media.error.no-config")); 405 | return; 406 | } 407 | 408 | if (config.width == '0') { 409 | config.width = group.config.width; 410 | config.height = group.config.width; 411 | } 412 | 413 | if (config.category && config.file) { 414 | link = urlPath.join(httpRoot, 'uimedia', config.category, config.file); 415 | } 416 | 417 | /** 418 | * Check for that we have a config instance and that our config instance has a group selected, otherwise report an error 419 | * @param {object} config - configs with the layout to be set 420 | * @param {string} path - the layout configuration fo the media to be shown 421 | */ 422 | function processImageLayout(config, path) { 423 | var HTML = undefined; 424 | var auto = false; 425 | // create a div name based on the path 426 | var d = new Date(); 427 | var div_name = String(d.getTime()); 428 | div_name.concat("-div"); 429 | 430 | /* to-do: this is a workaround, try to fix it with css only */ 431 | if ((config.width == '0') && (config.height == '0')) { 432 | auto = true; 433 | } 434 | 435 | var clickScript = String.raw` 436 | 460 | `; 461 | 462 | switch (config.layout) { 463 | 464 | case 'adjust': { 465 | HTML = String.raw` 466 |
467 | 472 |
`; 473 | break; 474 | } 475 | 476 | case 'center': { 477 | HTML = String.raw` 478 |
`; 488 | /*HTML = String.raw` 489 |
490 | 495 |
`;*/ 496 | break; 497 | } 498 | 499 | case 'expand': { 500 | HTML = String.raw` 501 |
`; 510 | break; 511 | } 512 | 513 | case 'side': { 514 | HTML = String.raw` 515 |
`; 524 | break; 525 | } 526 | 527 | default: { 528 | HTML = String.raw` 529 |
530 | 531 | 532 |
`; 533 | node.warn("Invalid Layout - " + layout); 534 | break; 535 | } 536 | } 537 | return HTML.concat(clickScript); 538 | } 539 | 540 | /** 541 | * Check for that we have a config instance and that our config instance has a group selected, otherwise report an error 542 | * @param {string} path - the layout configuration fo the media to be shown 543 | * @param {boolean} controls - 'true' if controls must be shown, 'false' if mustn't 544 | * @param {boolean} onstart - 'true' if video must start when load , 'false' if mustn't 545 | * @param {boolean} loop - 'true' if video must loop when finilshed, 'false' if mustn't 546 | * @param {boolean} muted whether the video should start muted 547 | */ 548 | function processVideoLayout(path, controls, onstart, loop, muted) { 549 | var controls_string = ""; 550 | var onstart_string = ""; 551 | var loop_string = ""; 552 | var muted_string = ""; 553 | 554 | if (controls) { controls_string = " controls" }; 555 | if (onstart) { onstart_string = " autoplay" }; 556 | if (loop) { loop_string = " loop=\"true\"" }; 557 | if (muted) { muted_string = " muted" }; 558 | 559 | var video_name = `video_${(Math.random() * 0xffffffff).toString(16)}` 560 | var HTML = String.raw` 561 | 579 | 580 | `; 585 | 586 | return HTML; 587 | } 588 | 589 | /** 590 | * Check for that we have a config instance and that our config instance has a group selected, otherwise report an error 591 | * @param {object} url - The file path 592 | * @returns {string} 'img' if the file has a image type and 'video' if the file has a video type 593 | */ 594 | function getFileType(url) { 595 | var type = String(mime.lookup(url)); 596 | 597 | if (type.includes("image")) { 598 | return "image"; 599 | } else if (type.includes("video")) { 600 | return "video"; 601 | } 602 | } 603 | 604 | /** 605 | * Check for that we have a config instance and that our config instance has a group selected, otherwise report an error 606 | * @param {object} config - The file path 607 | * @param {string} path - The file's extension 608 | * @param {string} type - The image layout to be set 609 | * @returns {string} Widget's HTML snippet 610 | */ 611 | function HTML(path, type, config) { 612 | var raw; 613 | 614 | if ((/(image)$/i).test(type)) { 615 | raw = processImageLayout(config, path); 616 | } else if ((/(video)$/i).test(type)) { 617 | raw = processVideoLayout(path, config.showcontrols, config.onstart, config.loop, config.muted); 618 | } 619 | 620 | return raw; 621 | } 622 | 623 | // creates the widget 624 | var done = ui.addWidget({ 625 | // define the widger properties 626 | node: node, 627 | width: config.width, 628 | height: config.height, 629 | format: '
', 630 | templateScope: "local", 631 | group: config.group, 632 | order: config.order, 633 | emitOnlyNewValues: false, 634 | forwardInputMessages: false, 635 | // define the functions of the widget 636 | convertBack: function (value) { 637 | return value; 638 | }, 639 | beforeEmit: function (msg, value) { 640 | let retVal = { msg }; 641 | 642 | // process current layout 643 | if (msg.layout !== undefined) { 644 | layout = msg.layout; 645 | updateHTML = true; 646 | } 647 | 648 | // process current media 649 | if (typeof msg.src === 'string') { 650 | updateHTML = true; 651 | 652 | link = msg.src; 653 | } else if (msg.payload) { 654 | updateHTML = true; 655 | 656 | if (typeof msg.payload == 'string') { 657 | link = msg.payload ? urlPath.join(httpRoot, 'uimedia', msg.payload) : ''; 658 | } else if (Buffer.isBuffer(msg.payload)) { 659 | // we need the mimetype to be explicitly defined when the payload is a Buffer 660 | if (typeof msg.mimetype !== 'string') { 661 | node.error(RED._("ui_media.error.no-mimetype")); 662 | return; 663 | } 664 | link = `data:${msg.mimetype};base64,${msg.payload.toString('base64')}`; 665 | } else if (msg.payload.category && msg.payload.name) { 666 | link = urlPath.join(httpRoot, 'uimedia', msg.payload.category, msg.payload.name); 667 | } 668 | 669 | // process media configuration 670 | if (msg.payload.onstart !== undefined) config.onstart = !!JSON.parse(msg.payload.onstart); 671 | if (msg.payload.loop !== undefined) config.loop = !!JSON.parse(msg.payload.loop); 672 | if (msg.payload.controls !== undefined) config.showcontrols = !!JSON.parse(msg.payload.controls); 673 | if (msg.payload.muted !== undefined) config.muted = !!JSON.parse(msg.payload.muted); 674 | } 675 | 676 | if (updateHTML) { 677 | let fileType = (typeof msg.mimetype === 'string') ? msg.mimetype.split('/')[0] : getFileType(link); 678 | if (link && !fileType) node.error(RED._("ui_media.error.undefined-media-type")); 679 | 680 | retVal.format = HTML(link, fileType, config); 681 | updateHTML = false; 682 | } 683 | 684 | return retVal; 685 | }, 686 | beforeSend: function (msg, orig) { 687 | if (orig) { 688 | // if the payload contains the desired hasOwnProperty 689 | if ('clientX' in orig.msg.payload) { 690 | return orig.msg; 691 | } 692 | } 693 | }, 694 | initController: function ($scope, events) { 695 | $scope.value = false; 696 | $scope.click = function (val) { 697 | $scope.send({ payload: val }); 698 | }; 699 | } 700 | 701 | }); 702 | node.emit('input', {}); //triggers the configured media 703 | node.on("close", done); 704 | } 705 | RED.nodes.registerType("ui_media", ImageNode); 706 | }; 707 | 708 | 709 | // list the files inside a directory 710 | function listFilesDir(pathDir, cb) { 711 | 712 | let callbackDone = false; 713 | 714 | function doCallback(err, data) { 715 | if (callbackDone) { 716 | return; 717 | } 718 | callbackDone = true; 719 | cb(err, data); 720 | } 721 | 722 | let medias = []; 723 | 724 | fs.readdir(pathDir, 'utf-8', (err, files) => { 725 | 726 | if (err) { 727 | doCallback(err, null); 728 | return; 729 | } 730 | 731 | let countFiles = files.length; 732 | 733 | if (countFiles === 0) { 734 | doCallback(null, medias); 735 | return; 736 | } 737 | 738 | files.forEach(file => { 739 | 740 | fs.stat(path.join(pathDir, file), (err, stat) => { 741 | 742 | countFiles--; 743 | 744 | if (err) { 745 | doCallback(err, null); 746 | return; 747 | } 748 | 749 | if (!stat.isDirectory()) { 750 | medias.push(file); 751 | } 752 | 753 | if (countFiles === 0) { 754 | doCallback(null, medias); 755 | } 756 | 757 | }); 758 | }); 759 | }); 760 | } 761 | 762 | // inspired on https://github.com/parshap/node-sanitize-filename 763 | const sanitizeInput = (function (str) { 764 | const illegalRe = /[\/\?<>\\:\*\|":]/g; 765 | const controlRe = /[\x00-\x1f\x80-\x9f]/g; 766 | const reservedRe = /^\.+$/; 767 | const windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; 768 | const windowsTrailingRe = /[\. ]+$/; 769 | 770 | const replacement = '_'; 771 | 772 | //return function sanitizeInput(str) { 773 | 774 | return (str || "") 775 | .replace(illegalRe, replacement) 776 | .replace(controlRe, replacement) 777 | .replace(reservedRe, replacement) 778 | .replace(windowsReservedRe, replacement) 779 | .replace(windowsTrailingRe, replacement); 780 | //} 781 | }); 782 | -------------------------------------------------------------------------------- /ui_media.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 523 | 524 | 723 | 724 | 864 | --------------------------------------------------------------------------------