PageRenderTime 70ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/symfony/plugins/sfWidgetFormInputSWFUploadPlugin/web/js/vendor/swfupload/swfupload/SWFUpload.as

https://bitbucket.org/wayfarer/verse
ActionScript | 1183 lines | 891 code | 186 blank | 106 comment | 179 complexity | 407be913a109376c0686129014f580ea MD5 | raw file
Possible License(s): ISC, AGPL-3.0, LGPL-2.1, BSD-3-Clause, LGPL-3.0
  1. /* Todo:
  2. * Missing initial progress event
  3. * Improve resizing/encoding so it doesn't lock up browser.
  4. * */
  5. package {
  6. import flash.display.BlendMode;
  7. import flash.display.DisplayObjectContainer;
  8. import flash.display.Loader;
  9. import flash.display.Stage;
  10. import flash.display.Sprite;
  11. import flash.display.StageAlign;
  12. import flash.display.StageScaleMode;
  13. import flash.net.FileReferenceList;
  14. import flash.net.FileReference;
  15. import flash.net.FileFilter;
  16. import flash.net.URLRequest;
  17. import flash.net.URLRequestMethod;
  18. import flash.net.URLVariables;
  19. import flash.events.*;
  20. import flash.external.ExternalInterface;
  21. import flash.system.Security;
  22. import flash.text.AntiAliasType;
  23. import flash.text.GridFitType;
  24. import flash.text.StaticText;
  25. import flash.text.StyleSheet;
  26. import flash.text.TextDisplayMode;
  27. import flash.text.TextField;
  28. import flash.text.TextFieldType;
  29. import flash.text.TextFieldAutoSize;
  30. import flash.text.TextFormat;
  31. import flash.ui.Mouse;
  32. import flash.utils.ByteArray;
  33. import flash.utils.Timer;
  34. import FileItem;
  35. import ExternalCall;
  36. import ImageResizer;
  37. import ImageResizerEvent;
  38. import MultipartURLLoader;
  39. public class SWFUpload extends Sprite {
  40. // Cause SWFUpload to start as soon as the movie starts
  41. public static function main():void
  42. {
  43. var SWFUpload:SWFUpload = new SWFUpload();
  44. }
  45. private const build_number:String = "2.5.0 2009-12-23 Beta 1";
  46. // State tracking variables
  47. private var fileBrowserMany:FileReferenceList = new FileReferenceList();
  48. private var fileBrowserOne:FileReference = null; // This isn't set because it can't be reused like the FileReferenceList. It gets setup in the SelectFile method
  49. private var file_queue:Array = new Array(); // holds a list of all items that are to be uploaded.
  50. private var current_file_item:FileItem = null; // the item that is currently being uploaded.
  51. private var file_index:Array = new Array();
  52. private var successful_uploads:Number = 0; // Tracks the uploads that have been completed
  53. private var queue_errors:Number = 0; // Tracks files rejected during queueing
  54. private var upload_errors:Number = 0; // Tracks files that fail upload
  55. private var upload_cancelled:Number = 0; // Tracks number of cancelled files
  56. private var queued_uploads:Number = 0; // Tracks the FileItems that are waiting to be uploaded.
  57. private var valid_file_extensions:Array = new Array();// Holds the parsed valid extensions.
  58. private var serverDataTimer:Timer = null;
  59. private var assumeSuccessTimer:Timer = null;
  60. private var sizeTimer:Timer;
  61. private var restoreExtIntTimer:Timer;
  62. private var hasCalledFlashReady:Boolean = false;
  63. // Callbacks
  64. private var flashReady_Callback:String;
  65. private var fileDialogStart_Callback:String;
  66. private var fileQueued_Callback:String;
  67. private var fileQueueError_Callback:String;
  68. private var fileDialogComplete_Callback:String;
  69. private var uploadStart_Callback:String;
  70. private var uploadProgress_Callback:String;
  71. private var uploadError_Callback:String;
  72. private var uploadSuccess_Callback:String;
  73. private var uploadComplete_Callback:String;
  74. private var debug_Callback:String;
  75. private var testExternalInterface_Callback:String;
  76. private var cleanUp_Callback:String;
  77. private var mouseOut_Callback:String;
  78. private var mouseOver_Callback:String;
  79. private var mouseClick_Callback:String;
  80. // Values passed in from the HTML
  81. private var movieName:String;
  82. private var uploadURL:String;
  83. private var filePostName:String;
  84. private var uploadPostObject:Object;
  85. private var fileTypes:String;
  86. private var fileTypesDescription:String;
  87. private var fileSizeLimit:Number;
  88. private var fileUploadLimit:Number = 0;
  89. private var fileQueueLimit:Number = 0;
  90. private var useQueryString:Boolean = false;
  91. private var requeueOnError:Boolean = false;
  92. private var httpSuccess:Array = [];
  93. private var assumeSuccessTimeout:Number = 0;
  94. private var debugEnabled:Boolean;
  95. private var buttonLoader:Loader;
  96. private var buttonTextField:TextField;
  97. private var buttonCursorSprite:Sprite;
  98. private var buttonImageURL:String;
  99. //private var buttonWidth:Number;
  100. //private var buttonHeight:Number;
  101. private var buttonText:String;
  102. private var buttonTextStyle:String;
  103. private var buttonTextTopPadding:Number;
  104. private var buttonTextLeftPadding:Number;
  105. private var buttonAction:Number;
  106. private var buttonCursor:Number;
  107. private var buttonStateOver:Boolean;
  108. private var buttonStateMouseDown:Boolean;
  109. private var buttonStateDisabled:Boolean;
  110. // Error code "constants"
  111. // Size check constants
  112. private var SIZE_TOO_BIG:Number = 1;
  113. private var SIZE_ZERO_BYTE:Number = -1;
  114. private var SIZE_OK:Number = 0;
  115. // Queue errors
  116. private var ERROR_CODE_QUEUE_LIMIT_EXCEEDED:Number = -100;
  117. private var ERROR_CODE_FILE_EXCEEDS_SIZE_LIMIT:Number = -110;
  118. private var ERROR_CODE_ZERO_BYTE_FILE:Number = -120;
  119. private var ERROR_CODE_INVALID_FILETYPE:Number = -130;
  120. // Upload Errors
  121. private var ERROR_CODE_HTTP_ERROR:Number = -200;
  122. private var ERROR_CODE_MISSING_UPLOAD_URL:Number = -210;
  123. private var ERROR_CODE_IO_ERROR:Number = -220;
  124. private var ERROR_CODE_SECURITY_ERROR:Number = -230;
  125. private var ERROR_CODE_UPLOAD_LIMIT_EXCEEDED:Number = -240;
  126. private var ERROR_CODE_UPLOAD_FAILED:Number = -250;
  127. private var ERROR_CODE_SPECIFIED_FILE_ID_NOT_FOUND:Number = -260;
  128. private var ERROR_CODE_FILE_VALIDATION_FAILED:Number = -270;
  129. private var ERROR_CODE_FILE_CANCELLED:Number = -280;
  130. private var ERROR_CODE_UPLOAD_STOPPED:Number = -290;
  131. private var ERROR_CODE_RESIZE:Number = -300;
  132. // Button Actions
  133. private var BUTTON_ACTION_SELECT_FILE:Number = -100;
  134. private var BUTTON_ACTION_SELECT_FILES:Number = -110;
  135. private var BUTTON_ACTION_START_UPLOAD:Number = -120;
  136. private var BUTTON_ACTION_NONE:Number = -130;
  137. private var BUTTON_ACTION_JAVASCRIPT:Number = -130; // DEPRECATED
  138. private var BUTTON_CURSOR_ARROW:Number = -1;
  139. private var BUTTON_CURSOR_HAND:Number = -2;
  140. // Resize encoder
  141. private var ENCODER_JPEG:Number = -1;
  142. private var ENCODER_PNG:Number = -2;
  143. public function SWFUpload() {
  144. // Do the feature detection. Make sure this version of Flash supports the features we need. If not
  145. // abort initialization.
  146. if (!flash.net.FileReferenceList || !flash.net.FileReference || !flash.net.URLRequest || !flash.external.ExternalInterface || !flash.external.ExternalInterface.available || !DataEvent.UPLOAD_COMPLETE_DATA) {
  147. return;
  148. }
  149. var self:SWFUpload = this;
  150. Security.allowDomain("*"); // Allow uploading to any domain
  151. Security.allowInsecureDomain("*"); // Allow uploading from HTTP to HTTPS and HTTPS to HTTP
  152. // Keep Flash Player busy so it doesn't show the "flash script is running slowly" error
  153. var counter:Number = 0;
  154. root.addEventListener(Event.ENTER_FRAME, function ():void { if (++counter > 100) counter = 0; });
  155. // Setup file FileReferenceList events
  156. this.fileBrowserMany.addEventListener(Event.SELECT, this.Select_Many_Handler);
  157. this.fileBrowserMany.addEventListener(Event.CANCEL, this.DialogCancelled_Handler);
  158. this.stage.align = StageAlign.TOP_LEFT;
  159. this.stage.scaleMode = StageScaleMode.NO_SCALE;
  160. this.stage.addEventListener(Event.RESIZE, function (e:Event):void {
  161. self.HandleStageResize(e);
  162. });
  163. // Setup the button and text label
  164. this.buttonLoader = new Loader();
  165. var doNothing:Function = function ():void { };
  166. this.buttonLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, doNothing );
  167. this.buttonLoader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, doNothing );
  168. this.buttonLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.ButtonImageLoaded );
  169. this.stage.addChild(this.buttonLoader);
  170. this.stage.addEventListener(MouseEvent.CLICK, function (event:MouseEvent):void {
  171. self.UpdateButtonState();
  172. self.ButtonClickHandler(event);
  173. });
  174. this.stage.addEventListener(MouseEvent.MOUSE_DOWN, function (event:MouseEvent):void {
  175. self.buttonStateMouseDown = true;
  176. self.UpdateButtonState();
  177. });
  178. this.stage.addEventListener(MouseEvent.MOUSE_UP, function (event:MouseEvent):void {
  179. self.buttonStateMouseDown = false;
  180. self.UpdateButtonState();
  181. });
  182. this.stage.addEventListener(MouseEvent.MOUSE_OVER, function (event:MouseEvent):void {
  183. self.buttonStateMouseDown = event.buttonDown;
  184. self.buttonStateOver = true;
  185. self.UpdateButtonState();
  186. ExternalCall.Simple(self.mouseOver_Callback);
  187. });
  188. this.stage.addEventListener(MouseEvent.MOUSE_OUT, function (event:MouseEvent):void {
  189. self.buttonStateMouseDown = false;
  190. self.buttonStateOver = false;
  191. self.UpdateButtonState();
  192. });
  193. // Handle the mouse leaving the flash movie altogether
  194. this.stage.addEventListener(Event.MOUSE_LEAVE, function (event:Event):void {
  195. self.buttonStateMouseDown = false;
  196. self.buttonStateOver = false;
  197. self.UpdateButtonState();
  198. ExternalCall.Simple(self.mouseOut_Callback);
  199. });
  200. this.buttonTextField = new TextField();
  201. this.buttonTextField.type = TextFieldType.DYNAMIC;
  202. this.buttonTextField.antiAliasType = AntiAliasType.ADVANCED;
  203. this.buttonTextField.autoSize = TextFieldAutoSize.NONE;
  204. this.buttonTextField.cacheAsBitmap = true;
  205. this.buttonTextField.multiline = true;
  206. this.buttonTextField.wordWrap = false;
  207. this.buttonTextField.tabEnabled = false;
  208. this.buttonTextField.background = false;
  209. this.buttonTextField.border = false;
  210. this.buttonTextField.selectable = false;
  211. this.buttonTextField.condenseWhite = true;
  212. this.stage.addChild(this.buttonTextField);
  213. this.buttonCursorSprite = new Sprite();
  214. this.buttonCursorSprite.graphics.beginFill(0xFFFFFF, 0);
  215. this.buttonCursorSprite.graphics.drawRect(0, 0, 1, 1);
  216. this.buttonCursorSprite.graphics.endFill();
  217. this.buttonCursorSprite.buttonMode = true;
  218. this.buttonCursorSprite.x = 0;
  219. this.buttonCursorSprite.y = 0;
  220. this.buttonCursorSprite.addEventListener(MouseEvent.CLICK, doNothing);
  221. this.stage.addChild(this.buttonCursorSprite);
  222. // Get the movie name
  223. this.movieName = decodeURIComponent(root.loaderInfo.parameters.movieName);
  224. // **Configure the callbacks**
  225. // The JavaScript tracks all the instances of SWFUpload on a page. We can access the instance
  226. // associated with this SWF file using the movieName. Each callback is accessible by making
  227. // a call directly to it on our instance. There is no error handling for undefined callback functions.
  228. // A developer would have to deliberately remove the default functions,set the variable to null, or remove
  229. // it from the init function.
  230. this.flashReady_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].flashReady";
  231. this.fileDialogStart_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileDialogStart";
  232. this.fileQueued_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileQueued";
  233. this.fileQueueError_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileQueueError";
  234. this.fileDialogComplete_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].fileDialogComplete";
  235. this.uploadStart_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadStart";
  236. this.uploadProgress_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadProgress";
  237. this.uploadError_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadError";
  238. this.uploadSuccess_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadSuccess";
  239. this.uploadComplete_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].uploadComplete";
  240. this.debug_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].debug";
  241. this.testExternalInterface_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].testExternalInterface";
  242. this.cleanUp_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].cleanUp";
  243. this.mouseOut_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].mouseOut";
  244. this.mouseOver_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].mouseOver";
  245. this.mouseClick_Callback = "SWFUpload.instances[\"" + this.movieName + "\"].mouseClick";
  246. // Get the Flash Vars
  247. this.uploadURL = decodeURIComponent(root.loaderInfo.parameters.uploadURL);
  248. this.filePostName = decodeURIComponent(root.loaderInfo.parameters.filePostName);
  249. this.fileTypes = decodeURIComponent(root.loaderInfo.parameters.fileTypes);
  250. this.fileTypesDescription = decodeURIComponent(root.loaderInfo.parameters.fileTypesDescription) + " (" + this.fileTypes + ")";
  251. this.loadPostParams(decodeURIComponent(root.loaderInfo.parameters.params));
  252. if (!this.filePostName) {
  253. this.filePostName = "Filedata";
  254. }
  255. if (!this.fileTypes) {
  256. this.fileTypes = "*.*";
  257. }
  258. if (!this.fileTypesDescription) {
  259. this.fileTypesDescription = "All Files";
  260. }
  261. this.LoadFileExensions(this.fileTypes);
  262. try {
  263. this.debugEnabled = decodeURIComponent(root.loaderInfo.parameters.debugEnabled) == "true" ? true : false;
  264. } catch (ex:Object) {
  265. this.debugEnabled = false;
  266. }
  267. try {
  268. this.SetFileSizeLimit(String(decodeURIComponent(root.loaderInfo.parameters.fileSizeLimit)));
  269. } catch (ex:Object) {
  270. this.fileSizeLimit = 0;
  271. }
  272. try {
  273. this.fileUploadLimit = Number(decodeURIComponent(root.loaderInfo.parameters.fileUploadLimit));
  274. if (this.fileUploadLimit < 0) this.fileUploadLimit = 0;
  275. } catch (ex:Object) {
  276. this.fileUploadLimit = 0;
  277. }
  278. try {
  279. this.fileQueueLimit = Number(decodeURIComponent(root.loaderInfo.parameters.fileQueueLimit));
  280. if (this.fileQueueLimit < 0) this.fileQueueLimit = 0;
  281. } catch (ex:Object) {
  282. this.fileQueueLimit = 0;
  283. }
  284. // Set the queue limit to match the upload limit when the queue limit is bigger than the upload limit
  285. if (this.fileQueueLimit > this.fileUploadLimit && this.fileUploadLimit != 0) this.fileQueueLimit = this.fileUploadLimit;
  286. // The the queue limit is unlimited and the upload limit is not then set the queue limit to the upload limit
  287. if (this.fileQueueLimit == 0 && this.fileUploadLimit != 0) this.fileQueueLimit = this.fileUploadLimit;
  288. try {
  289. this.useQueryString = decodeURIComponent(root.loaderInfo.parameters.useQueryString) == "true" ? true : false;
  290. } catch (ex:Object) {
  291. this.useQueryString = false;
  292. }
  293. try {
  294. this.requeueOnError = decodeURIComponent(root.loaderInfo.parameters.requeueOnError) == "true" ? true : false;
  295. } catch (ex:Object) {
  296. this.requeueOnError = false;
  297. }
  298. try {
  299. this.SetHTTPSuccess(String(decodeURIComponent(root.loaderInfo.parameters.httpSuccess)));
  300. } catch (ex:Object) {
  301. this.SetHTTPSuccess([]);
  302. }
  303. try {
  304. this.SetAssumeSuccessTimeout(Number(decodeURIComponent(root.loaderInfo.parameters.assumeSuccessTimeout)));
  305. } catch (ex:Object) {
  306. this.SetAssumeSuccessTimeout(0);
  307. }
  308. try {
  309. this.SetButtonImageURL(String(decodeURIComponent(root.loaderInfo.parameters.buttonImageURL)));
  310. } catch (ex:Object) {
  311. this.SetButtonImageURL("");
  312. }
  313. try {
  314. this.SetButtonText(String(decodeURIComponent(root.loaderInfo.parameters.buttonText)));
  315. } catch (ex:Object) {
  316. this.SetButtonText("");
  317. }
  318. try {
  319. this.SetButtonTextPadding(Number(decodeURIComponent(root.loaderInfo.parameters.buttonTextLeftPadding)), Number(decodeURIComponent(root.loaderInfo.parameters.buttonTextTopPadding)));
  320. } catch (ex:Object) {
  321. this.SetButtonTextPadding(0, 0);
  322. }
  323. try {
  324. this.SetButtonTextStyle(String(decodeURIComponent(root.loaderInfo.parameters.buttonTextStyle)));
  325. } catch (ex:Object) {
  326. this.SetButtonTextStyle("");
  327. }
  328. try {
  329. this.SetButtonAction(Number(decodeURIComponent(root.loaderInfo.parameters.buttonAction)));
  330. } catch (ex:Object) {
  331. this.SetButtonAction(this.BUTTON_ACTION_SELECT_FILES);
  332. }
  333. try {
  334. this.SetButtonDisabled(decodeURIComponent(root.loaderInfo.parameters.buttonDisabled) == "true" ? true : false);
  335. } catch (ex:Object) {
  336. this.SetButtonDisabled(Boolean(false));
  337. }
  338. try {
  339. this.SetButtonCursor(Number(decodeURIComponent(root.loaderInfo.parameters.buttonCursor)));
  340. } catch (ex:Object) {
  341. this.SetButtonCursor(this.BUTTON_CURSOR_ARROW);
  342. }
  343. this.SetupExternalInterface();
  344. this.Debug("SWFUpload Init Complete");
  345. this.PrintDebugInfo();
  346. if (ExternalCall.Bool(this.testExternalInterface_Callback)) {
  347. ExternalCall.Simple(this.flashReady_Callback);
  348. this.hasCalledFlashReady = true;
  349. }
  350. // Start periodically checking the external interface
  351. this.restoreExtIntTimer = new Timer(1000, 0);
  352. this.restoreExtIntTimer.addEventListener(TimerEvent.TIMER, function ():void { self.CheckExternalInterface();} );
  353. this.restoreExtIntTimer.start();
  354. }
  355. private function HandleStageResize(e:Event):void {
  356. try {
  357. if (this.stage.stageWidth > 0 || this.stage.stageHeight > 0) {
  358. var buttonHeight:Number = this.buttonLoader.contentLoaderInfo.height / 4;
  359. // Scale the button cursor
  360. this.buttonCursorSprite.width = this.stage.stageWidth;
  361. this.buttonCursorSprite.height = this.stage.stageHeight;
  362. // scale the button
  363. this.buttonLoader.height = this.stage.stageHeight * 4;
  364. this.buttonLoader.scaleX = this.buttonLoader.scaleY;
  365. // scale the text area (it doesn't resize but it still needs to fit)
  366. this.buttonTextField.width = this.stage.stageWidth;
  367. this.buttonTextField.height = this.stage.stageHeight;
  368. this.Debug("Stage:" + this.stage.stageWidth + " by " + this.stage.stageHeight);
  369. }
  370. } catch (ex:Error) {}
  371. }
  372. // Used to periodically check that the External Interface functions are still working
  373. private function CheckExternalInterface():void {
  374. if (!ExternalCall.Bool(this.testExternalInterface_Callback)) {
  375. this.SetupExternalInterface();
  376. this.Debug("ExternalInterface reinitialized");
  377. if (!this.hasCalledFlashReady) {
  378. ExternalCall.Simple(this.flashReady_Callback);
  379. this.hasCalledFlashReady = true;
  380. }
  381. }
  382. }
  383. private function StopExternalInterfaceCheck():void {
  384. if (this.restoreExtIntTimer) {
  385. this.restoreExtIntTimer.start();
  386. this.restoreExtIntTimer = null;
  387. }
  388. }
  389. // Called by JS to see if it can access the external interface
  390. private function TestExternalInterface():Boolean {
  391. return true;
  392. }
  393. private function SetupExternalInterface():void {
  394. try {
  395. ExternalInterface.addCallback("SelectFile", this.SelectFile);
  396. ExternalInterface.addCallback("SelectFiles", this.SelectFiles);
  397. ExternalInterface.addCallback("StartUpload", this.StartUpload);
  398. ExternalInterface.addCallback("ReturnUploadStart", this.ReturnUploadStart);
  399. ExternalInterface.addCallback("StopUpload", this.StopUpload);
  400. ExternalInterface.addCallback("CancelUpload", this.CancelUpload);
  401. ExternalInterface.addCallback("RequeueUpload", this.RequeueUpload);
  402. ExternalInterface.addCallback("GetStats", this.GetStats);
  403. ExternalInterface.addCallback("SetStats", this.SetStats);
  404. ExternalInterface.addCallback("GetFile", this.GetFile);
  405. ExternalInterface.addCallback("GetFileByIndex", this.GetFileByIndex);
  406. ExternalInterface.addCallback("GetFileByQueueIndex", this.GetFileByQueueIndex);
  407. ExternalInterface.addCallback("AddFileParam", this.AddFileParam);
  408. ExternalInterface.addCallback("RemoveFileParam", this.RemoveFileParam);
  409. ExternalInterface.addCallback("SetUploadURL", this.SetUploadURL);
  410. ExternalInterface.addCallback("SetPostParams", this.SetPostParams);
  411. ExternalInterface.addCallback("SetFileTypes", this.SetFileTypes);
  412. ExternalInterface.addCallback("SetFileSizeLimit", this.SetFileSizeLimit);
  413. ExternalInterface.addCallback("SetFileUploadLimit", this.SetFileUploadLimit);
  414. ExternalInterface.addCallback("SetFileQueueLimit", this.SetFileQueueLimit);
  415. ExternalInterface.addCallback("SetFilePostName", this.SetFilePostName);
  416. ExternalInterface.addCallback("SetUseQueryString", this.SetUseQueryString);
  417. ExternalInterface.addCallback("SetRequeueOnError", this.SetRequeueOnError);
  418. ExternalInterface.addCallback("SetHTTPSuccess", this.SetHTTPSuccess);
  419. ExternalInterface.addCallback("SetAssumeSuccessTimeout", this.SetAssumeSuccessTimeout);
  420. ExternalInterface.addCallback("SetDebugEnabled", this.SetDebugEnabled);
  421. ExternalInterface.addCallback("SetButtonImageURL", this.SetButtonImageURL);
  422. ExternalInterface.addCallback("SetButtonText", this.SetButtonText);
  423. ExternalInterface.addCallback("SetButtonTextPadding", this.SetButtonTextPadding);
  424. ExternalInterface.addCallback("SetButtonTextStyle", this.SetButtonTextStyle);
  425. ExternalInterface.addCallback("SetButtonAction", this.SetButtonAction);
  426. ExternalInterface.addCallback("SetButtonDisabled", this.SetButtonDisabled);
  427. ExternalInterface.addCallback("SetButtonCursor", this.SetButtonCursor);
  428. ExternalInterface.addCallback("TestExternalInterface", this.TestExternalInterface);
  429. ExternalInterface.addCallback("StopExternalInterfaceCheck", this.StopExternalInterfaceCheck);
  430. } catch (ex:Error) {
  431. this.Debug("Callbacks where not set: " + ex.message);
  432. return;
  433. }
  434. ExternalCall.Simple(this.cleanUp_Callback);
  435. }
  436. /* *****************************************
  437. * FileReference Event Handlers
  438. * *************************************** */
  439. private function DialogCancelled_Handler(event:Event):void {
  440. this.Debug("Event: fileDialogComplete: File Dialog window cancelled.");
  441. ExternalCall.FileDialogComplete(this.fileDialogComplete_Callback, 0, 0, this.queued_uploads);
  442. }
  443. private function Open_Handler(event:Event):void {
  444. this.Debug("Event: uploadProgress (OPEN): File ID: " + this.current_file_item.id);
  445. this.current_file_item.finalUploadProgress = false;
  446. ExternalCall.UploadProgress(this.uploadProgress_Callback, this.current_file_item.ToJavaScriptObject(), 0, this.current_file_item.file_reference.size);
  447. }
  448. private function FileProgress_Handler(event:ProgressEvent):void {
  449. // On early than Mac OS X 10.3 bytesLoaded is always -1, convert this to zero. Do bytesTotal for good measure.
  450. // http://livedocs.adobe.com/flex/3/langref/flash/net/FileReference.html#event:progress
  451. var bytesLoaded:Number = event.bytesLoaded < 0 ? 0 : event.bytesLoaded;
  452. var bytesTotal:Number = event.bytesTotal < 0 ? 0 : event.bytesTotal;
  453. // Because Flash never fires a complete event if the server doesn't respond after 30 seconds or on Macs if there
  454. // is no content in the response we'll set a timer and assume that the upload is successful after the defined amount of
  455. // time. If the timeout is zero then we won't use the timer.
  456. if (bytesLoaded === bytesTotal) {
  457. this.current_file_item.finalUploadProgress = true;
  458. if (bytesTotal > 0 && this.assumeSuccessTimeout > 0) {
  459. if (this.assumeSuccessTimer !== null) {
  460. this.assumeSuccessTimer.stop();
  461. this.assumeSuccessTimer = null;
  462. }
  463. this.assumeSuccessTimer = new Timer(this.assumeSuccessTimeout * 1000, 1);
  464. this.assumeSuccessTimer.addEventListener(TimerEvent.TIMER_COMPLETE, AssumeSuccessTimer_Handler);
  465. this.assumeSuccessTimer.start();
  466. }
  467. }
  468. this.Debug("Event: uploadProgress: File ID: " + this.current_file_item.id + ". Bytes: " + bytesLoaded + ". Total: " + bytesTotal);
  469. ExternalCall.UploadProgress(this.uploadProgress_Callback, this.current_file_item.ToJavaScriptObject(), bytesLoaded, bytesTotal);
  470. }
  471. private function AssumeSuccessTimer_Handler(event:TimerEvent):void {
  472. this.Debug("Event: AssumeSuccess: " + this.assumeSuccessTimeout + " passed without server response");
  473. this.UploadSuccess(this.current_file_item, "", false);
  474. }
  475. private function Complete_Handler(event:Event):void {
  476. /* Because we can't do COMPLETE or DATA events (we have to do both) we can't
  477. * just call uploadSuccess from the complete handler, we have to wait for
  478. * the Data event which may never come. However, testing shows it always comes
  479. * within a couple milliseconds if it is going to come so the solution is:
  480. *
  481. * Set a timer in the COMPLETE event (which always fires) and if DATA is fired
  482. * it will stop the timer and call uploadComplete
  483. *
  484. * If the timer expires then DATA won't be fired and we call uploadComplete
  485. * */
  486. // Set the timer
  487. if (serverDataTimer != null) {
  488. this.serverDataTimer.stop();
  489. this.serverDataTimer = null;
  490. }
  491. this.serverDataTimer = new Timer(100, 1);
  492. //var self:SWFUpload = this;
  493. this.serverDataTimer.addEventListener(TimerEvent.TIMER, this.ServerDataTimer_Handler);
  494. this.serverDataTimer.start();
  495. }
  496. private function ServerDataTimer_Handler(event:TimerEvent):void {
  497. this.UploadSuccess(this.current_file_item, "");
  498. }
  499. private function ServerData_Handler(event:DataEvent):void {
  500. this.UploadSuccess(this.current_file_item, event.data);
  501. }
  502. private function UploadSuccess(file:FileItem, serverData:String, responseReceived:Boolean = true):void {
  503. if (this.serverDataTimer !== null) {
  504. this.serverDataTimer.stop();
  505. this.serverDataTimer = null;
  506. }
  507. if (this.assumeSuccessTimer !== null) {
  508. this.assumeSuccessTimer.stop();
  509. this.assumeSuccessTimer = null;
  510. }
  511. // If the 100% upload progress hasn't been called then call it now
  512. if (!file.finalUploadProgress) {
  513. file.finalUploadProgress = true;
  514. this.Debug("Event: uploadProgress (simulated 100%): File ID: " + file.id + ". Bytes: " + file.file_reference.size + ". Total: " + file.file_reference.size);
  515. ExternalCall.UploadProgress(this.uploadProgress_Callback, file.ToJavaScriptObject(), file.file_reference.size, file.file_reference.size);
  516. }
  517. this.successful_uploads++;
  518. file.file_status = FileItem.FILE_STATUS_SUCCESS;
  519. this.Debug("Event: uploadSuccess: File ID: " + file.id + " Response Received: " + responseReceived.toString() + " Data: " + serverData);
  520. ExternalCall.UploadSuccess(this.uploadSuccess_Callback, file.ToJavaScriptObject(), serverData, responseReceived);
  521. this.UploadComplete(false);
  522. }
  523. private function HTTPError_Handler(event:HTTPStatusEvent):void {
  524. var isSuccessStatus:Boolean = false;
  525. for (var i:Number = 0; i < this.httpSuccess.length; i++) {
  526. if (this.httpSuccess[i] === event.status) {
  527. isSuccessStatus = true;
  528. break;
  529. }
  530. }
  531. if (isSuccessStatus) {
  532. this.Debug("Event: httpError: Translating status code " + event.status + " to uploadSuccess");
  533. var serverDataEvent:DataEvent = new DataEvent(DataEvent.UPLOAD_COMPLETE_DATA, event.bubbles, event.cancelable, "");
  534. this.ServerData_Handler(serverDataEvent);
  535. } else {
  536. this.upload_errors++;
  537. this.current_file_item.file_status = FileItem.FILE_STATUS_ERROR;
  538. this.Debug("Event: uploadError: HTTP ERROR : File ID: " + this.current_file_item.id + ". HTTP Status: " + event.status + ".");
  539. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_HTTP_ERROR, this.current_file_item.ToJavaScriptObject(), event.status.toString());
  540. this.UploadComplete(true); // An IO Error is also called so we don't want to complete the upload yet.
  541. }
  542. }
  543. // Note: Flash Player does not support Uploads that require authentication. Attempting this will trigger an
  544. // IO Error or it will prompt for a username and password and may crash the browser (FireFox/Opera)
  545. private function IOError_Handler(event:IOErrorEvent):void {
  546. // Only trigger an IO Error event if we haven't already done an HTTP error
  547. if (this.current_file_item.file_status != FileItem.FILE_STATUS_ERROR) {
  548. this.upload_errors++;
  549. this.current_file_item.file_status = FileItem.FILE_STATUS_ERROR;
  550. this.Debug("Event: uploadError : IO Error : File ID: " + this.current_file_item.id + ". IO Error: " + event.text);
  551. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_IO_ERROR, this.current_file_item.ToJavaScriptObject(), event.text);
  552. }
  553. this.UploadComplete(true);
  554. }
  555. private function SecurityError_Handler(event:SecurityErrorEvent):void {
  556. this.upload_errors++;
  557. this.current_file_item.file_status = FileItem.FILE_STATUS_ERROR;
  558. this.Debug("Event: uploadError : Security Error : File Number: " + this.current_file_item.id + ". Error text: " + event.text);
  559. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_SECURITY_ERROR, this.current_file_item.ToJavaScriptObject(), event.text);
  560. this.UploadComplete(true);
  561. }
  562. private function Select_Many_Handler(event:Event):void {
  563. this.Select_Handler(this.fileBrowserMany.fileList);
  564. }
  565. private function Select_One_Handler(event:Event):void {
  566. var fileArray:Array = new Array(1);
  567. fileArray[0] = this.fileBrowserOne;
  568. this.Select_Handler(fileArray);
  569. }
  570. private function Select_Handler(file_reference_list:Array):void {
  571. this.Debug("Select Handler: Received the files selected from the dialog. Processing the file list...");
  572. var num_files_queued:Number = 0;
  573. // Determine how many queue slots are remaining (check the unlimited (0) settings, successful uploads and queued uploads)
  574. var queue_slots_remaining:Number = 0;
  575. if (this.fileUploadLimit == 0) {
  576. queue_slots_remaining = this.fileQueueLimit == 0 ? file_reference_list.length : (this.fileQueueLimit - this.queued_uploads); // If unlimited queue make the allowed size match however many files were selected.
  577. } else {
  578. var remaining_uploads:Number = this.fileUploadLimit - this.successful_uploads - this.queued_uploads;
  579. if (remaining_uploads < 0) remaining_uploads = 0;
  580. if (this.fileQueueLimit == 0 || this.fileQueueLimit >= remaining_uploads) {
  581. queue_slots_remaining = remaining_uploads;
  582. } else if (this.fileQueueLimit < remaining_uploads) {
  583. queue_slots_remaining = this.fileQueueLimit - this.queued_uploads;
  584. }
  585. }
  586. if (queue_slots_remaining < 0) queue_slots_remaining = 0;
  587. // Check if the number of files selected is greater than the number allowed to queue up.
  588. if (queue_slots_remaining < file_reference_list.length) {
  589. this.Debug("Event: fileQueueError : Selected Files (" + file_reference_list.length + ") exceeds remaining Queue size (" + queue_slots_remaining + ").");
  590. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_QUEUE_LIMIT_EXCEEDED, null, queue_slots_remaining.toString());
  591. } else {
  592. // Process each selected file
  593. for (var i:Number = 0; i < file_reference_list.length; i++) {
  594. var file_item:FileItem = new FileItem(file_reference_list[i], this.movieName, this.file_index.length);
  595. this.file_index[file_item.index] = file_item;
  596. // Verify that the file is accessible. Zero byte files and possibly other conditions can cause a file to be inaccessible.
  597. var jsFileObj:Object = file_item.ToJavaScriptObject();
  598. var is_valid_file_reference:Boolean = (jsFileObj.filestatus !== FileItem.FILE_STATUS_ERROR);
  599. if (is_valid_file_reference) {
  600. // Check the size, if it's within the limit add it to the upload list.
  601. var size_result:Number = this.CheckFileSize(file_item);
  602. var is_valid_filetype:Boolean = this.CheckFileType(file_item);
  603. if(size_result == this.SIZE_OK && is_valid_filetype) {
  604. file_item.file_status = FileItem.FILE_STATUS_QUEUED;
  605. this.file_queue.push(file_item);
  606. this.queued_uploads++;
  607. num_files_queued++;
  608. this.Debug("Event: fileQueued : File ID: " + file_item.id);
  609. ExternalCall.FileQueued(this.fileQueued_Callback, file_item.ToJavaScriptObject());
  610. }
  611. else if (!is_valid_filetype) {
  612. //file_item.file_reference = null; // Cleanup the object
  613. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  614. this.queue_errors++;
  615. this.Debug("Event: fileQueueError : File not of a valid type.");
  616. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_INVALID_FILETYPE, file_item.ToJavaScriptObject(), "File is not an allowed file type.");
  617. }
  618. else if (size_result == this.SIZE_TOO_BIG) {
  619. //file_item.file_reference = null; // Cleanup the object
  620. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  621. this.queue_errors++;
  622. this.Debug("Event: fileQueueError : File exceeds size limit.");
  623. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_FILE_EXCEEDS_SIZE_LIMIT, file_item.ToJavaScriptObject(), "File size exceeds allowed limit.");
  624. }
  625. else if (size_result == this.SIZE_ZERO_BYTE) {
  626. file_item.file_reference = null; // Cleanup the object
  627. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  628. this.queue_errors++;
  629. this.Debug("Event: fileQueueError : File is zero bytes.");
  630. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_ZERO_BYTE_FILE, file_item.ToJavaScriptObject(), "File is zero bytes and cannot be uploaded.");
  631. }
  632. } else {
  633. file_item.file_reference = null; // Cleanup the object
  634. file_item.file_status = FileItem.FILE_STATUS_ERROR;
  635. this.queue_errors++;
  636. this.Debug("Event: fileQueueError : File is zero bytes or FileReference is invalid.");
  637. ExternalCall.FileQueueError(this.fileQueueError_Callback, this.ERROR_CODE_ZERO_BYTE_FILE, file_item.ToJavaScriptObject(), "File is zero bytes or cannot be accessed and cannot be uploaded.");
  638. }
  639. }
  640. }
  641. this.Debug("Event: fileDialogComplete : Finished processing selected files. Files selected: " + file_reference_list.length + ". Files Queued: " + num_files_queued);
  642. ExternalCall.FileDialogComplete(this.fileDialogComplete_Callback, file_reference_list.length, num_files_queued, this.queued_uploads);
  643. }
  644. /* ****************************************************************
  645. Externally exposed functions
  646. ****************************************************************** */
  647. // Opens a file browser dialog that allows one file to be selected.
  648. private function SelectFile():void {
  649. this.fileBrowserOne = new FileReference();
  650. this.fileBrowserOne.addEventListener(Event.SELECT, this.Select_One_Handler);
  651. this.fileBrowserOne.addEventListener(Event.CANCEL, this.DialogCancelled_Handler);
  652. // Default file type settings
  653. var allowed_file_types:String = "*.*";
  654. var allowed_file_types_description:String = "All Files";
  655. // Get the instance settings
  656. if (this.fileTypes.length > 0) allowed_file_types = this.fileTypes;
  657. if (this.fileTypesDescription.length > 0) allowed_file_types_description = this.fileTypesDescription;
  658. this.Debug("Event: fileDialogStart : Browsing files. Single Select. Allowed file types: " + allowed_file_types);
  659. ExternalCall.Simple(this.fileDialogStart_Callback);
  660. try {
  661. this.fileBrowserOne.browse([new FileFilter(allowed_file_types_description, allowed_file_types)]);
  662. } catch (ex:Error) {
  663. this.Debug("Exception: " + ex.toString());
  664. }
  665. }
  666. // Opens a file browser dialog that allows multiple files to be selected.
  667. private function SelectFiles():void {
  668. var allowed_file_types:String = "*.*";
  669. var allowed_file_types_description:String = "All Files";
  670. if (this.fileTypes.length > 0) allowed_file_types = this.fileTypes;
  671. if (this.fileTypesDescription.length > 0) allowed_file_types_description = this.fileTypesDescription;
  672. this.Debug("Event: fileDialogStart : Browsing files. Multi Select. Allowed file types: " + allowed_file_types);
  673. ExternalCall.Simple(this.fileDialogStart_Callback);
  674. try {
  675. this.fileBrowserMany.browse([new FileFilter(allowed_file_types_description, allowed_file_types)]);
  676. } catch (ex:Error) {
  677. this.Debug("Exception: " + ex.toString());
  678. }
  679. }
  680. // Cancel the current upload and stops. Doesn't advance the upload pointer. The current file is requeued at the beginning.
  681. private function StopUpload():void {
  682. if (this.current_file_item != null) {
  683. // Cancel the upload and re-queue the FileItem
  684. if (this.current_file_item.upload_type === FileItem.UPLOAD_TYPE_NORMAL) {
  685. this.current_file_item.file_reference.cancel();
  686. } else {
  687. if (this.current_file_item.resized_uploader != null) {
  688. this.current_file_item.resized_uploader.cancel();
  689. this.current_file_item.resized_uploader = null;
  690. }
  691. }
  692. // Remove the event handlers
  693. this.removeEventListeners(this.current_file_item);
  694. this.current_file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  695. this.current_file_item.file_status = FileItem.FILE_STATUS_QUEUED;
  696. this.file_queue.unshift(this.current_file_item);
  697. var js_object:Object = this.current_file_item.ToJavaScriptObject();
  698. this.current_file_item = null;
  699. this.Debug("Event: uploadError: upload stopped. File ID: " + js_object.ID);
  700. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_UPLOAD_STOPPED, js_object, "Upload Stopped");
  701. this.Debug("Event: uploadComplete. File ID: " + js_object.ID);
  702. ExternalCall.UploadComplete(this.uploadComplete_Callback, js_object);
  703. this.Debug("StopUpload(): upload stopped.");
  704. } else {
  705. this.Debug("StopUpload(): No file is currently uploading. Nothing to do.");
  706. }
  707. }
  708. /* Cancels the upload specified by file_id
  709. * If the file is currently uploading it is cancelled and the uploadComplete
  710. * event gets called.
  711. * If the file is not currently uploading then only the uploadCancelled event is fired.
  712. *
  713. * The triggerComplete is used by the resize stuff to cancel the upload
  714. * */
  715. private function CancelUpload(file_id:String, triggerErrorEvent:Boolean = true):void {
  716. var file_item:FileItem = null;
  717. // Check the current file item
  718. if (this.current_file_item != null && (this.current_file_item.id == file_id || !file_id)) {
  719. if (this.current_file_item.upload_type === FileItem.UPLOAD_TYPE_NORMAL) {
  720. this.current_file_item.file_reference.cancel();
  721. } else {
  722. if (this.current_file_item.resized_uploader != null) {
  723. this.current_file_item.resized_uploader.cancel();
  724. this.current_file_item.resized_uploader = null;
  725. }
  726. }
  727. this.current_file_item.file_status = FileItem.FILE_STATUS_CANCELLED;
  728. this.current_file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  729. this.upload_cancelled++;
  730. if (triggerErrorEvent) {
  731. this.Debug("Event: uploadError: File ID: " + this.current_file_item.id + ". Cancelled current upload");
  732. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_FILE_CANCELLED, this.current_file_item.ToJavaScriptObject(), "File Upload Cancelled.");
  733. } else {
  734. this.Debug("Event: cancelUpload: File ID: " + this.current_file_item.id + ". Cancelled current upload. Suppressed uploadError event.");
  735. }
  736. this.UploadComplete(false);
  737. } else if (file_id) {
  738. // Find the file in the queue
  739. var file_index:Number = this.FindIndexInFileQueue(file_id);
  740. if (file_index >= 0) {
  741. // Remove the file from the queue
  742. file_item = FileItem(this.file_queue[file_index]);
  743. file_item.file_status = FileItem.FILE_STATUS_CANCELLED;
  744. this.file_queue.splice(file_index, 1);
  745. this.queued_uploads--;
  746. this.upload_cancelled++;
  747. // Cancel the file (just for good measure) and make the callback
  748. if (file_item.upload_type === FileItem.UPLOAD_TYPE_NORMAL) {
  749. file_item.file_reference.cancel();
  750. } else {
  751. if (file_item.resized_uploader != null) {
  752. file_item.resized_uploader.cancel();
  753. file_item.resized_uploader = null;
  754. }
  755. }
  756. this.removeEventListeners(file_item);
  757. file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  758. if (triggerErrorEvent) {
  759. this.Debug("Event: uploadError : " + file_item.id + ". Cancelled queued upload");
  760. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_FILE_CANCELLED, file_item.ToJavaScriptObject(), "File Cancelled");
  761. } else {
  762. this.Debug("Event: cancelUpload: File ID: " + file_item.id + ". Cancelled current upload. Suppressed uploadError event.");
  763. }
  764. // Get rid of the file object
  765. file_item = null;
  766. }
  767. } else {
  768. // Get the first file and cancel it
  769. while (this.file_queue.length > 0 && file_item == null) {
  770. // Check that File Reference is valid (if not make sure it's deleted and get the next one on the next loop)
  771. file_item = FileItem(this.file_queue.shift()); // Cast back to a FileItem
  772. if (typeof(file_item) == "undefined") {
  773. file_item = null;
  774. continue;
  775. }
  776. }
  777. if (file_item != null) {
  778. file_item.file_status = FileItem.FILE_STATUS_CANCELLED;
  779. this.queued_uploads--;
  780. this.upload_cancelled++;
  781. // Cancel the file (just for good measure) and make the callback
  782. if (file_item.upload_type === FileItem.UPLOAD_TYPE_NORMAL) {
  783. file_item.file_reference.cancel();
  784. } else {
  785. if (file_item.resized_uploader != null) {
  786. file_item.resized_uploader.cancel();
  787. file_item.resized_uploader = null;
  788. }
  789. }
  790. this.removeEventListeners(file_item);
  791. file_item.upload_type = FileItem.UPLOAD_TYPE_NORMAL;
  792. if (triggerErrorEvent) {
  793. this.Debug("Event: uploadError : " + file_item.id + ". Cancelled queued upload");
  794. ExternalCall.UploadError(this.uploadError_Callback, this.ERROR_CODE_FILE_CANCELLED, file_item.ToJavaScriptObject(), "File Cancelled");
  795. } else {
  796. this.Debug("Event: cancelUpload: File ID: " + file_item.id + ". Cancelled current upload. Suppressed uploadError event.");
  797. }
  798. // Get rid of the file object
  799. file_item = null;
  800. }
  801. }
  802. }
  803. /* Requeues the indicated file. Returns true if successful or if the file is
  804. * already in the queue. Otherwise returns false.
  805. * */
  806. private function RequeueUpload(fileIdentifier:*):Boolean {
  807. var file:FileItem = null;
  808. if (typeof(fileIdentifier) === "number") {
  809. var fileIndex:Number = Number(fileIdentifier);
  810. if (fileIndex >= 0 && fileIndex < this.file_index.length) {
  811. file = this.file_index[fileIndex];
  812. }
  813. } else if (typeof(fileIdentifier) === "string") {
  814. file = FindFileInFileIndex(String(fileIdentifier));
  815. } else {
  816. return false;
  817. }
  818. if (file !== null && file.file_reference !== null) {
  819. if (file.file_status === FileItem.FILE_STATUS_IN_PROGRESS || file.file_status === FileItem.FILE_STATUS_NEW) {
  820. return false;
  821. } else if (file.file_status !== FileItem.FILE_STATUS_QUEUED) {
  822. file.file_status = FileItem.FILE_STATUS_QUEUED;
  823. this.file_queue.unshift(file);
  824. this.queued_uploads++;
  825. }
  826. return true;
  827. } else {
  828. return false;
  829. }
  830. }
  831. private function GetStats():Object {
  832. return {
  833. in_progress : this.current_file_item == null ? 0 : 1,
  834. files_queued : this.queued_uploads,
  835. successful_uploads : this.successful_uploads,
  836. upload_errors : this.upload_errors,
  837. upload_cancelled : this.upload_cancelled,
  838. queue_errors : this.queue_errors
  839. };
  840. }
  841. private function SetStats(stats:Object):void {
  842. this.successful_uploads = typeof(stats["successful_uploads"]) === "number" ? stats["successful_uploads"] : this.successful_uploads;
  843. this.upload_errors = typeof(stats["upload_errors"]) === "number" ? stats["upload_errors"] : this.upload_errors;
  844. this.upload_cancelled = typeof(stats["upload_cancelled"]) === "number" ? stats["upload_cancelled"] : this.upload_cancelled;
  845. this.queue_errors = typeof(stats["queue_errors"]) === "number" ? stats["queue_errors"] : this.queue_errors;
  846. }
  847. private function GetFile(file_id:String):Object {
  848. var file_index:Number = this.FindIndexInFileQueue(file_id);
  849. if (file_index >= 0) {
  850. var file:FileItem = this.file_queue[file_index];
  851. } else {
  852. if (this.current_file_item != null) {
  853. file = this.current_file_item;
  854. } else {
  855. for (var i:Number = 0; i < this.file_queue.length; i++) {
  856. file = this.file_queue[i];
  857. if (file != null) break;
  858. }
  859. }
  860. }
  861. if (file == null) {
  862. return null;
  863. } else {
  864. return file.ToJavaScriptObject();
  865. }
  866. }
  867. private function GetFileByIndex(index:Number):Object {
  868. if (index < 0 || index > this.file_index.length - 1) {
  869. return null;
  870. } else {
  871. return this.file_index[index].ToJavaScriptObject();
  872. }
  873. }
  874. private function GetFileByQueueIndex(index:Number):Object {
  875. if (index < 0 || index > this.file_queue.length - 1) {
  876. return null;
  877. } else {
  878. return this.file_queue[index].ToJavaScriptObject();
  879. }
  880. }
  881. private function AddFileParam(file_id:String, name:String, value:String):Boolean {
  882. var item:FileItem = this.FindFileInFileIndex(file_id);
  883. if (item != null) {
  884. item.AddParam(name, value);
  885. return true;
  886. }
  887. else {
  888. return false;
  889. }
  890. }
  891. private function RemoveFileParam(file_id:String, name:String):Boolean {
  892. var item:FileItem = this.FindFileInFileIndex(file_id);
  893. if (item != null) {
  894. item.RemoveParam(name);
  895. return true;
  896. }
  897. else {
  898. return false;
  899. }
  900. }
  901. private function SetUploadURL(url:String):void {
  902. if (typeof(url) !== "undefined" && url !== "") {
  903. this.uploadURL = url;
  904. }
  905. }
  906. private function SetPostParams(post_object:Object):void {
  907. if (typeof(post_object) !== "undefined" && post_object !== null) {
  908. this.uploadPostObject = post_object;
  909. }
  910. }
  911. private function SetFileTypes(types:String, description:String):void {
  912. this.fileTypes = types;
  913. this.fileTypesDescription = description;
  914. this.LoadFileExensions(this.fileTypes);
  915. }
  916. // Sets the file size limit. Accepts size values with units: 100 b, 1KB, 23Mb, 4 Gb
  917. // Parsing is not robust. "100 200 MB KB B GB" parses as "100 MB"
  918. private function SetFileSizeLimit(size:String):void {
  919. var value:Number = 0;
  920. var unit:String = "kb";
  921. // Trim the string
  922. var trimPattern:RegExp = /^\s*|\s*$/;
  923. size = size.toLowerCase();
  924. size = size.replace(trimPattern, "");
  925. // Get the value part
  926. var values:Array = size.match(/^\d+/);
  927. if (values !== null && values.length > 0) {
  928. value = parseInt(values[0]);
  929. }
  930. if (isNaN(value) || value < 0) value = 0;
  931. // Get the units part
  932. var units:Array = size.match(/(b|kb|mb|gb)/);
  933. if (units != null && units.length > 0) {
  934. unit = units[0];
  935. }
  936. // Set the multiplier for converting the unit to bytes
  937. var multiplier:Number = 1024;
  938. if (unit === "b")
  939. multiplier = 1;
  940. else if (unit === "mb")
  941. multiplier = 1048576;
  942. else if (unit === "gb")
  943. multiplier = 1073741824;
  944. this.fileSizeLimit = value * multiplier;
  945. }
  946. private function SetFileUploadLimit(file_upload_limit:Number):void {
  947. if (file_upload_limit < 0) file_upload_limit = 0;
  948. this.fileUploadLimit = file_upload_limit;
  949. }
  950. private function SetFileQueueLimit(file_queue_limit:Number):void {
  951. if (file_queue_limit < 0) file_queue_limit = 0;
  952. this.fileQueueLimit = file_queue_limit;
  953. }
  954. private function SetFilePostName(file_post_name:String):void {
  955. if (file_post_name != "") {
  956. this.filePostName = file_post_name;
  957. }
  958. }
  959. private function SetUseQueryString(use_query_string:Boolean):void {
  960. this.useQueryString = use_query_string;
  961. }
  962. private function SetRequeueOnError(requeue_on_error:Boolean):void {
  963. this.requeueOnError = requeue_on_error;
  964. }
  965. private function SetHTTPSuccess(http_status_codes:*):void {
  966. this.httpSuccess = [];
  967. if (typeof http_status_codes === "string") {
  968. var status_code_strings:Array = http_status_codes.replace(" ", "").split(",");
  969. for each (var http_status_string:String in status_code_strings)
  970. {
  971. try {
  972. this.httpSuccess.push(Number(http_status_string));
  973. } catch (ex:Object) {
  974. // Ignore errors
  975. this.Debug("Could not add HTTP Success code: " + http_status_string);
  976. }
  977. }
  978. }
  979. else if (typeof http_status_codes === "object" && typeof http_status_codes.length === "number") {
  980. for each (var http_status:* in http_status_codes)
  981. {
  982. try {
  983. this.Debug("adding: " + http_status);
  984. this.httpSuccess.push(Number(http_status));
  985. } catch (ex:Object) {
  986. this.Debug("Could not add HTTP Success code: " + http_status);
  987. }
  988. }
  989. }
  990. }
  991. private function SetAssumeSuccessTimeout(timeout_seconds:Number):void {
  992. this.assumeSuccessTimeout = timeout_seconds < 0 ? 0 : timeout_seconds;
  993. }
  994. private function SetDebugEnabled(debug_enabled:Boolean):void {
  995. this.debugEnabled = debug_enabled;
  996. }
  997. /* ************