Commiting to continue stuff at home
[swf-overlay.git] / StreamInfo.as
1 package {
2 import flash.events.Event;
3 import flash.events.EventDispatcher;
4 import flash.utils.setInterval;
5 import flash.net.*
6
7 public class StreamInfo extends EventDispatcher {
8 private var request:URLRequest;
9 private var loader:URLLoader;
10 private var streamInfo = {};
11 private var lastUpdated:Array;
12 private var section:String;
13 private var fileLock = false;
14 private var loadCallback:Function;
15
16 public static const INFO_UPDATE = "info_update";
17
18 public function StreamInfo(section:String, refreshRate:int) {
19 this.request = new URLRequest("StreamInfo.txt");
20 this.loader = new URLLoader();
21 this.section = section;
22 setInterval(this.parse, refreshRate);
23 }
24
25 public function parse() {
26 if(!this.fileLock) {
27 this.loadCallback = this.onLoaded(this);
28
29 loader.addEventListener(Event.COMPLETE, this.loadCallback);
30 this.fileLock = true;
31 this.loader.load(this.request);
32 } else {
33 trace("Lock active, not doing anything.");
34 }
35 }
36
37 public function getStreamParameter(name:String) {
38 return this.streamInfo[name];
39 }
40
41 public function getLastUpdated():Array {
42 return this.lastUpdated;
43 }
44
45 private function releaseLock() {
46 this.fileLock = false;
47 }
48
49 private function onLoaded(streamInfo:StreamInfo):Function {
50 return function(e:Event):void {
51 //Deal with windows style line endings, and tabs.
52 var lines = streamInfo.loader.data.replace(/(\t|\r)/gi, "").split("\n");
53 var sectionLines:Array = streamInfo.extractSection(lines);
54 streamInfo.parseVars(sectionLines);
55 streamInfo.releaseLock();
56 streamInfo.loader.removeEventListener(Event.COMPLETE, streamInfo.loadCallback);
57 }
58 }
59
60 private function extractSection(lines:Array) {
61 var sectionLines:Array = new Array();
62 var foundFirstLineOfSection:Boolean = false;
63 for each(var line in lines) {
64 foundFirstLineOfSection = !foundFirstLineOfSection ? line.indexOf("[" + this.section + "]") >= 0 : !line.match(/\[\w+\]/);
65
66 if(foundFirstLineOfSection) {
67 sectionLines.push(line);
68 }
69 }
70
71 return sectionLines;
72 }
73
74 private function parseVars(lines:Array) {
75 var broadcastUpdate = false;
76 for each(var line in lines) {
77 var keyValue = line.split("=", 2).map(Util.trim);
78 if(keyValue.length == 2) {
79 if(this.streamInfo[keyValue[0]] != keyValue[1]) {
80 if(!broadcastUpdate) {
81 this.lastUpdated = new Array();
82 }
83
84 broadcastUpdate = true;
85
86 this.lastUpdated.push(keyValue[0]);
87 this.streamInfo[keyValue[0]] = keyValue[1];
88 }
89 }
90 }
91
92 if(broadcastUpdate) {
93 this.dispatchEvent(new Event(INFO_UPDATE));
94 }
95 }
96 }
97 }