9952a51e6fe2bfebcdc249996b7bf3d201932e95
[lhc/web/wiklou.git] / js2 / mwEmbed / libAddMedia / mvFirefogg.js
1 /* adds firefogg support.
2 * autodetects: new upload api or old http POST.
3 */
4
5 loadGM({
6 "fogg-select_file" : "Select file",
7 "fogg-select_new_file" : "Select new file",
8 "fogg-select_url" : "Select URL",
9 "fogg-save_local_file" : "Save Ogg",
10 "fogg-check_for_fogg" : "Checking for Firefogg <blink>...<\/blink>",
11 "fogg-installed" : "Firefogg is installed",
12 "fogg-for_improved_uplods" : "For improved uploads:",
13 "fogg-please_install" : "<a href=\"$1\">Install Firefogg<\/a>. More <a href=\"http:\/\/commons.wikimedia.org\/wiki\/Commons:Firefogg\">about Firefogg<\/a>",
14 "fogg-use_latest_fox" : "Please first install <a href=\"http:\/\/www.mozilla.com\/en-US\/firefox\/upgrade.html?from=firefogg\">Firefox 3.5<\/a> (or later). <i>Then revisit this page to install the <b>Firefogg<\/b> extension.<\/i>",
15 "fogg-passthrough_mode" : "Your selected file is already Ogg or not a video file",
16 "fogg-transcoding" : "Encoding video to Ogg",
17 "fogg-encoding-done" : "Encoding complete",
18 "fogg-badtoken" : "Token is not valid",
19 "fogg-preview" : "Preview video",
20 "fogg-hidepreview" : "Hide preview"
21 });
22
23 var firefogg_install_links = {
24 'macosx': 'http://firefogg.org/macosx/Firefogg.xpi',
25 'win32': 'http://firefogg.org/win32/Firefogg.xpi',
26 'linux' : 'http://firefogg.org/linux/Firefogg.xpi'
27 };
28
29 var default_firefogg_options = {
30 //what to do when finished uploading
31 'done_upload_cb':false,
32 //if firefoog is enabled
33 'fogg_enabled':false,
34 //the api url to upload to
35 'api_url':null,
36 //the passthrough flag (enables un-modified uploads)
37 'passthrough': false,
38 //if we will be showing the encoder interface
39 'encoder_interface': false,
40 //if we want to limit the library functionality to "only firefoog" (no upload or progress bars)
41 'only_fogg': false,
42
43
44 //callbacks:
45 'new_source_cb': false, //called on source name update passes along source name
46
47 //target control container or form (can't be left null)
48 'selector': '',
49
50 //if not rewriting a form we are encoding local.
51 'form_rewrite': false,
52
53 //taget buttons:
54 'target_btn_select_file': false,
55 'target_btn_select_new_file': false,
56
57 //'target_btn_select_url': false,
58
59 'target_btn_save_local_file': false,
60 'target_input_file_name': false,
61
62
63 //target install descriptions
64 'target_check_for_fogg': false,
65 'target_installed': false,
66 'target_please_install': false,
67 'target_use_latest_fox': false,
68 //status:
69 'target_passthrough_mode':false,
70
71 //if firefogg should take over the form submit action
72 'firefogg_form_action':true,
73
74 //if we should show a preview of encoding progress
75 'show_preview':false,
76 }
77
78
79 var mvFirefogg = function(iObj){
80 return this.init( iObj );
81 }
82 mvFirefogg.prototype = { //extends mvBaseUploadInterface
83
84 min_firefogg_version : '0.9.9.5',
85 fogg_enabled : false, //if firefogg is enabled or not.
86 encoder_settings:{ //@@todo allow server to set this
87 'maxSize' : '400',
88 'videoBitrate' : '544',
89 'audioBitrate' : '96',
90 'noUpscaling' : true
91 },
92 sourceFileInfo: {},
93 ogg_extensions: ['ogg', 'ogv', 'oga'],
94 video_extensions: ['avi', 'mov', 'mp4', 'mp2', 'mpeg', 'mpeg2', 'mpeg4', 'dv', 'wmv'],
95
96 passthrough: false,
97 sourceMode: 'file',
98
99 init: function( iObj ){
100 if(!iObj)
101 iObj = {};
102
103 //if we have no api_url set upload to "post"
104 if(!iObj.api_url)
105 iObj.upload_mode = 'post';
106
107 //inherit iObj properties:
108 for(var i in default_firefogg_options){
109 if(iObj[i]){
110 this[i] = iObj[i];
111 }else{
112 this[i] = default_firefogg_options[i];
113 }
114 }
115 //check if we want to limit the usage:
116 if(!this.only_fogg){
117 var myBUI = new mvBaseUploadInterface( iObj );
118
119 //standard extends code:
120 for(var i in myBUI){
121 if(this[i]){
122 this['pe_'+ i] = myBUI[i];
123 }else{
124 this[i] = myBUI[i];
125 }
126 }
127 }
128
129 if(!this.selector){
130 js_log('firefogg: missing selector ');
131 }
132 },
133 doRewrite:function( callback ){
134 var _this = this;
135 js_log('sel len: ' + this.selector + '::' + $j(this.selector).length + ' tag:'+ $j(this.selector).get(0).tagName);
136 if( $j(this.selector).length >=0 ){
137
138 if( $j(this.selector).get(0).tagName.toLowerCase() == 'input' ){
139 _this.form_rewrite = true;
140 }
141 }
142 //check if we are rewriting an input or a form:
143 if( this.form_rewrite ){
144 this.setupForm();
145 }else{
146 this.doControlHTML();
147 this.doControlBindings();
148 }
149
150 //doRewrite is done:
151 if(callback)
152 callback();
153 },
154 doControlHTML: function( ){
155 var _this = this;
156 var out = '';
157 $j.each(default_firefogg_options, function(target, na){
158 if(target.substring(0, 6)=='target'){
159 //js_log('check for target html: ' + target);
160 //check for the target if missing add to the output:
161 if( _this[target] === false){
162 out += _this.getTargetHtml(target) + ' ';
163 //update the target selector
164 _this[target] = _this.selector + ' .' + target;
165 }
166 }
167 });
168 $j( this.selector ).append( out ).hide();
169 },
170 getTargetHtml:function(target){
171 if( target.substr(7,3)=='btn'){
172 return '<input style="" class="' + target + '" type="button" value="' + gM( 'fogg-' + target.substring(11)) + '"/> ';
173 }else if(target.substr(7,5)=='input'){
174 return '<input style="" class="' + target + '" type="text" value="' + gM( 'fogg-' + target.substring(11)) + '"/> ';
175 }else{
176 return '<div style="" class="' + target + '" >'+ gM('fogg-'+ target.substring(7)) + '</div> ';
177 }
178 },
179 doControlBindings: function(){
180 var _this = this;
181
182 //hide all targets:
183 var hide_target_list='';
184 var coma='';
185 $j.each(default_firefogg_options, function(target, na){
186 if(target.substring(0, 6)=='target'){
187 hide_target_list+=coma + _this[target];
188 coma=',';
189 }
190 });
191 $j( hide_target_list ).hide();
192 //now that the proper set of items has been hiiden show:
193 $j( this.selector ).show();
194
195
196 //hide all but check-for-fogg
197 //check for firefogg
198 if( _this.firefoggCheck() ){
199
200 //if rewriting the form lets keep the text input around:
201 if( _this.form_rewrite )
202 $j(this.target_input_file_name).show();
203
204 //show select file:
205 $j( this.target_btn_select_file ).unbind(
206 ).attr('disabled', false
207 ).css({'display':'inline'}
208 ).click(function(){
209 _this.selectFogg();
210 });
211
212 //also setup the text file display on Click to select file:
213 $j(this.target_input_file_name).unbind().attr('readonly', 'readonly').click(function(){
214 _this.selectFogg();
215 })
216
217 }else{
218 //first check firefox version:
219 if(!( $j.browser.mozilla && $j.browser.version >= '1.9.1' )) {
220 js_log( 'show use latest::' + _this.target_use_latest_fox );
221 if( _this.target_use_latest_fox ){
222 if( _this.form_rewrite )
223 $j( _this.target_use_latest_fox ).prepend( gM('fogg-for_improved_uplods') );
224
225 $j( _this.target_use_latest_fox ).show();
226 }
227 return ;
228 }
229
230 //if rewriting form use upload msg text
231 var upMsg = (_this.form_rewrite) ? gM('fogg-for_improved_uplods') : '';
232 $j( _this.target_please_install ).html( upMsg + gM('fogg-please_install', _this.getOSlink() )).css('padding', '10px').show();
233 }
234 //setup the target save local file bindins:
235 $j( _this.target_btn_save_local_file ).unbind().click(function(){
236 _this.saveLocalFogg();
237 });
238 },
239 /*
240 * returns the firefogg link for your os:
241 */
242 getOSlink:function(){
243 var os_link = false;
244 if(navigator.oscpu){
245 if(navigator.oscpu.search('Linux') >= 0)
246 os_link = firefogg_install_links['linux'];
247 else if(navigator.oscpu.search('Mac') >= 0)
248 os_link = firefogg_install_links['macosx'];
249 else if(navigator.oscpu.search('Win') >= 0)
250 os_link = firefogg_install_links['win32'];
251 }
252 return os_link
253 },
254 firefoggCheck:function(){
255 if(typeof(Firefogg) != 'undefined' && Firefogg().version >= this.min_firefogg_version){
256 this.fogg = new Firefogg();
257 this.fogg_enabled = true;
258 return true;
259 }else{
260 return false;
261 }
262 },
263 //assume input target
264 setupForm: function(){
265 js_log('firefogg::setupForm::');
266 //to parent form setup if we want http updates
267 if( this.form_rewrite ){
268 //do parent form setup:
269 this.pe_setupForm();
270 }
271
272 //check if we have firefogg (if not just add a link and stop proccessing)
273 if( !this.firefoggCheck() ){
274 //add some status indicators if not provided:
275 if(!this.target_please_install){
276 $j(this.selector).after ( this.getTargetHtml('target_please_install') );
277 this.target_please_install = this.selector + ' ~ .target_please_install';
278 }
279 if(!this.target_use_latest_fox){
280 $j(this.selector).after ( this.getTargetHtml('target_use_latest_fox') );
281 this.target_use_latest_fox = this.selector + ' ~ .target_use_latest_fox';
282 }
283 //update download link:
284 this.doControlBindings();
285 return ;
286 }
287
288 //change the file browser to type text: (can't directly change input from "file" to "text" so longer way:
289 var inTag = '<input ';
290 $j.each($j(this.selector).get(0).attributes, function(i, attr){
291 var val = attr.value;
292 if( attr.name == 'type')
293 val = 'text';
294 inTag += attr.name + '="' + val + '" ';
295 });
296 if(!$j(this.selector).attr('style'))
297 inTag += 'style="display:inline" ';
298
299 inTag+= '/><span id="' + $j(this.selector).attr('name') + '_fogg-control"></span>';
300
301 js_log('set input: ' + inTag);
302 $j(this.selector).replaceWith(inTag);
303
304 this.target_input_file_name = 'input[name=' + $j(this.selector).attr('name') + ']';
305 //update the selector to the control target:
306 this.selector = '#' + $j(this.selector).attr('name') + "_fogg-control";
307
308 this.doControlHTML();
309 //check for the other inline status indicator targets:
310
311 //update the bindings:
312 this.doControlBindings();
313 },
314 //do firefogg specific additions:
315 dispProgressOverlay:function(){
316 this.pe_dispProgressOverlay();
317 //if we are uploading video (not in passthrough mode show preview button)
318 if( ! this.encoder_settings['passthrough'] ){
319 this.doPreviewControl();
320 }
321 },
322 doPreviewControl:function(){
323 var _this = this;
324 //prepend preview collapable
325 $j('#upProgressDialog').append(
326 '<div style="clear:both;height:3em"/>'+
327 $j.btnHtml(gM('fogg-preview'), 'fogg_preview', 'triangle-1-e') +
328 '<div style="padding:10px;">' +
329 '<canvas style="margin:auto;" id="fogg_preview_canvas" />' +
330 '</div>'
331 );
332 //set initial state
333 if( _this.show_preview == true){
334 $j('#fogg_preview_canvas').show();
335 }else{
336 $j('#fogg_preview_canvas').hide();
337 }
338 //apply preview binding:
339 $j('#upProgressDialog .fogg_preview').btnBind().click( function(){
340 js_log("click .foog_preview" + $j(this).children('.ui-icon').attr('class') );
341 //check state:
342 if( $j(this).children('.ui-icon').hasClass('ui-icon-triangle-1-e') ){
343 _this.show_preview = true;
344 //update icon:
345 $j(this).children('.ui-icon')
346 .removeClass('ui-icon-triangle-1-e')
347 .addClass('ui-icon-triangle-1-s');
348 //update text
349 $j(this).children('.btnText').text( gM('fogg-hidepreview') );
350
351 //show preview window
352 $j('#fogg_preview_canvas').show('fast');
353 }else{
354 _this.show_preview = false;
355 //update icon:
356 $j(this).children('.ui-icon')
357 .removeClass('ui-icon-triangle-1-s')
358 .addClass('ui-icon-triangle-1-e');
359 //update text:
360 $j(this).children('.btnText').text( gM('fogg-preview') );
361
362 $j('#fogg_preview_canvas').hide('slow');
363 }
364 //don't follow the #
365 return false;
366 });
367 },
368 doRenderPreview:function(){
369 var _this = this;
370 //set up the hidden video to pull frames from:
371 if( $j('#fogg_preview_vid').length == 0 )
372 $j('body').append('<video id="fogg_preview_vid" style="display:none"></video>');
373 var v = $j('#fogg_preview_vid').get(0);
374
375 function seekToEnd(){
376 var v = $j('#fogg_preview_vid').get(0);
377 v.currentTime = v.duration-0.4;
378 }
379 function getFrame() {
380 var v = $j('#fogg_preview_vid').get(0);
381 var canvas = $j('#fogg_preview_canvas').get(0);
382 if( canvas ){
383 canvas.width = 160;
384 canvas.height = canvas.width * v.videoHeight/v.videoWidth;
385 var ctx = canvas.getContext("2d");
386 ctx.drawImage(v, 0, 0, canvas.width, canvas.height);
387 }
388 }
389 var previewI=null;
390 function preview() {
391 //initialize the video if not setup already:
392 var v = $j('#fogg_preview_vid').get(0);
393 if( v.src != _this.fogg.previewUrl ){
394 js_log('init preview with url:' + _this.fogg.previewUrl);
395 v.src = _this.fogg.previewUrl;
396
397 //set the video to seek to the end of the video
398 v.removeEventListener("loadedmetadata", seekToEnd, true);
399 v.addEventListener("loadedmetadata", seekToEnd, true);
400
401 //render a frame once seek is complete:
402 v.removeEventListener("seeked", getFrame, true);
403 v.addEventListener("seeked", getFrame, true);
404
405 //refresh the video duration/meta:
406 clearInterval(previewI);
407 var previewI = setInterval(function(){
408 if (_this.fogg.status() != "encoding"){
409 clearInterval(previewI);
410 }
411 v.load();
412 }, 1000);
413 }
414 }
415 preview();
416 },
417 getEditForm:function(){
418 if( this.target_edit_from )
419 return this.pe_getEditForm();
420 //else try to get the parent "from" of the file selector:
421 return $j(this.selector).parents('form:first').get(0);
422 },
423 selectFogg:function(){
424 var _this = this;
425 if(_this.fogg.selectVideo() ){
426 this.selectFoggActions();
427 }
428 },
429 selectFoggActions:function(){
430 var _this = this;
431 js_log('videoSelectReady');
432 //if not already hidden hide select file and show "select new":
433 $j(_this.target_btn_select_file).hide();
434
435 //show and setup binding for select new file:
436 $j(_this.target_btn_select_new_file).show().unbind().click(function(){
437 //create new fogg instance:
438 _this.fogg = new Firefogg();
439 _this.selectFogg();
440 });
441
442 //update if we are in passthrough mode or going to encode
443 if( _this.fogg.sourceInfo && _this.fogg.sourceFilename ){
444 //update the source status
445 try{
446 _this.sourceFileInfo = JSON.parse( _this.fogg.sourceInfo ) ;
447 }catch (e){
448 js_error('error could not parse fogg sourceInfo');
449 }
450
451 //now setup encoder settings based source type:
452 _this.autoEncoderSettings();
453
454 //if set to passthough update the interface:
455 if(_this.encoder_settings['passthrough'] == true){
456 $j(_this.target_passthrough_mode).show();
457 }else{
458 $j(_this.target_passthrough_mode).hide();
459 //if set to encoder expose the encode button:
460 if( !_this.form_rewrite ){
461 $j(_this.target_btn_save_local_file).show();
462 }
463 }
464 //~otherwise the encoding will be triggered by the form~
465
466 //do source name update callback:
467 js_log(" should update: " + _this.target_input_file_name + ' to: ' + _this.fogg.sourceFilename );
468 $j(_this.target_input_file_name).val(_this.fogg.sourceFilename).show();
469
470 if(_this.new_source_cb){
471 if(_this.encoder_settings['passthrough']){
472 var fName = _this.fogg.sourceFilename
473 }else{
474 var oggExt = (_this.isSourceAudio())?'oga':'ogg';
475 oggExt = (_this.isSourceVideo())?'ogv':oggExt;
476 oggExt = (_this.isUnknown())?'ogg':oggExt;
477 oggName = _this.fogg.sourceFilename.substr(0,
478 _this.fogg.sourceFilename.lastIndexOf('.'));
479 var fName = oggName +'.'+ oggExt
480 }
481 _this.new_source_cb( _this.fogg.sourceFilename , fName);
482 }
483 }
484 },
485 saveLocalFogg:function(){
486 //request target location:
487 if(this.fogg){
488 if(!this.fogg.saveVideoAs() )
489 return false;
490
491 //we have set a target now call the encode:
492 this.doEncode();
493 }
494 },
495 //simple auto encoder settings just enable passthough if file is not video or > 480 pixles tall
496 autoEncoderSettings:function(){
497 var _this = this;
498 //grab the extension:
499 var sf = _this.fogg.sourceFilename;
500 var ext = '';
501 if( sf.lastIndexOf('.') != -1){
502 ext = sf.substring( sf.lastIndexOf('.')+1 ).toLowerCase();
503 }
504
505 //set to passthrough to true by default (images, arbitrary files that we want to send with http chunks)
506 this.encoder_settings['passthrough'] = true;
507
508 //see if we have video or audio:
509 if( _this.isSourceAudio() || _this.isSourceVideo() ){
510 _this.encoder_settings['passthrough'] = false;
511 }
512
513 //special case see if we already have ogg video:
514 if( _this.isOggFormat() ){
515 _this.encoder_settings['passthrough'] = true;
516 }
517
518 js_log('base autoEncoderSettings::' + _this.sourceFileInfo.contentType + ' passthrough:' + _this.encoder_settings['passthrough']);
519 },
520 isUnknown:function(){
521 return (this.sourceFileInfo.contentType.indexOf("unknown") != -1);
522 },
523 isSourceAudio:function(){
524 return (this.sourceFileInfo.contentType.indexOf("audio/") != -1);
525 },
526 isSourceVideo:function(){
527 return (this.sourceFileInfo.contentType.indexOf("video/") != -1);
528 },
529 isOggFormat:function(){
530 return ( this.sourceFileInfo.contentType.indexOf("video/ogg") != -1 ||
531 this.sourceFileInfo.contentType.indexOf("application/ogg") != -1 );
532 },
533 getProgressTitle:function(){
534 js_log("fogg:getProgressTitle f:" + this.fogg_enabled + ' rw:' + this.form_rewrite);
535 //return the parent if we don't have fogg turned on:
536 if(! this.fogg_enabled || !this.firefogg_form_action )
537 return this.pe_getProgressTitle();
538 if( !this.form_rewrite )
539 return gM('fogg-transcoding');
540 //else return our upload+transcode msg:
541 return gM('mwe-upload-transcode-in-progress');
542 },
543 doUploadSwitch:function(){
544 var _this = this;
545 js_log("firefogg: doUploadSwitch:: " + this.fogg_enabled + ' up mode:' + _this.upload_mode);
546 //make sure firefogg is enabled otherwise do parent UploadSwich:
547 if( !this.fogg_enabled || !this.firefogg_form_action )
548 return _this.pe_doUploadSwitch();
549
550 //check what mode to use firefogg in:
551 if( _this.upload_mode == 'post' ){
552 _this.doEncode();
553 }else if( _this.upload_mode == 'api' ){ //if api mode and chunks supported do chunkUpload
554 _this.doChunkUpload();
555 }else{
556 js_error( 'Error: unrecongized upload mode: ' + _this.upload_mode );
557 }
558 },
559 //doChunkUpload does both uploading and encoding at the same time and uploads one meg chunks as they are ready
560 doChunkUpload : function(){
561 js_log('firefogg::doChunkUpload');
562 var _this = this;
563 _this.action_done = false;
564
565 //extension should already be ogg but since its user editable,
566 //check again
567 //we are transcoding so we know it will be an ogg
568 //(should not be done for passthrough mode)
569 var sf = _this.formData['filename'];
570 var ext = '';
571 if( sf.lastIndexOf('.') != -1){
572 ext = sf.substring( sf.lastIndexOf('.') ).toLowerCase();
573 }
574 if( !_this.encoder_settings['passthrough'] && $j.inArray(ext.substr(1), _this.ogg_extensions) == -1 ){
575 var extreg = new RegExp(ext + '$', 'i');
576 _this.formData['filename'] = sf.replace(extreg, '.ogg');
577 }
578 //add chunk response hook to build the resultURL when uploading chunks
579
580 //check for editToken:
581 if(!this.etoken){
582 js_log('missing token try ' + _this.formData['token']);
583 if( _this.formData['token']){
584 _this.etoken = _this.formData['token'];
585 _this.doChunkWithFormData();
586 }else{
587 get_mw_token(
588 'File:'+ _this.formData['filename'],
589 _this.api_url,
590 function( eToken ){
591 if( !eToken || eToken == '+\\' ){
592 _this.updateProgressWin( gM('fogg-badtoken'), gM('fogg-badtoken') );
593 return false;
594 }
595 _this.etoken = eToken;
596 _this.doChunkWithFormData();
597 }
598 );
599 }
600 }else{
601 js_log('we already have token: ' + this.etoken);
602 _this.doChunkWithFormData();
603 }
604 },
605 doChunkWithFormData:function(){
606 var _this = this;
607 js_log("firefogg::doChunkWithFormData" + _this.etoken);
608 //build the api url:
609 var aReq ={
610 'action': 'upload',
611 'format': 'json',
612 'filename': _this.formData['filename'],
613 'comment': _this.formData['comment'],
614 'enablechunks': 'true'
615 };
616
617 if( _this.etoken )
618 aReq['token'] = this.etoken;
619
620 if( _this.formData['watch'] )
621 aReq['watch'] = _this.formData['watch'];
622
623 if( _this.formData['ignorewarnings'] )
624 aReq['ignorewarnings'] = _this.formData['ignorewarnings'];
625
626 js_log('do fogg upload/encode call: '+ _this.api_url + ' :: ' + JSON.stringify( aReq ) );
627 js_log('foggEncode: '+ JSON.stringify( _this.encoder_settings ) );
628 _this.fogg.upload( JSON.stringify( _this.encoder_settings ), _this.api_url , JSON.stringify( aReq ) );
629
630 //update upload status:
631 _this.doUploadStatus();
632 },
633 //doEncode and monitor progress:
634 doEncode : function(){
635 var _this = this;
636 _this.action_done = false;
637 _this.dispProgressOverlay();
638 js_log('doEncode: with: ' + JSON.stringify( _this.encoder_settings ) );
639 _this.fogg.encode( JSON.stringify( _this.encoder_settings ) );
640
641 //show transcode status:
642 $j('#up-status-state').html( gM('mwe-upload-transcoded-status') );
643
644 //setup a local function for timed callback:
645 var encodingStatus = function() {
646 var status = _this.fogg.status();
647
648 if( _this.show_preview == true && _this.fogg.state == 'encoding'){
649 _this.doRenderPreview();
650 }
651
652 //update progress bar
653 _this.updateProgress( _this.fogg.progress() );
654
655 //loop to get new status if still encoding
656 if( _this.fogg.state == 'encoding' ) {
657 setTimeout(encodingStatus, 500);
658 }else if ( _this.fogg.state == 'encoding done' ) { //encoding done, state can also be 'encoding failed
659 _this.encodeDone();
660 }else if(_this.fogg.state == 'encoding fail'){
661 //@@todo error handling:
662 js_error('encoding failed');
663 }
664 }
665 encodingStatus();
666 },
667 encodeDone:function(){
668 var _this = this;
669 js_log('::encodeDone::');
670 _this.action_done = true;
671 //send to the post url:
672 if( _this.form_rewrite && _this.upload_mode == 'post' ){
673 js_log('done with encoding do POST upload:' + _this.editForm.action);
674 // ignore warnings & set source type
675 //_this.formData[ 'wpIgnoreWarning' ]='true';
676 _this.formData[ 'wpSourceType' ] = 'upload';
677 _this.formData[ 'action' ] = 'submit';
678 //wpUploadFile is set by firefogg
679 delete _this.formData[ 'file' ];
680
681 _this.fogg.post( _this.editForm.action, 'wpUploadFile', JSON.stringify( _this.formData ) );
682 //update upload status:
683 _this.doUploadStatus();
684 }else{
685 js_log("done with encoding (no upload) ");
686 //set stuats to 100% for one second:
687 _this.updateProgress( 1 );
688 setTimeout(function(){
689 _this.updateProgressWin(gM('fogg-encoding-done'),
690 gM('fogg-encoding-done') + '<br>' +
691 //show the video at full resolution upto 720px wide
692 '<video controls="true" style="margin:auto" id="fogg_final_vid" src="' +
693 _this.fogg.previewUrl + '"></video>'
694 );
695 //load the video and set a callback:
696 var v = $j('#fogg_final_vid').get(0);
697 function resizeVid(){
698 var v = $j('#fogg_final_vid').get(0);
699 if( v.videoWidth > 720 ){
700 var vW = 720;
701 var vH = 720 * (v.videoHeight/v.videoWidth)
702 }else{
703 var vW = v.videoWidth;
704 var vH = v.videoHeight;
705 }
706 //reize the video:
707 $j(v).css({
708 'width' : vW,
709 'height': vH
710 });
711 //if large video resize the dialog box:
712 if( vW + 5 > 400){
713 //also resize the dialog box
714 $j('#upProgressDialog').dialog('option', 'width', vW + 20);
715 $j('#upProgressDialog').dialog('option', 'height', vH + 120);
716
717 //also position the dialog container
718 $j('#upProgressDialog').dialog('option', 'position', 'center');
719 }
720 }
721 v.removeEventListener("loadedmetadata", resizeVid, true);
722 v.addEventListener("loadedmetadata", resizeVid, true);
723 v.load();
724 }, 1000);
725 }
726 },
727 doUploadStatus:function() {
728 var _this = this;
729 $j( '#up-status-state' ).html( gM('mwe-uploaded-status') );
730
731 _this.oldResponseText = '';
732 //setup a local function for timed callback:
733 var uploadStatus = function(){
734 //get the response text:
735 var response_text = _this.fogg.responseText;
736 if(!response_text){
737 try{
738 var pstatus = JSON.parse( _this.fogg.uploadstatus() );
739 response_text = pstatus["responseText"];
740 }catch(e){
741 js_log("could not parse uploadstatus / could not get responseText");
742 }
743 }
744
745 if( _this.oldResponseText != response_text){
746 js_log('new result text:' + response_text + ' state:' + _this.fogg.state);
747 _this.oldResponseText = response_text;
748 //try and parse the response text and check for errors
749 try{
750 var apiResult = JSON.parse( response_text );
751 }catch(e){
752 js_log("could not parse response_text::" + response_text + ' ...for now try with eval...');
753 try{
754 var apiResult = eval( response_text );
755 }catch(e){
756 var apiResult = null;
757 }
758 }
759 if(apiResult && _this.apiUpdateErrorCheck( apiResult ) === false){
760 //stop status update we have an error
761 _this.action_done = true;
762 _this.fogg.cancel();
763 return false;
764 }
765 }
766 if( _this.show_preview == true ){
767 if( _this.fogg.state == 'encoding' ){
768 _this.doRenderPreview();
769 }
770 }
771
772 //update progress bar
773 _this.updateProgress( _this.fogg.progress() );
774
775 //loop to get new status if still uploading (could also be encoding if we are in chunk upload mode)
776 if( _this.fogg.state == 'encoding' || _this.fogg.state == 'uploading') {
777 setTimeout(uploadStatus, 100);
778 }//check upload state
779 else if( _this.fogg.state == 'upload done' ||
780 _this.fogg.state == 'done' ||
781 _this.fogg.state == 'encoding done' ) {
782 //if in "post" upload mode read the html response (should be depricated):
783 if( _this.upload_mode == 'api' ){
784 if( apiResult && apiResult.resultUrl ){
785 var buttons ={};
786 buttons[gM('mwe-go-to-resource')] = function(){
787 window.location = apiResult.resultUrl;
788 }
789 var go_to_url_txt = gM('mwe-go-to-resource');
790 if( typeof _this.done_upload_cb == 'function' ){
791 //if done action return 'true'
792 if( _this.done_upload_cb( _this.formData ) ){
793 //update status
794 _this.updateProgressWin( gM('mwe-successfulupload'), gM( 'mwe-upload_done', apiResult.resultUrl),buttons);
795 }else{
796 //if done action returns 'false' //close progress window
797 this.action_done = true;
798 $j('#upProgressDialog').empty().dialog('close');
799 }
800 }else{
801 //update status (without done_upload_cb)
802 _this.updateProgressWin( gM('mwe-successfulupload'), gM( 'mwe-upload_done', apiResult.resultUrl),buttons);
803 }
804 }else{
805 //done state with error? ..not really possible given how firefogg works
806 js_log(" Upload done in chunks mode, but no resultUrl!");
807 }
808 }else if( _this.upload_mode == 'post' && _this.api_url ) {
809 _this.procPageResponse( response_text );
810 }
811 }else{
812 //upload error:
813 js_log('Error:firefogg upload error: ' + _this.fogg.state );
814 }
815 }
816 uploadStatus();
817 },
818 cancel_action:function( dlElm ){
819 if(!this.fogg_enabled){
820 return this.pe_cancel_action();
821 }
822 js_log('firefogg:cancel')
823 if( confirm( gM('mwe-cancel-confim') )){
824 if(navigator.oscpu && navigator.oscpu.search('Win') >= 0){
825 alert( 'sorry we do not yet support cancel on windows' );
826 }else{
827 this.action_done = true;
828 this.fogg.cancel();
829 $j(dlElm).empty().dialog('close');
830 return false;
831 }
832 } else{
833 return false;
834 }
835 },
836 /**
837 * procPageResponse should be faded out in favor of the upload api soon..
838 * its all very fragile to read the html output and guess at stuff
839 */
840 procPageResponse:function( result_page ){
841 var _this = this;
842 js_log('f:procPageResponse');
843 var sstring = 'var wgTitle = "' + this.formData['filename'].replace('_',' ');
844
845 if(wgArticlePath){
846 var result_txt = gM('mwe-upload_done', wgArticlePath.replace(/\$1/, 'File:' + _this.formData['filename'] ) );
847 }else{
848 result_txt = 'File has uploaded but api "done" URL was provided. Check the log for result page output';
849 }
850
851 //set the error text in case we dont' get far along in processing the response
852 _this.updateProgressWin( gM('mwe-upload_completed'), result_txt );
853
854 if( result_page && result_page.toLowerCase().indexOf( sstring.toLowerCase() ) != -1){
855 js_log( 'upload done got redirect found: ' + sstring + ' r:' + _this.done_upload_cb );
856 if( _this.done_upload_cb == 'redirect' ){
857 $j( '#dlbox-centered' ).html( '<h3>Upload Completed:</h3>' + result_txt + '<br>' + form_txt);
858 window.location = wgArticlePath.replace( /\$1/, 'File:' + _this.formData['wpDestFile'] );
859 }else{
860 //check if the add_done_action is a callback:
861 if( typeof _this.done_upload_cb == 'function' )
862 _this.done_upload_cb();
863 }
864 }else{
865 //js_log( 'upload page error: did not find: ' +sstring + ' in ' + "\n" + result_page );
866 var form_txt = '';
867 if( !result_page ){
868 //@@todo fix this:
869 //the mediaWiki upload system does not have an API so we can\'t read errors
870 }else{
871 var res = grabWikiFormError( result_page );
872
873 if(res.error_txt)
874 result_txt = res.error_txt;
875
876 if(res.form_txt)
877 form_txt = res.form_txt;
878 }
879 js_log( 'error text is: ' + result_txt );
880 $j( '#dlbox-centered' ).html( '<h3>' + gM('mwe-upload_completed') + '</h3>' + result_txt + '<br>' + form_txt);
881 }
882 }
883 };