1 /** 2 * This library ONLY WORKS IN AIR atm 3 * 4 * This is a conversion of the actionscript library from twstreamer <http://github.com/r/twstreamer/> into JavaScript. 5 * No license was listed on the git repo, so I am assuming something public domain or new-BSD-ish. 6 * 7 * @constructor 8 */ 9 var SpazTwitterStream = function(opts) { 10 var that = this; 11 12 this.opts = sch.defaults({ 13 'auth' : null, 14 'userstream_url': "https://userstream.twitter.com/2/user.json", 15 'onData' : null, 16 'onError' : null 17 }, opts); 18 19 this.stream = new air.URLStream; 20 21 this.connect = function() { 22 var amountRead = 0; 23 var streamBuffer = ""; 24 var request = createStreamRequest(that.opts.userstream_url, that.opts.auth); 25 that.stream = new air.URLStream(); 26 that.stream.addEventListener(air.IOErrorEvent.IO_ERROR, errorReceived); 27 that.stream.addEventListener(air.ProgressEvent.PROGRESS, dataReceived); 28 that.stream.load(request); 29 }; 30 31 this.disconnect = function() { 32 that.stream.close(); 33 that.stream = null; 34 }; 35 36 function createStreamRequest(username, pass) { 37 var request = new air.URLRequest(that.opts.userstream_url); 38 var auth_header = that.opts.auth.signRequest(air.URLRequestMethod.POST, that.opts.userstream_url, ''); 39 sch.debug('auth_header:'+auth_header); 40 request.requestHeaders = new Array(new air.URLRequestHeader("Authorization", auth_header)); 41 request.method = air.URLRequestMethod.POST; 42 request.data = ''; 43 return request; 44 } 45 46 function errorReceived(e) { 47 sch.error("errorReceived in stream"); 48 sch.debug(e); 49 if (that.opts.onError) { 50 that.opts.onError.call(this, e); 51 } 52 } 53 54 55 var isReading = false; 56 var amountRead = 0; 57 var streamBuffer = ''; 58 function dataReceived(e) { 59 sch.debug("dataReceived"); 60 sch.debug(e.toString()); 61 62 var toRead = e.bytesLoaded - amountRead; 63 sch.debug("toRead:"+toRead); 64 var buffer = that.stream.readUTFBytes(toRead); 65 sch.debug("buffer:"+buffer); 66 amountRead = e.bytesLoaded; 67 sch.debug("amountRead:"+amountRead); 68 69 var parts = []; 70 if (!isReading) { 71 parts = buffer.split(/\n/); 72 var firstPart = parts[0].replace(/[\s\n]*/, ""); 73 sch.debug("firstPart:"+firstPart); 74 buffer = parts.slice(1).join("\n"); 75 sch.debug("buffer:"+buffer); 76 isReading = true; 77 } 78 79 // pump the JSON pieces through 80 if ((toRead > 0) && (amountRead > 0)) { 81 streamBuffer += buffer; 82 sch.debug("streamBuffer:"+streamBuffer); 83 parts = streamBuffer.split(/\n/); 84 sch.debug("parts:"+parts); 85 var lastElement = parts.pop(); 86 for (var i=0; i < parts.length; i++) { 87 sch.debug('parts['+i+']:'+parts[i]); 88 if (that.opts.onData) { 89 that.opts.onData.call(this, parts[i]); 90 } 91 } 92 streamBuffer = lastElement; 93 sch.debug("streamBuffer:"+streamBuffer); 94 } 95 } 96 }; 97