d18f620b450e79394fab0c9de4c3789636609629
[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
127 angular.module('UploadFiles',['AppConfig', 'ModalNotification', 'RangeSlider'])
128
129 .directive('uploadAppli', function(AppConfig,  JQemu, Notification, ModalFactory, $timeout) {
130     function mymethods(scope, elem, attrs) {
131         
132         // get widget image handle from template
133         scope.inputElem  = elem.find('input');
134         scope.divElem    = elem.find('div');
135         
136         // Image was ckick let's simulate an input (file) click
137         scope.imgClicked = function () {
138             scope.inputElem[0].click(); // Warning Angular TriggerEvent does not work!!!
139         };
140         
141         // Slider control handle registration after creation
142         scope.SliderInitCB=function (slider) {
143            scope.slider= slider; 
144         };
145         
146         // Upload is delegated to a shared function
147         scope.UpLoadFile=function (files) {
148             var handle; 
149             var appicon;
150             
151             var accepted = function() {
152                 console.log ("Modal Accepted");
153                 // This Looks OK let's Post Xform/File
154                 handle.postfile(attrs.posturl + "?token=" + AppConfig.session.token);
155
156                 scope.modal.deactivate();
157                 $timeout (function() {scope.modal.destroy();}, 1000);
158             };
159             
160             var refused = function() {
161                 console.log ("Modal Refused");
162                 scope.modal.deactivate();
163                 $timeout (function() {scope.modal.destroy();}, 1000);
164             };
165                        
166             var readerCB = function (upload) {
167
168                 var zipapp = new JSZip (upload.target.result);
169                 var thumbnail = zipapp.file("icon_128.png");
170                 
171                 // Check is we have a thumbnail within loaded Zipfile
172                 if (!thumbnail) {
173                     console.log ("This is not a valid Application Framework APP");
174                     scope.thumbnail=AppConfig.paths[scope.category] + 'isnotvalid.png';
175                     scope.$apply('thumbnail'); // we short-circuit Angular resync Image
176                 } else {
177                     //scope.imgElem[0].src = window.URL.createObjectURL(new Blob([thumbnail.asArrayBuffer()], {type: "image"}));
178                     appicon = window.URL.createObjectURL(new Blob([thumbnail.asArrayBuffer()], {type: "image"}));
179                     
180                     // reference http://foundation.zurb.com/apps/docs/#!/angular-modules
181                     var config = {
182                         animationIn: 'slideInFromTop',
183                         contentScope: {
184                             accepted: accepted,
185                             refused:  refused,
186                             appicon:  appicon,
187                             appname:  handle.basename
188                         }, template:  tmplModal
189                     }; 
190                     // Popup Modal to render application data
191                     scope.modal = new ModalFactory(config);
192                     scope.modal.activate ();
193                 }
194             };
195             
196             // Load file within browser and if OK call readerCB
197             handle = new LoadFileSvc (scope, files, readerCB);
198         };
199
200         // Initiallize default values from attributes values
201         scope.name= attrs.name || 'appli';
202         scope.category= attrs.category  || 'appli';
203         scope.mimetype= (attrs.accept || '.wgt');
204         scope.maxsize = attrs.maxsize || 100000; // default max size 100MB
205         scope.regexp  = new RegExp (attrs.accept+ '.*','i');
206         scope.icon    = attrs.icon || 'fi-upload';
207         scope.label   = attrs.label || 'Upload';
208         
209         if (attrs.thumbnail) scope.isnotvalid= AppConfig.paths[scope.category] +  attrs.isnotvalid;
210         else  scope.isnotvalid=AppConfig.paths[scope.category] + 'isnotvalid.png';
211
212         if (attrs.istoobig) scope.istoobig= AppConfig.paths[scope.category] +  attrs.istoobig;
213         else  scope.istoobig=AppConfig.paths[scope.category] + 'istoobig.png';
214         scope.noslider = attrs.noslider || false;
215
216         if (!attrs.posturl) throw new TypeError('file-upload %s posturl=/api/xxxx/xxxx required', scope.attrs);            
217     }
218     return {
219         restrict: 'E',
220         template: tmplAppli,
221         link: mymethods,
222         scope: {
223             callback : '='
224         }
225     };
226     
227 });
228
229 console.log ("UploadFile Loaded");
230 })();