3 * Copyright (C) 2015 "IoT.bzh"
4 * Author "Fulup Ar Foll"
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.
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..
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
26 * Bugs: zip file sent even when flag as invalid
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>' +
40 var tmplModal = '<span class="modal-text">Upload Application <b>{{appname}}</b> ?</span>' +
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> ' +
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();
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);
59 // Upload is finish let's notify controler callback
60 xmlReq.onload = function () {
61 scope.divElem.addClass ("success");
62 scope.divElem.removeClass ("error");
64 status : xmlReq.status,
65 headers: xmlReq.getAllResponseHeaders()
67 scope.callback (response);
70 xmlReq.onerror = function () {
71 scope.divElem.addClass ("error");
72 scope.divElem.removeClass ("success");
75 xmlReq.onabort = function () {
76 scope.divElem.addClass ("error");
77 scope.divElem.removeClass ("success");
79 status : xmlReq.status,
80 headers: xmlReq.getAllResponseHeaders()
82 scope.callback (response);
85 this.postfile = function(posturl) {
86 // everything looks OK let's Post it
87 xmlReq.open("POST", posturl , true);
91 for (var i = 0; i < files.length; i++) {
93 console.log ("filetype=%s",this.file.type );
94 // Unknow Type !!! if (!this.file.type.match(scope.mimetype)) continue;
96 console.log ("Selected file=" + this.file.name + " size="+ this.file.size/1024 + " Type="+ this.file.type);
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
105 // This is not an uploadable file
106 if(isNaN(this.file.size)) {
107 scope.thumbnail = scope.isnotvalid;
108 scope.$apply('thumbnail');
112 this.basename= this.file.name.split('/').reverse()[0];
113 //scope.imgElem[0].file = this.file;
115 // If File is an image let display it now
117 var reader = new FileReader();
118 reader.readAsArrayBuffer(this.file);
119 reader.onload = fileCB;
121 // if everything is OK let's add file to xform
122 xform.append(scope.name, this.file, this.file.name);
126 angular.module('UploadFiles',['AppConfig', 'ModalNotification', 'RangeSlider'])
128 .directive('uploadAppli', function(AppConfig, JQemu, Notification, ModalFactory, $timeout) {
129 function mymethods(scope, elem, attrs) {
131 // get widget image handle from template
132 scope.inputElem = elem.find('input');
133 scope.divElem = elem.find('div');
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!!!
140 // Slider control handle registration after creation
141 scope.SliderInitCB=function (slider) {
142 scope.slider= slider;
145 // Upload is delegated to a shared function
146 scope.UpLoadFile=function (files) {
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);
155 scope.modal.deactivate();
156 $timeout (function() {scope.modal.destroy();}, 1000);
159 var refused = function() {
160 console.log ("Modal Refused");
161 scope.modal.deactivate();
162 $timeout (function() {scope.modal.destroy();}, 1000);
165 var readerCB = function (upload) {
167 var zipapp = new JSZip (upload.target.result);
168 var thumbnail = zipapp.file("icon_128.png");
170 // Check is we have a thumbnail within loaded Zipfile
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
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"}));
179 // reference http://foundation.zurb.com/apps/docs/#!/angular-modules
181 animationIn: 'slideInFromTop',
186 appname: handle.basename
187 }, template: tmplModal
189 // Popup Modal to render application data
190 scope.modal = new ModalFactory(config);
191 scope.modal.activate ();
195 // Load file within browser and if OK call readerCB
196 handle = new LoadFileSvc (scope, files, readerCB);
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';
208 if (attrs.thumbnail) scope.isnotvalid= AppConfig.paths[scope.category] + attrs.isnotvalid;
209 else scope.isnotvalid=AppConfig.paths[scope.category] + 'isnotvalid.png';
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;
215 if (!attrs.posturl) throw new TypeError('file-upload %s posturl=/api/xxxx/xxxx required', scope.attrs);
228 console.log ("UploadFile Loaded");