-
Notifications
You must be signed in to change notification settings - Fork 56
/
BulkLoader.as
1939 lines (1770 loc) · 89.6 KB
/
BulkLoader.as
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** BulkLoader: manage multiple loadings in Actioncript 3.
*
*
* @author Arthur Debert
*/
/**
* Licensed under the MIT License
*
* Copyright (c) 2006-2007 Arthur Debert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://code.google.com/p/bulk-loader/
* http://www.opensource.org/licenses/mit-license.php
*
*/
package br.com.stimuli.loading {
import br.com.stimuli.loading.loadingtypes.*;
import flash.display.*;
import flash.events.*;
import flash.media.Sound;
import flash.net.*;
import flash.utils.*;
/**
* Dispatched on download progress by any of the items to download.
*
* @eventType br.com.stimuli.loading.BulkProgressEvent.PROGRESS
*/
[Event(name="progress", type="br.com.stimuli.loading.BulkProgressEvent")]
/**
* Dispatched when all items have been downloaded and parsed. Note that this event only fires if there are no errors.
*
* @eventType br.com.stimuli.loading.BulkProgressEvent.COMPLETE
*/
[Event(name="complete", type="br.com.stimuli.loading.BulkProgressEvent")]
/**
* Manages loading for simultaneous items and multiple formats.
* Exposes a simpler interface, with callbacks instead of events for each item to be loaded (but still dispatched "global" events).
* The number of simultaneous connections is configurable.
*
* @example Basic usage:<listing version="3.0">
import br.com.stimuli.loading.BulkLoader;
/ /instantiate a BulkLoader with a name : a way to reference this instance from another classes without having to set a expolicit reference on many places
var bulkLoader : BulkLoader = new BulkLoader("main loading");
// add items to be loaded
bulkLoader.add("my_xml_file.xml");
bulkLoader.add("main.swf");
// you can also use a URLRequest object
var backgroundURL : URLRequest = new URLRequest("background.jpg");
bulkLoader.add(backgroundURL);
// add event listeners for the loader itself :
// event fired when all items have been loaded and nothing has failed!
bulkLoader.addEventListener(BulkLoader.COMPLETE, onCompleteHandler);
// event fired when loading progress has been made:
bulkLoader.addEventListener(BulkLoader.PROGRESS, _onProgressHandler);
// start loading all items
bulkLoader.start();
function _onProgressHandler(evt : ProgressEvent) : void{
trace("Loaded" , evt.bytesLoaded," of ", evt.bytesTotal);
}
function onCompleteHandler(evt : ProgressEvent) : void{
trace("All items are loaeded and ready to consume");
// grab the main movie clip:
var mainMovie : MovieClip = bulkLoader.getMovieClip("main.swf");
// Get the xml object:
var mXML : XML = bulkLoader.getXML("my_xml_file.xml");
// grab the bitmap for the background image by a string:
var myBitmap : Bitmap = bulkLoader.getBitmap("background.jpg");
// grab the bitmap for the background image using the url rquest object:
var myBitmap : Bitmap = bulkLoader.getBitmap(backgroundURL);
}
// In any other class you can access those assets without having to pass around references to the bulkLoader instance.
// In another class you get get a reference to the "main loading" bulkLoader:
var mainLoader : BulkLoader = BulkLoader.getLoader("main loading");
// now grab the xml:
var mXML : XML = mainLoader.getXML("my_xml_file.xml");
// or shorter:
var mXML : XML = BulkLoader.getLoader("main loading").getXML("my_xml_file.xml");
* </listing>
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*
* @author Arthur Debert
* @since 15.09.2007
*/
public class BulkLoader extends EventDispatcher {
/** Version. Useful for debugging. */
public static const VERSION : String = "$Id$";
/** Tells this class to use a <code>Loader</code> object to load the item.*/
public static const TYPE_BINARY : String = "binary";
/** Tells this class to use a <code>Loader</code> object to load the item.*/
public static const TYPE_IMAGE : String = "image";
/** Tells this class to use a <code>Loader</code> object to load the item.*/
public static const TYPE_MOVIECLIP : String = "movieclip";
/** Tells this class to use a <code>Sound</code> object to load the item.*/
public static const TYPE_SOUND : String = "sound";
/** Tells this class to use a <code>URLRequest</code> object to load the item.*/
public static const TYPE_TEXT : String = "text";
/** Tells this class to use a <code>XML</code> object to load the item.*/
public static const TYPE_XML : String = "xml";
/** Tells this class to use a <code>NetStream</code> object to load the item.*/
public static const TYPE_VIDEO : String = "video";
public static const AVAILABLE_TYPES : Array = [TYPE_VIDEO, TYPE_XML, TYPE_TEXT, TYPE_SOUND, TYPE_MOVIECLIP, TYPE_IMAGE, TYPE_BINARY]
/** List of all file extensions that the <code>BulkLoader</code> knows how to guess.
* Availabe types: swf, jpg, jpeg, gif, png. */
public static var AVAILABLE_EXTENSIONS : Array = ["swf", "jpg", "jpeg", "gif", "png", "flv", "mp3", "xml", "txt", "js" ];
/** List of file extensions that will be automagically use a <code>Loader</code> object for loading.
* Availabe types: swf, jpg, jpeg, gif, png, image.
*/
public static var IMAGE_EXTENSIONS : Array = [ "jpg", "jpeg", "gif", "png"];
public static var MOVIECLIP_EXTENSIONS : Array = ['swf'];
/** List of file extensions that will be automagically treated as text for loading.
* Availabe types: txt, js, xml, php, asp .
*/
public static var TEXT_EXTENSIONS : Array = ["txt", "js", "php", "asp", "py" ];
/** List of file extensions that will be automagically treated as video for loading.
* Availabe types: flv, f4v, f4p.
*/
public static var VIDEO_EXTENSIONS : Array = ["flv", "f4v", "f4p", "mp4"];
/** List of file extensions that will be automagically treated as sound for loading.
* Availabe types: mp3, f4a, f4b.
*/
public static var SOUND_EXTENSIONS : Array = ["mp3", "f4a", "f4b"];
public static var XML_EXTENSIONS : Array = ["xml"];
/** @private */
public static var _customTypesExtensions : Object ;
/**
* The name of the event
* @eventType progress
*/
public static const PROGRESS : String = "progress";
/**
* The name of the event
* @eventType complete
*/
public static const COMPLETE : String = "complete";
/**
* The name of the event
* @eventType httpStatus
*/
public static const HTTP_STATUS : String = "httpStatus";
/**
* The name of the event
* @eventType error
*/
public static const ERROR : String = "error";
/**
* The name of the event
* @eventType securityError
*/
public static const SECURITY_ERROR : String = "securityError";
/**
* The name of the event
* @eventType error
*/
public static const OPEN : String = "open";
/**
* The name of the event
* @eventType error
*/
public static const CAN_BEGIN_PLAYING : String = "canBeginPlaying";
public static const CHECK_POLICY_FILE : String = "checkPolicyFile"
// properties on adding a new url:
/** If <code>true</code> a random query (or post data parameter) will be added to prevent caching. Checked when adding a new item to load.
* @see #add()
*/
public static const PREVENT_CACHING : String = "preventCache";
/** An array of RequestHeader objects to be used when contructing the <code>URLRequest</code> object. If the <code>url</code> parameter is passed as a <code>URLRequest</code> object it will be ignored. Checked when adding a new item to load.
* @see #add()
*/
public static const HEADERS : String = "headers";
/** An object definig the loading context for this load operario. If this item is of <code>TYPE_SOUND</code>, a <code>SoundLoaderContext</code> is expected. If it's a <code>TYPE_IMAGE</code> a LoaderContext should be passed. Checked when adding a new item to load.
* @see #add()
*/
public static const CONTEXT : String = "context";
/** A <code>String</code> to be used to identify an item to load, can be used in any method that fetches content (as the key parameters), stops, removes and resume items. Checked when adding a new item to load.
* @see #add()
* @see #getContent()
* @see #pause()
* @see #resume()
* @see #removeItem()
*/
public static const ID : String = "id";
/** An <code>int</code> that controls which items are loaded first. Items with a higher <code>PRIORITY</code> will load first. If more than one item has the same <code>PRIORITY</code> number, the order in which they are added will be taken into consideration. Checked when adding a new item to load.
* @see #add()
*/
public static const PRIORITY : String = "priority";
/** The number, as an <code>int</code>, to retry downloading an item in case it fails. Checked when adding a new item to load.
* @default 3
* @see #add()
*/
public static const MAX_TRIES : String = "maxTries";
/* An <code>int</code> that sets a relative size of this item. It's used on the <code>BulkProgressEvent.weightPercent</code> property. This allows bulk downloads with more items that connections and with widely varying file sizes to give a more accurate progress information. Checked when adding a new item to load.
* @see #add()
* @default 3
*/
public static const WEIGHT : String = "weight";
/* An <code>Boolean</code> that if true and applied on a video item will pause the video on the start of the loading operation.
* @see #add()
* @default false
*/
public static const PAUSED_AT_START : String = "pausedAtStart";
public static const GENERAL_AVAILABLE_PROPS : Array = [
WEIGHT, MAX_TRIES, HEADERS, ID, PRIORITY, PREVENT_CACHING, "type"];
/** @private
*/
public var _name : String;
/** @private */
public var _id : int;
/** @private */
public static var _instancesCreated : int = 0;
/** @private */
public var _items : Array = [];
/** @private */
public var _contents : Dictionary = new Dictionary(true);
/** @private */
public static var _allLoaders : Object = {};
/** @private */
public var _additionIndex : int = 0;
// Maximum number of simultaneous open requests
public static const DEFAULT_NUM_CONNECTIONS : int = 12;
/** @private */
public var _numConnections : int = DEFAULT_NUM_CONNECTIONS;
public var maxConnectionsPerHost : int = 2;
/** @private */
public var _connections : Object;
/**
* @private
**/
public var _loadedRatio : Number = 0;
/** @private */
public var _itemsTotal : int = 0;
/** @private */
public var _itemsLoaded : int = 0;
/** @private
*/
public var _totalWeight : int = 0;
/** @private
*/
public var _bytesTotal : int = 0;
/** @private
*/
public var _bytesTotalCurrent : int = 0;
/** @private
*/
public var _bytesLoaded : int = 0;
/** @private
*/
public var _percentLoaded : Number = 0;
/** @private
*/
public var _weightPercent : Number;
/**The average latency (in miliseconds) for the entire loading.*/
public var avgLatency : Number;
/**The average speed (in kb/s) for the entire loading.*/
public var speedAvg : Number;
/** @private
*/
public var _speedTotal : Number;
/** @private
*/
public var _startTime : int ;
/** @private
*/
public var _endTIme : int;
/** @private
*/
public var _lastSpeedCheck : int;
/** @private
*/
public var _lastBytesCheck : int;
/** @private */
public var _speed : Number;
/**Time in seconds for the whole loading. Only available after everything is laoded*/
public var totalTime : Number;
/** LogLevel: Outputs everything that is happening. Usefull for debugging. */
public static const LOG_VERBOSE : int = 0;
/**Ouputs noteworthy events such as when an item is started / finished loading.*/
public static const LOG_INFO : int = 2;
/**Ouputs noteworthy events such as when an item is started / finished loading.*/
public static const LOG_WARNINGS : int = 3;
/**Will only trace errors. Defaut level*/
public static const LOG_ERRORS : int = 4;
/**Nothing will be logged*/
public static const LOG_SILENT : int = 10;
/**The logging level <code>BulkLoader</code> will use.
* @see #LOG_VERBOSE
* @see #LOG_SILENT
* @see #LOG_ERRORS
* @see #LOG_INFO
*/
public static const DEFAULT_LOG_LEVEL : int = LOG_ERRORS;
/** @private */
public var logLevel: int = DEFAULT_LOG_LEVEL;
/** @private */
public var _allowsAutoIDFromFileName : Boolean = false;
/** @private */
public var _isRunning : Boolean;
/** @private */
public var _isFinished : Boolean;
/** @private */
public var _isPaused : Boolean = true;
/** @private */
public var _logFunction : Function = trace;
/** @private */
public var _stringSubstitutions : Object;
/** @private */
public static var _typeClasses : Object = {
image: ImageItem,
movieclip: ImageItem,
xml: XMLItem,
video: VideoItem,
sound: SoundItem,
text: URLItem,
binary: BinaryItem
}
/** Creates a new BulkLoader object identifiable by the <code>name</code> parameter. The <code>name</code> parameter must be unique, else an Error will be thrown.
*
* @param name A name that can be used later to reference this loader in a static context,
* @param numConnections The number of maximum simultaneous connections to be open.
* @param logLevel At which level should traces be outputed. By default only errors will be traced.
*
* @see #numConnections
* @see #log()
*/
public function BulkLoader(name : String, numConnections : int = BulkLoader.DEFAULT_NUM_CONNECTIONS, logLevel : int = BulkLoader.DEFAULT_LOG_LEVEL){
if (Boolean(_allLoaders[name])){
__debug_print_loaders();
throw new Error ("BulkLoader with name'" + name +"' has already been created.");
}else if (!name ){
throw new Error ("Cannot create a BulkLoader instance without a name");
}
_allLoaders[name] = this;
if (numConnections > 0){
this._numConnections = numConnections;
}
this.logLevel = logLevel;
_name = name;
_instancesCreated ++;
_id = _instancesCreated;
_additionIndex = 0;
// we create a mock event listener for errors, else Unhandled errors will bubble and display an stack trace to the end user:
addEventListener(BulkLoader.ERROR, _swallowError, false, 1, true);
}
/** Creates a BulkLoader instance with an unique name. This is useful for situations where you might be creating
* many BulkLoader instances and it gets tricky to garantee that no other instance is using that name.
* @param numConnections The number of maximum simultaneous connections to be open.
* @param logLevel At which level should traces be outputed. By default only errors will be traced.
* @return A BulkLoader intance, with an unique name.
*/
public static function createUniqueNamedLoader( numConnections : int=BulkLoader.DEFAULT_NUM_CONNECTIONS, logLevel : int = BulkLoader.DEFAULT_LOG_LEVEL) : BulkLoader{
return new BulkLoader(BulkLoader.getUniqueName(), numConnections, logLevel);
}
public static function getUniqueName() : String{
return "BulkLoader-" + _instancesCreated;
}
/** Fetched a <code>BulkLoader</code> object created with the <code>name</code> parameter.
* This is usefull if you must access loades assets from another scope, without having to pass direct references to this loader.
* @param name The name of the loader to be fetched.
* @return The BulkLoader instance that was registred with that name. Returns null if none is found.
*/
public static function getLoader(name :String) : BulkLoader{
return BulkLoader._allLoaders[name] as BulkLoader;
}
/** @private */
public static function _hasItemInBulkLoader(key : *, atLoader : BulkLoader) : Boolean{
var item : LoadingItem = atLoader.get(key);
if (item) {
return true;
}
return false;
}
/** Checks if there is <b>loaded</b> item in this <code>BulkLoader</code>.
* @param The url (as a <code>String</code> or a <code>URLRequest</code> object)or an id (as a <code>String</code>) by which the item is identifiable.
* @param searchAll If true will search through all <code>BulkLoader</code> instances. Else will only search this one.
* @return True if a loader has a <b>loaded</b> item stored.
*/
public function hasItem(key : *, searchAll : Boolean = true) : Boolean{
var loaders : *;
if (searchAll){
loaders = _allLoaders;
}else{
loaders = [this];
}
for each (var l : BulkLoader in loaders){
if (_hasItemInBulkLoader(key, l )) return true;
}
return false;
}
/** Checks which <code>BulkLoader</code> has an item by the given key.
* @param The url (as a <code>String</code> or a <code>URLRequest</code> object)or an id (as a <code>String</code>) by which the item is identifiable.
* @return The <code>BulkLoader</code> instance that has the given key or <code>null</code> if no key if found in any loader.
*/
public static function whichLoaderHasItem(key : *) : BulkLoader{
for each (var l : BulkLoader in _allLoaders){
if (BulkLoader._hasItemInBulkLoader(key, l )) return l;
}
return null;
}
/** Adds a new assets to be loaded. The <code>BulkLoader</code> object will manage diferent assets type. If the right type cannot be infered from the url termination (e.g. the url ends with ".swf") the BulkLoader will relly on the <code>type</code> property of the <code>props</code> parameter. If both are set, the <code>type</code> property of the props object will overrite the one defined in the <code>url</code>. In case none is specified and the url won't hint at it, the type <code>TYPE_TEXT</code> will be used.
*
* @param url String OR URLRequest A <code>String</code> or a <code>URLRequest</code> instance.
* @param props An object specifing extra data for this loader. The following properties are supported:<p/>
* <table>
* <th>Property name</th>
* <th>Class constant</th>
* <th>Data type</th>
* <th>Description</th>
* <tr>
* <td>preventCache</td>
* <td><a href="#PREVENT_CACHING">PREVENT_CACHING</a></td>
* <td><code>Boolean</code></td>
* <td>If <code>true</code> a random query string will be added to the url (or a post param in case of post reuquest).</td>
* </tr>
* <tr>
* <td>id</td>
* <td><a href="#ID">ID</a></td>
* <td><code>String</code></td>
* <td>A string to identify this item. This id can be used in any method that uses the <code>key</code> parameter, such as <code>pause, removeItem, resume, getContent, getBitmap, getBitmapData, getXML, getMovieClip and getText</code>.</td>
* </tr>
* <tr>
* <td>priority</td.
* <td><a href="#PRIORITY">PRIORITY</a></td>
* <td><code>int</code></td>
* <td>An <code>int</code> used to order which items till be downloaded first. Items with a higher priority will download first. For items with the same priority they will be loaded in the same order they've been added.</td>
* </tr>
* <tr>
* <td>maxTries</td.
* <td><a href="#MAX_TRIES">MAX_TRIES</a></td>
* <td><code>int</code></td>
* <td>The number of retries in case the lading fails, defaults to 3.</td>
* </tr>
* <tr>
* <td>weight</td.
* <td><a href="#WEIGHT">WEIGHT</a></td>
* <td><code>int</code></td>
* <td>A number that sets an arbitrary relative size for this item. See #weightPercent.</td>
* </tr>
* <tr>
* <td>headers</td.
* <td><a href="#HEADERS">HEADERS</a></td>
* <td><code>Array</code></td>
* <td>An array of <code>RequestHeader</code> objects to be used when constructing the URL. If the <code>url</code> parameter is passed as a string, <code>BulkLoader</code> will use these request headers to construct the url.</td>
* </tr>
* <tr>
* <td>context</td.
* <td><a href="#CONTEXT">CONTEXT</a></td>
* <td><code>LoaderContext or SoundLoaderContext</code></td>
* <td>An object definig the loading context for this load operario. If this item is of <code>TYPE_SOUND</code>, a <code>SoundLoaderContext</code> is expected. If it's a <code>TYPE_IMAGE</code> a LoaderContext should be passed.</td>
* </tr>
* <tr>
* <td>pausedAtStart</td.
* <td><a href="#PAUSED_AT_START">PAUSED_AT_START</a></td>
* <td><code>Boolean</code></td>
* <td>If true, the nestream will be paused when loading has begun.</td>
* </tr>
* </table>
* You can use string substitutions (variable expandsion).
* @example Retriving contents:<listing version="3.0">
import br.stimuli.loaded.BulkLoader;
var bulkLoader : BulkLoader = new BulkLoader("main");
// simple item:
bulkLoader.add("config.xml");
// use an id that can be retirved latterL
bulkLoader.add("background.jpg", {id:"bg"});
// or use a static var to have auto-complete and static checks on your ide:
bulkLoader.add("background.jpg", {BulkLoader.ID:"bg"});
// loads the languages.xml file first and parses before all items are done:
public function parseLanguages() : void{
var theLangXML : XML = bulkLoader.getXML("langs");
// do something wih the xml:
doSomething(theLangXML);
}
bulkLoader.add("languages.xml", {priority:10, onComplete:parseLanguages, id:"langs"});
// Start the loading operation with only 3 simultaneous connections:
bulkLoader.start(3)
</listing>
* @see #stringSubstitutions
*
*/
public function add(url : *, props : Object= null ) : LoadingItem {
if(!_name){
throw new Error("[BulkLoader] Cannot use an instance that has been cleared from memory (.clear())");
}
if(!url || !String(url)){
throw new Error("[BulkLoader] Cannot add an item with a null url")
}
props = props || {};
if (url is String){
url = new URLRequest(BulkLoader.substituteURLString(url, _stringSubstitutions));
if(props[HEADERS]){
url.requestHeaders = props[HEADERS];
}
}else if (!url is URLRequest){
throw new Error("[BulkLoader] cannot add object with bad type for url:'" + url.url);
}
var item : LoadingItem = get(props[ID]);
// have already loaded this?
if( item ){
log("Add received an already added id: " + props[ID] + ", not adding a new item");
return item;
}
var type : String;
if (props["type"]) {
type = props["type"].toLowerCase();
// does this type exist?
if (AVAILABLE_TYPES.indexOf(type)==-1){
log("add received an unknown type:", type, "and will cast it to text", LOG_WARNINGS);
}
}
if (!type){
type = guessType(url.url);
}
_additionIndex ++;
item = new _typeClasses[type] (url, type , _instancesCreated + "_" + String(_additionIndex));
if (!props["id"] && _allowsAutoIDFromFileName){
props["id"] = getFileName(url.url);
log("Adding automatic id from file name for item:", item , "( id= " + props["id"] + " )");
}
var errors : Array = item._parseOptions(props);
for each (var error : String in errors){
log(error, LOG_WARNINGS);
}
log("Added",item, LOG_VERBOSE);
// properties from the props argument
item._addedTime = getTimer();
item._additionIndex = _additionIndex;
// add a lower priority than default, else the event for all items complete will fire before
// individual listerners attached to the item
item.addEventListener(Event.COMPLETE, _onItemComplete, false, int.MIN_VALUE, true);
// need an extra event listener to increment items loaded, because this must happen
// **before** the item's normal event, or else client code will get a dummy value for it
item.addEventListener(Event.COMPLETE, _incrementItemsLoaded, false, int.MAX_VALUE, true);
item.addEventListener(ERROR, _onItemError, false, 0, true);
item.addEventListener(Event.OPEN, _onItemStarted, false, 0, true);
item.addEventListener(ProgressEvent.PROGRESS, _onProgress, false, 0, true);
_items.push(item);
_itemsTotal += 1;
_totalWeight += item.weight;
sortItemsByPriority();
_isFinished = false;
if (!_isPaused){
_loadNext();
}
return item;
}
/** Start loading all items added previously
* @param withConnections [optional]The maximum number of connections to make at the same time. If specified, will override the parameter passed (if any) to the constructor.
* @see #numConnections
* @see #see #BulkLoader()
*/
public function start(withConnections : int = -1 ) : void{
if (withConnections > 0){
_numConnections = withConnections;
}
if(_connections){
_loadNext();
return;
}
_startTime = getTimer();
_connections = {};
_loadNext();
_isRunning = true;
_lastBytesCheck = 0;
_lastSpeedCheck = getTimer();
_isPaused = false;
}
/** Forces the item specified by key to be reloaded right away. This will stop any open connection as needed.
* @param key The url request, url as a string or a id from which the asset was created.
* @return <code>True</code> if an item with that key is found, <code>false</code> otherwise.
*/
public function reload(key : *) : Boolean{
var item : LoadingItem = get(key);
if(!item){
return false;
}
_removeFromItems(item);
_removeFromConnections(item);
item.stop();
item.cleanListeners();
item.status = null;
_isFinished = false;
item._addedTime = getTimer();
item._additionIndex = _additionIndex ++;
item.addEventListener(Event.COMPLETE, _onItemComplete, false, int.MIN_VALUE, true);
item.addEventListener(Event.COMPLETE, _incrementItemsLoaded, false, int.MAX_VALUE, true);
item.addEventListener(ERROR, _onItemError, false, 0, true);
item.addEventListener(Event.OPEN, _onItemStarted, false, 0, true);
item.addEventListener(ProgressEvent.PROGRESS, _onProgress, false, 0, true);
_items.push(item);
_itemsTotal += 1;
_totalWeight += item.weight;
sortItemsByPriority();
_isFinished = false;
loadNow(item);
return true;
}
/** Forces the item specified by key to be loaded right away. This will stop any open connection as needed.
* If needed, the connection to be closed will be the one with the lower priority. In case of a tie, the one
* that has more bytes to complete will be removed. The item to load now will be automatically be set the highest priority value in this BulkLoader instance.
* @param key The url request, url as a string or a id from which the asset was created.
* @return <code>True</code> if an item with that key is found, <code>false</code> otherwise.
*/
public function loadNow(key : *) : Boolean{
var item : LoadingItem = get(key);
if(!item){
return false;
}
if(!_connections){
_connections = {};
}
// is this item already loaded or loading?
if (item.status == LoadingItem.STATUS_FINISHED ||
item.status == LoadingItem.STATUS_STARTED){
return true;
}
// do we need to remove an item from the open connections?
if (_getNumConnections() >= numConnections || _getNumConnectionsForItem(item) >= maxConnectionsPerHost ){
//which item should we remove?
var itemToRemove : LoadingItem = _getLeastUrgentOpenedItem();
pause(itemToRemove);
_removeFromConnections(itemToRemove);
itemToRemove.status = null;
}
// update the item's piority so that subsequent calls to loadNow don't close a
// connection we've just started to load
item._priority = highestPriority;
_loadNext(item);
return true;
}
/** @private
* Figures out which item to remove from open connections, comparation is done by priority
* and then by bytes remaining
*/
public function _getLeastUrgentOpenedItem() : LoadingItem{
// TODO: make sure we remove from the righ hostname
var itemsToLoad : Array = _getAllConnections();
itemsToLoad.sortOn(["priority", "bytesRemaining", "_additionIndex"], [Array.NUMERIC, Array.DESCENDING , Array.NUMERIC, Array.NUMERIC])
var toRemove : LoadingItem = LoadingItem(itemsToLoad[0]);
return toRemove;
}
/** Register a new file extension to be loaded as a given type. This is used both in the guessing of types from the url and affects how loading is done for each type.
* If you are adding an extension to be of a type you are creating, you must pass the <code>withClass</code> parameter, which should be a class that extends LoadingItem.
* @param extension The file extension to be used (can include the dot or not)
* @param atType Which type this extension will be associated with.
* @param withClass For new types (not new extensions) wich class that extends LoadingItem should be used to mange this item.
* @see #TYPE_IMAGE
* @see #TYPE_VIDEO
* @see #TYPE_SOUND
* @see #TYPE_TEXT
* @see #TYPE_XML
* @see #TYPE_MOVIECLIP
* @see #LoadingItem
*
* @return A <code>Boolean</code> indicating if the new extension was registered.
*/
public static function registerNewType( extension : String, atType : String, withClass : Class = null) : Boolean {
// Normalize extension
if (extension.charAt(0) == ".") extension = extension.substring(1);
if(!_customTypesExtensions) _customTypesExtensions = {};
// Is this a new type?
if (AVAILABLE_TYPES.indexOf(atType) == -1){
// new type: we need a class for that:
if (!Boolean(withClass) ){
throw new Error("[BulkLoader]: When adding a new type and extension, you must determine which class to use");
}
// add that class to the available classes
_typeClasses[atType] = withClass;
if(!_customTypesExtensions[atType]){
_customTypesExtensions[atType] = [];
AVAILABLE_TYPES.push(atType);
}
_customTypesExtensions[atType].push( extension);
return true;
}else{
// do have this exension registred for this type?
if(_customTypesExtensions[atType])
_customTypesExtensions[atType].push( extension);
}
var extensions : Array ;
var options : Object = { };
options[TYPE_IMAGE] = IMAGE_EXTENSIONS,
options[TYPE_MOVIECLIP] = MOVIECLIP_EXTENSIONS,
options[TYPE_VIDEO] = VIDEO_EXTENSIONS,
options[TYPE_SOUND] = SOUND_EXTENSIONS,
options[TYPE_TEXT] = TEXT_EXTENSIONS,
options[TYPE_XML] = XML_EXTENSIONS,
extensions = options[atType];
if (extensions && extensions.indexOf(extension) == -1){
extensions.push(extension);
return true;
}
return false;
}
public function _getNextItemToLoad() : LoadingItem{
// check for "stale items"
_getAllConnections().forEach(function(i : LoadingItem, ...rest) : void{
if(i.status == LoadingItem.STATUS_ERROR && i.numTries >= i.maxTries){
_removeFromConnections(i);
}
});
for each (var checkItem:LoadingItem in _items){
if (!checkItem._isLoading && checkItem.status != LoadingItem.STATUS_STOPPED && _canOpenConnectioForItem(checkItem)){
return checkItem;
}
}
return null;
}
// if toLoad is specified it will take precedence over whoever is queued cut line
/** @private */
public function _loadNext(toLoad : LoadingItem = null) : Boolean{
if(_isFinished){
return false;
}if (!_connections){
_connections = {};
}
var next : Boolean = false;
toLoad = toLoad || _getNextItemToLoad();
if (toLoad){
next = true;
_isRunning = true;
// need to check again, as _loadNext might have been called with an item to be loaded forcefully.
if(_canOpenConnectioForItem(toLoad)){
var connectionsForItem : Array = _getConnectionsForHostName(toLoad.hostName)
connectionsForItem.push(toLoad);
toLoad.load();
//trace("begun loading", toLoad.url.url);//, _getNumConnectionsForItem(toLoad) + "/" + maxConnectionsPerHost, _getNumConnections() + "/" + numConnections);
log("Will load item:", toLoad, LOG_INFO);
}
// if we've got any more connections to open, load the next item
if(_getNextItemToLoad()){
_loadNext();
}
}
return next;
}
/** @private */
public function _onItemComplete(evt : Event) : void {
var item : LoadingItem = evt.target as LoadingItem;
_removeFromConnections(item);
log("Loaded ", item, LOG_INFO);
log("Items to load", getNotLoadedItems(), LOG_VERBOSE);
item.cleanListeners();
_contents[item.url.url] = item.content;
var next : Boolean= _loadNext();
var allDone : Boolean = _isAllDoneP();
if(allDone) {
_onAllLoaded();
}
evt.stopPropagation();
}
/** @private
*/
public function _incrementItemsLoaded(evt : Event) : void{
_itemsLoaded ++;
}
/** @private */
public function _updateStats() : void {
avgLatency = 0;
speedAvg = 0;
var totalLatency : Number = 0;
var totalBytes : int = 0;
_speedTotal = 0;
var num : Number = 0;
for each(var item : LoadingItem in _items){
if (item._isLoaded && item.status != LoadingItem.STATUS_ERROR){
totalLatency += item.latency;
totalBytes += item.bytesTotal;
num ++;
}
}
_speedTotal = (totalBytes/1024) / totalTime;
avgLatency = totalLatency / num;
speedAvg = _speedTotal / num;
}
/** @private */
public function _removeFromItems(item : LoadingItem) : Boolean{
var removeIndex : int = _items.indexOf(item);
if(removeIndex > -1){
_items.splice( removeIndex, 1);
}else{
return false;
}
if(item._isLoaded){
_itemsLoaded --;
}
_itemsTotal --;
_totalWeight -= item.weight;
log("Removing " + item, LOG_VERBOSE);
item.removeEventListener(Event.COMPLETE, _onItemComplete, false)
item.removeEventListener(Event.COMPLETE, _incrementItemsLoaded, false)
item.removeEventListener(ERROR, _onItemError, false);
item.removeEventListener(Event.OPEN, _onItemStarted, false);
item.removeEventListener(ProgressEvent.PROGRESS, _onProgress, false);
return true;
}
/** @private */
public function _removeFromConnections(item : *) : Boolean{
if(!_connections || _getNumConnectionsForItem(item) == 0) return false;
var connectionsForHost : Array = _getConnectionsForHostName(item.hostName);(item);
var removeIndex : int = connectionsForHost.indexOf(item)
if(removeIndex > -1){
connectionsForHost.splice( removeIndex, 1);
return true;
}
return false;
}
public function _getNumConnectionsForHostname(hostname :String) : int{
var conns : Array = _getConnectionsForHostName(hostname);
if (!conns) {
return 0;
}
return conns.length;
}
/** @private */
public function _getNumConnectionsForItem(item :LoadingItem) : int{
var conns : Array = _getConnectionsForHostName(item.hostName);(item);
if (!conns) {
return 0;
}
return conns.length;
}
/** @private */
public function _getAllConnections() : Array {
var conns : Array = [];
for (var hostname : String in _connections){
conns = conns.concat ( _connections[hostname] ) ;
}
return conns;
}
/** @private **/
public function _getNumConnections() : int{
var connections : int = 0;
for (var hostname : String in _connections){
connections += _connections[hostname].length;
}
return connections;
}
public function _getConnectionsForHostName (hostname : String) : Array {
if (_connections[hostname] == null ){
_connections[hostname] = [];
}
return _connections[hostname];
}
public function _canOpenConnectioForItem(item :LoadingItem) : Boolean{
if (_getNumConnections() >= numConnections) return false;
if (_getNumConnectionsForItem(item) >= maxConnectionsPerHost) return false;
return true;
}
/** @private */
public function _onItemError(evt : ErrorEvent) : void{
var item : LoadingItem = evt.target as LoadingItem;
_removeFromConnections(item);
log("After " + item.numTries + " I am giving up on " + item.url.url, LOG_ERRORS);
log("Error loading", item, evt.text, LOG_ERRORS);
_loadNext();
//evt.stopPropagation();
//evt.currentTarget = item;
dispatchEvent(evt);
}
/** @private */
public function _onItemStarted(evt : Event) : void{
var item : LoadingItem = evt.target as LoadingItem;
log("Started loading", item, LOG_INFO);
dispatchEvent(evt);
}
/** @private */
public function _onProgress(evt : Event = null) : void{
// TODO: check these values are correct! tough _onProgress
var e : BulkProgressEvent = getProgressForItems(_items);
// update values:
_bytesLoaded = e.bytesLoaded;
_bytesTotal = e.bytesTotal;
_weightPercent = e.weightPercent;
_percentLoaded = e.percentLoaded;
_bytesTotalCurrent = e.bytesTotalCurrent;
_loadedRatio = e.ratioLoaded;
dispatchEvent(e);
}
/** Calculates the progress for a specific set of items.
* @param keys An <code>Array</code> containing keys (ids or urls) or <code>LoadingItem</code> objects to measure progress of.
* @return A <code>BulkProgressEvent</code> object with the current progress status.
* @see BulkProgressEvent
*/
public function getProgressForItems(keys : Array) : BulkProgressEvent{
_bytesLoaded = _bytesTotal = _bytesTotalCurrent = 0;
var localWeightPercent : Number = 0;
var localWeightTotal : int = 0;
var itemsStarted : int = 0;
var localWeightLoaded : Number = 0;
var localItemsTotal : int = 0;
var localItemsLoaded : int = 0;
var localBytesLoaded : int = 0;
var localBytesTotal : int = 0;
var localBytesTotalCurrent : int = 0;
var item : LoadingItem;