forked from mailru/FileAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileAPI.Flash.js
More file actions
579 lines (477 loc) · 14 KB
/
Copy pathFileAPI.Flash.js
File metadata and controls
579 lines (477 loc) · 14 KB
1
2
3
4
5
6
7
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/**
* FileAPI fallback to Flash
*
* @flash-developer "Vladimer Demidov" <v.demidov@corp.mail.ru>
*/
(function (api, window, document){
api.support.flash = (function (){
var nav = window.navigator, mime = nav.mimeTypes, has = false;
if( nav.plugins && typeof nav.plugins['Shockwave Flash'] == 'object' ){
has = nav.plugins['Shockwave Flash'].description && !(mime && mime['application/x-shockwave-flash'] && !mime['application/x-shockwave-flash'].enabledPlugin);
}
else {
try {
has = !!(window.ActiveXObject && new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
}
catch(er){ /*__*/ }
}
return has;
})();
if( (0 || !api.support.html5) && api.support.flash ) (function (){
var
_attr = api.uid()
, _retry = 0
, _files = {}
, _toInt = function (val){ return parseInt(val, 10); }
, _rhttp = /^https?:/i
, flash = {
_fn: {},
/**
* Initialization & preload flash object
*/
init: function (){
var child = document.body && document.body.firstChild;
if( child ){
do {
if( child.nodeType == 1 ){
api.log('FlashAPI.Flash.inited');
var dummy = document.createElement('div');
_css(dummy, {
top: 1
, right: 1
, width: 5
, height: 5
, position: 'absolute'
});
child.parentNode.insertBefore(dummy, child);
flash.pingUrl = flash.pingUrl || (location.protocol+'//'+location.host);
flash.publish(dummy, _attr);
return;
}
}
while( child = child.nextSibling )
}
if( _retry < 10 ){
setTimeout(flash.init, ++_retry*50);
}
},
/**
* Publish flash-object
*
* @param {HTMLElement} el
* @param {String} id
*/
publish: function (el, id){
el.innerHTML = _makeFlashHTML({
id: id
, src: _geturl(api.staticPath + 'FileAPI.flash.swf?r=' + api.build)
// , src: _geturl('http://v.demidov.boom.corp.mail.ru/uploaderfileapi/FlashFileAPI.swf?1')
, wmode: 'transparent'
, flashvars: 'callback=FileAPI.Flash.event'
+ '&flashId='+ id
+ '&storeKey='+ navigator.userAgent.match(/\d/ig).join('') +'_'+ api.build
+ (flash.isReady || !flash.pingUrl ? '' : '&ping='+flash.pingUrl)
});
},
ready: function (){
flash.ready = api.F;
flash.isReady = true;
flash.patch();
api.event.on(document, 'mouseover', flash.mouseover);
api.event.on(document, 'click', function (evt){
if( flash.mouseover(evt) ){
evt.preventDefault
? evt.preventDefault()
: (evt.returnValue = true)
;
}
});
},
getWrapper: function (node){
do {
if( /js-fileapi-wrapper/.test(node.className) ){
return node;
}
}
while( (node = node.parentNode) && (node !== document.body) );
},
mouseover: function (evt){
var target = api.event.fix(evt).target;
if( /input/i.test(target.nodeName) && target.type == 'file' ){
var state = target.getAttribute(_attr);
if( state == 'n' ){
// publish fail
return false;
}
else if( state != 'y' ){
target.setAttribute(_attr, 'n');
var
dummy = document.createElement('div')
, wrapper = flash.getWrapper(target)
;
if( !wrapper ){
api.log('flash.mouseover.error: js-fileapi-wrapper not found');
return
}
_css(dummy, {
top: 0
, left: 0
, width: target.offsetWidth + 100
, height: target.offsetHeight + 100
, position: 'absolute'
// , background: 'red'
});
wrapper.appendChild(dummy);
flash.publish(dummy, api.uid());
target.setAttribute(_attr, 'y');
}
return true;
}
},
event: function (evt){
var type = evt.type;
if( type == 'ready' ){
api.log('Flash.event.'+evt.type+':', evt);
flash.ready();
setTimeout(function (){ flash.mouseenter(evt); }, 50);
return true;
}
else if( type === 'ping' ){
api.log('(flash -> js).ping:', [evt.status, evt.savedStatus], evt.error);
}
else if( type === 'log' ){
api.log('(flash -> js).log:', evt.target);
}
else if( type in flash ) setTimeout(function (){
api.log('Flash.event.'+evt.type+':', evt);
flash[type](evt);
}, 1);
},
mouseenter: function (evt){
var node = flash.getInput(evt.flashId);
if( node ){
// Set multiple mode
flash.cmd(evt, 'multiple', node.getAttribute('multiple') !== null);
// Set files filter
flash.cmd(evt, 'accept', (node.getAttribute('accept') || '*').replace(/\./g, ''));
}
},
get: function (id){
return document[id] || window[id] || document.embeds[id];
},
getInput: function (id){
try {
var node = flash.getWrapper(flash.get(id));
if( node ) return node.getElementsByTagName('input')[0];
} catch (e){ }
},
select: function (evt){
var
inp = flash.getInput(evt.flashId)
, uid = api.uid(inp)
, files = evt.target.files
, event
;
api.each(files, function (file){
api.checkFileObj(file);
});
_files[uid] = files;
if( document.createEvent ){
event = document.createEvent('Event');
event.initEvent ('change', true, false);
inp.dispatchEvent(event)
}
else if( document.createEventObject ){
event = document.createEventObject();
inp.fireEvent('onchange', event)
}
},
cmd: function (id, name, data, last){
try {
api.log('(js -> flash).'+name+':', data);
return flash.get(id.flashId || id).cmd(name, data);
} catch (e){
api.log('(js -> flash).onError:', e);
if( !last ){
// try again
setTimeout(function (){ flash.cmd(id, name, data, true); }, 50);
}
}
},
patch: function (){
api.flashEngine =
api.support.transform = true;
// FileAPI
_inherit(api, {
getFiles: function (input, filter, callback){
if( callback ){
api.filterFiles(api.getFiles(input), filter, callback);
return null;
}
var files = api.isArray(input) ? input : _files[api.uid(input.target || input.srcElement || input)];
if( !files ){
// Файлов нету, вызываем родительский метод
return this.parent.apply(this, arguments);
}
if( filter ){
filter = api.getFilesFilter(filter);
files = api.filter(files, function (file){ return filter.test(file.name); });
}
return files;
},
getInfo: function (file, fn){
if( _isHtmlFile(file) ){
this.parent.apply(this, arguments);
}
else if( file.info ){
fn(false, file.info);
}
else {
flash.cmd(file, 'getFileInfo', {
id: file.id
, callback: _wrap(function _(err, info){
_unwrap(_);
fn(err, file.info = info);
})
});
}
}
});
// FileAPI.Image
api.support.transform = true;
_inherit(FileAPI.Image.prototype, {
_load: function (file, fn){
api.log('FileAPI.Image._load:', file);
if( _isHtmlFile(file) ){
this.parent.apply(this, arguments);
}
else {
var _this = this;
api.getInfo(file, function (err, info){
fn.call(_this, err, file);
});
}
},
_apply: function (file, fn){
api.log('FileAPI.Image._apply:', file);
if( _isHtmlFile(file) ){
this.parent.apply(this, arguments);
}
else {
var m = this.getMatrix(file.info);
flash.cmd(file, 'imageTransform', {
id: file.id
, matrix: m
, callback: _wrap(function _(err, base64){
_unwrap(_);
if( err ){
fn(err);
}
else if( !api.support.dataURI || base64.length > 3e4 ){
_makeFlashImage({
width: !(m.deg % 180) ? m.dw : m.dh
, height: (m.deg % 180) ? m.dw : m.dh
}, base64, fn);
}
else {
var img = new Image;
img.src = 'data:'+ file.type +';base64,'+ base64;
api.event.one(img, 'error abort load', function (evt){
fn(evt.type != 'load' && evt.type, img);
img = null;
});
}
})
});
}
},
toData: function (fn){
var data = this.data;
if( _isHtmlFile(data) ){
this.parent.apply(this, arguments);
}
else {
fn.call(this, !data.info, {
id: data.id
, flashId: data.flashId
, name: data.name
, type: data.type
, matrix: this.getMatrix(data.info)
});
}
}
});
// FileAPI.Form
_inherit(api.Form.prototype, {
toData: function (fn){
var items = this.items, i = items.length;
for( ; i--; ){
if( items[i].file && _isHtmlFile(items[i].blob) ){
return this.parent.apply(this, arguments);
}
}
api.log('flash.Form.toData');
fn(items);
}
});
// FileAPI.XHR
_inherit(api.XHR.prototype, {
_send: function (options, formData){
if(
formData.nodeName
|| formData.append && api.support.html5
|| api.isArray(formData) && (typeof formData[0] === 'string')
){
// HTML5, Multipart or IFrame
return this.parent.apply(this, arguments);
}
var
data = {}
, files = {}
, _this = this
, flashId
, fileId
;
api.each(formData, function (item){
if( item.file ){
files[item.name] = item = item.blob;
fileId = item.id;
flashId = item.flashId;
}
else {
data[item.name] = item.blob;
}
});
api.log('flash.XHR._send:', flashId, fileId, files);
this.xhr = {
headers: {},
abort: function (){ flash.cmd(flashId, 'abort', fileId); },
getResponseHeader: function (name){ return this.headers[name]; },
getAllResponseHeaders: function (){ return this.headers; }
};
flash.cmd(flashId, 'upload', {
url: _geturl(options.url)
, data: data
, files: files
, headers: options.headers
, callback: _wrap(function upload(evt){
var type = evt.type, result = evt.result;
api.log('flash.upload.'+type+':', evt.status, evt);
if( type == 'progress' ){
evt.lengthComputable = true;
options.progress(evt);
}
else if( type == 'complete' ){
_unwrap(upload);
if( typeof result == 'string' ){
_this.responseText = result.replace(/%22/g, "\"").replace(/%5c/g, "\\").replace(/%26/g, "&").replace(/%25/g, "%");
}
_this.end(evt.status || 200);
}
else if( type == 'abort' || type == 'error' ){
_this.end(0, evt.message);
_unwrap(upload);
}
})
});
}
});
}
}
;
function _makeFlashHTML(opts){
return ('<object id="#id#" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%">'
+ '<param name="movie" value="#src#" />'
+ '<param name="flashvars" value="#flashvars#" />'
+ '<param name="swliveconnect" value="true" />'
+ '<param name="allowscriptaccess" value="always" />'
+ '<param name="allownetworking" value="all" />'
+ '<param name="menu" value="false" />'
+ '<param name="wmode" value="#wmode#" />'
+ '<embed flashvars="#flashvars#" swliveconnect="true" allownetworking="all" allowscriptaccess="always" name="#id#" src="#src#" width="100%" height="100%" menu="false" wmode="transparent" type="application/x-shockwave-flash"></embed>'
+ '</object>').replace(/#(\w+)#/ig, function (a, name){ return opts[name]; })
;
}
function _css(el, css){
if( el && el.style ){
var key, val;
for( key in css ){
val = css[key];
if( typeof val == 'number' ) val += 'px';
try { el.style[key] = val; } catch (e) {}
}
}
}
function _inherit(obj, methods){
api.each(methods, function (fn, name){
var prev = obj[name];
obj[name] = function (){
this.parent = prev;
return fn.apply(this, arguments);
};
});
}
function _isHtmlFile(file){
return file && !file.flashId;
}
function _wrap(fn){
var id = fn.wid = api.uid();
flash._fn[id] = fn;
return 'FileAPI.Flash._fn.'+id;
}
function _unwrap(fn){
delete flash._fn[fn.wid];
}
function _geturl(url){
if( !_rhttp.test(url) ){
if( /^\.\//.test(url) || '/' != url.charAt(0) ){
url = location.pathname +'/'+ url.substr(RegExp.$1 ? 2 : 0);
}
if( '//' != url.substr(0, 2) ){
url = location.hostname +'/'+ url;
}
if( !_rhttp.test(url) ){
url = location.protocol +'//'+ url;
}
}
return url;
}
function _makeFlashImage(opts, base64, fn){
var _id, flashId = api.uid(), el = document.createElement('ins');
for( _id in opts ){
el.setAttribute('data-img-' + _id, opts[_id]);
}
_css(el, opts);
el.innerHTML = _makeFlashHTML({
id: flashId
, src: api.staticPath + 'FileAPI.flash.image.swf?r=' + api.build
, wmode: 'opaque'
, flashvars: 'callback='+_wrap(function _setData(evt){
try {
var img = flash.get(flashId);
img.setImage(base64);
img = el = null;
_unwrap(_setData);
} catch (e){
if( !evt || evt.type == 'ready' ){
clearTimeout(_id);
_id = setTimeout(_setData, 50);
}
}
return true;
})
});
fn(false, el);
}
// @export
api.Flash = flash;
// Check dataURI support
var dataURICheck = new Image;
api.event.one(dataURICheck, 'error load', function (){
api.support.dataURI = !(dataURICheck.width != 1 || dataURICheck.height != 1);
dataURICheck = null;
flash.init();
});
dataURICheck.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
})();
})(FileAPI, this, document);