Cosmetic fixes
[src/app-framework-demo.git] / afm-client / app / Frontend / widgets / FormInput / UploadAppli.js
1
2 /* 
3  * Copyright (C) 2015 "IoT.bzh"
4  * Author "Fulup Ar Foll"
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details..
15  * 
16  * Reference:
17  *   https://developer.mozilla.org/en/docs/Web/API/FileReader 
18  *   https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Using_hidden_file_input_elements_using_the_click%28%29_method
19  *   https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
20  *   https://www.terlici.com/2015/05/16/uploading-files-locally.html
21  *   https://github.com/nervgh/angular-file-upload/blob/master/src/services/FileUploader.js
22  *   https://stuk.github.io/jszip/documentation/howto/read_zip.html
23  *   http://onehungrymind.com/zip-parsing-jszip-angular/
24  *   http://stackoverflow.com/questions/15341912/how-to-go-from-blob-to-arraybuffer
25  *   
26  *   Bugs: zip file sent even when flag as invalid 
27  */
28
29  
30
31 (function() {
32 'use strict';
33
34 var tmplAppli = '<input type="file" name="{{name}}-input" onchange="angular.element(this).scope().UpLoadFile(this.files)" accept="{{mimetype}}" style="display:none">'+
35             '<div class="upload-file" ng-click="imgClicked()">' +
36             '<i class="{{icon}}"></i> <span>{{label}}</span>' +
37             '<range-slider ng-show="!noslider" id="{{name}}-slider" automatic=true inithook="SliderInitCB"></range-slider>' +
38             '</div>';
39     
40 var tmplModal = '<span class="modal-text">Upload Application <b>{{appname}}</b> ?</span>' +
41             '<div>'+
42             '<img ng-src="{{appicon}}">' +
43             '<submit-button icon="fi-x" label="Cancel" clicked="refused"></submit-button>'+
44             '<submit-button icon="fi-like" label="Install" clicked="accepted"></submit-button> ' +
45             '</div>';
46     
47
48 // Service Create xform insert files in and Post it to url
49 function LoadFileSvc (scope, files, fileCB) {
50     var xmlReq = new XMLHttpRequest();
51     var xform  = new FormData();
52     
53     // Update slider during Upload
54     xmlReq.upload.onprogress = function (event) {
55         var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);
56         if (scope.slider) scope.slider.setValue (progress);
57     };
58
59     // Upload is finish let's notify controler callback
60     xmlReq.onload = function () {
61         scope.divElem.addClass ("success");
62         scope.divElem.removeClass ("error");
63         var response ={
64             status : xmlReq.status,
65             headers: xmlReq.getAllResponseHeaders() 
66         };
67         scope.callback (response);
68     };
69
70     xmlReq.onerror = function () {
71         scope.divElem.addClass ("error");
72         scope.divElem.removeClass ("success");
73     };
74
75     xmlReq.onabort = function () {
76         scope.divElem.addClass ("error");
77         scope.divElem.removeClass ("success");
78         var response ={
79             status : xmlReq.status,
80             headers: xmlReq.getAllResponseHeaders() 
81         };
82         scope.callback (response);
83     };
84     
85     this.postfile = function(posturl) { 
86         // everything looks OK let's Post it
87         xmlReq.open("POST", posturl , true);
88         xmlReq.send(xform);
89     };
90
91     for (var i = 0; i < files.length; i++) {
92         this.file = files[i];
93         console.log ("filetype=%s",this.file.type );
94         // Unknow Type !!! if (!this.file.type.match(scope.mimetype)) continue;
95
96         console.log ("Selected file=" + this.file.name + " size="+ this.file.size/1024 + " Type="+ this.file.type);
97
98         // File to upload is too big
99         if (this.file.size > scope.maxsize*1024) {
100             scope.thumbnail = scope.istoobig; // warning if image path is wrong nothing happen
101             scope.$apply('thumbnail'); // we short-circuit Angular resync Image
102             return;
103         }
104
105         // This is not an uploadable file
106         if(isNaN(this.file.size)) {
107             scope.thumbnail = scope.isnotvalid; 
108             scope.$apply('thumbnail');
109             return;
110         }
111
112         this.basename= this.file.name.split('/').reverse()[0];
113         //scope.imgElem[0].file = this.file;
114
115         // If File is an image let display it now
116         if (fileCB) {
117             var reader = new FileReader();
118             reader.readAsArrayBuffer(this.file);
119             reader.onload = fileCB;
120         } 
121         // if everything is OK let's add file to xform
122         xform.append(scope.name, this.file, this.file.name);
123     }
124 }
125
126 angular.module('UploadFiles',['AppConfig', 'ModalNotification', 'RangeSlider'])
127
128 .directive('uploadAppli', function(AppConfig,  JQemu, Notification, ModalFactory, $timeout) {
129     function mymethods(scope, elem, attrs) {
130         
131         // get widget image handle from template
132         scope.inputElem  = elem.find('input');
133         scope.divElem    = elem.find('div');
134         
135         // Image was ckick let's simulate an input (file) click
136         scope.imgClicked = function () {
137             scope.inputElem[0].click(); // Warning Angular TriggerEvent does not work!!!
138         };
139         
140         // Slider control handle registration after creation
141         scope.SliderInitCB=function (slider) {
142            scope.slider= slider; 
143         };
144         
145         // Upload is delegated to a shared function
146         scope.UpLoadFile=function (files) {
147             var handle; 
148             var appicon;
149             
150             var accepted = function() {
151                 console.log ("Modal Accepted");
152                 // This Looks OK let's Post Xform/File
153                 handle.postfile(attrs.posturl + "?token=" + AppConfig.session.token);
154
155                 scope.modal.deactivate();
156                 $timeout (function() {scope.modal.destroy();}, 1000);
157             };
158             
159             var refused = function() {
160                 console.log ("Modal Refused");
161                 scope.modal.deactivate();
162                 $timeout (function() {scope.modal.destroy();}, 1000);
163             };
164                        
165             var readerCB = function (upload) {
166
167                 var zipapp = new JSZip (upload.target.result);
168                 var thumbnail = zipapp.file("icon_128.png");
169                 
170                 // Check is we have a thumbnail within loaded Zipfile
171                 if (!thumbnail) {
172                     console.log ("This is not a valid Application Framework APP");
173                     scope.thumbnail=AppConfig.paths[scope.category] + 'isnotvalid.png';
174                     scope.$apply('thumbnail'); // we short-circuit Angular resync Image
175                 } else {
176                     //scope.imgElem[0].src = window.URL.createObjectURL(new Blob([thumbnail.asArrayBuffer()], {type: "image"}));
177                     appicon = window.URL.createObjectURL(new Blob([thumbnail.asArrayBuffer()], {type: "image"}));
178                     
179                     // reference http://foundation.zurb.com/apps/docs/#!/angular-modules
180                     var config = {
181                         animationIn: 'slideInFromTop',
182                         contentScope: {
183                             accepted: accepted,
184                             refused:  refused,
185                             appicon:  appicon,
186                             appname:  handle.basename
187                         }, template:  tmplModal
188                     }; 
189                     // Popup Modal to render application data
190                     scope.modal = new ModalFactory(config);
191                     scope.modal.activate ();
192                 }
193             };
194             
195             // Load file within browser and if OK call readerCB
196             handle = new LoadFileSvc (scope, files, readerCB);
197         };
198
199         // Initiallize default values from attributes values
200         scope.name= attrs.name || 'appli';
201         scope.category= attrs.category  || 'appli';
202         scope.mimetype= (attrs.accept || '.wgt');
203         scope.maxsize = attrs.maxsize || 100000; // default max size 100MB
204         scope.regexp  = new RegExp (attrs.accept+ '.*','i');
205         scope.icon    = attrs.icon || 'fi-upload';
206         scope.label   = attrs.label || 'Upload';
207         
208         if (attrs.thumbnail) scope.isnotvalid= AppConfig.paths[scope.category] +  attrs.isnotvalid;
209         else  scope.isnotvalid=AppConfig.paths[scope.category] + 'isnotvalid.png';
210
211         if (attrs.istoobig) scope.istoobig= AppConfig.paths[scope.category] +  attrs.istoobig;
212         else  scope.istoobig=AppConfig.paths[scope.category] + 'istoobig.png';
213         scope.noslider = attrs.noslider || false;
214
215         if (!attrs.posturl) throw new TypeError('file-upload %s posturl=/api/xxxx/xxxx required', scope.attrs);            
216     }
217     return {
218         restrict: 'E',
219         template: tmplAppli,
220         link: mymethods,
221         scope: {
222             callback : '='
223         }
224     };
225     
226 });
227
228 console.log ("UploadFile Loaded");
229 })();