package { import flash.events.Event; import flash.events.EventDispatcher; import flash.utils.setInterval; import flash.net.* public class StreamInfo extends EventDispatcher { private var request:URLRequest; private var loader:URLLoader; private var streamInfo = {}; private var lastUpdated:Array; private var section:String; private var fileLock = false; private var loadCallback:Function; public static const INFO_UPDATE = "info_update"; public function StreamInfo(section:String, refreshRate:int) { this.request = new URLRequest("StreamInfo.txt"); this.loader = new URLLoader(); this.section = section; setInterval(this.parse, refreshRate); } public function parse() { if(!this.fileLock) { this.loadCallback = this.onLoaded(this); loader.addEventListener(Event.COMPLETE, this.loadCallback); this.fileLock = true; this.loader.load(this.request); } else { trace("Lock active, not doing anything."); } } public function getStreamParameter(name:String) { return this.streamInfo[name]; } public function getLastUpdated():Array { return this.lastUpdated; } private function releaseLock() { this.fileLock = false; } private function onLoaded(streamInfo:StreamInfo):Function { return function(e:Event):void { //Deal with windows style line endings, and tabs. var lines = streamInfo.loader.data.replace(/(\t|\r)/gi, "").split("\n"); var sectionLines:Array = streamInfo.extractSection(lines); streamInfo.parseVars(sectionLines); streamInfo.releaseLock(); streamInfo.loader.removeEventListener(Event.COMPLETE, streamInfo.loadCallback); } } private function extractSection(lines:Array) { var sectionLines:Array = new Array(); var foundFirstLineOfSection:Boolean = false; for each(var line in lines) { foundFirstLineOfSection = !foundFirstLineOfSection ? line.indexOf("[" + this.section + "]") >= 0 : !line.match(/\[\w+\]/); if(foundFirstLineOfSection) { sectionLines.push(line); } } return sectionLines; } private function parseVars(lines:Array) { var broadcastUpdate = false; for each(var line in lines) { var keyValue = line.split("=", 2).map(Util.trim); if(keyValue.length == 2) { if(this.streamInfo[keyValue[0]] != keyValue[1]) { if(!broadcastUpdate) { this.lastUpdated = new Array(); } broadcastUpdate = true; this.lastUpdated.push(keyValue[0]); this.streamInfo[keyValue[0]] = keyValue[1]; } } } if(broadcastUpdate) { this.dispatchEvent(new Event(INFO_UPDATE)); } } } }