Created
December 15, 2013 18:04
-
-
Save fuba/7976088 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git lib/AnyEvent/Twitter/Stream.pm lib/AnyEvent/Twitter/Stream.pm | |
index 548aee9..16dfba1 100644 | |
--- lib/AnyEvent/Twitter/Stream.pm | |
+++ lib/AnyEvent/Twitter/Stream.pm | |
@@ -109,6 +109,7 @@ sub new { | |
} | |
my $self = bless {}, $class; | |
+ my $buf = ""; | |
{ | |
Scalar::Util::weaken(my $self = $self); | |
@@ -123,7 +124,9 @@ sub new { | |
# Twitter stream returns "\x0a\x0d\x0a" if there's no matched tweets in ~30s. | |
$set_timeout->(); | |
if ($json !~ /^\s*$/) { | |
- my $tweet = $decode_json ? JSON::decode_json($json) : $json; | |
+ my $tweet = eval { $decode_json ? JSON::decode_json($json) : $json; }; | |
+ die $json if $@; | |
+ | |
if ($on_delete && $tweet->{delete} && $tweet->{delete}->{status}) { | |
$on_delete->($tweet->{delete}->{status}->{id}, $tweet->{delete}->{status}->{user_id}); | |
}elsif($on_friends && $tweet->{friends}) { | |
@@ -140,6 +143,19 @@ sub new { | |
$on_keepalive->(); | |
} | |
}; | |
+ my $buf = ''; | |
+ my $on_json_fragment = sub { | |
+ my ($json_fragment) = @_; | |
+ if ($json_fragment !~ /\n$/) { | |
+ $buf .= $json_fragment; | |
+ } | |
+ else { | |
+ my $json = $buf . $json_fragment; | |
+ $buf = ''; | |
+ $on_json_message->($json); | |
+ } | |
+ }; | |
+ | |
$set_timeout->(); | |
@@ -179,7 +195,7 @@ sub new { | |
$handle->push_read(line => sub { length $_[1] and die 'bad chunk (missing last empty line)'; }); | |
unless ($headers->{'content-encoding'}) { | |
- $on_json_message->($chunk); | |
+ $on_json_fragment->($chunk); | |
} elsif ($headers->{'content-encoding'} =~ 'deflate|gzip') { | |
$input .= $chunk; | |
my ($message); | |
@@ -187,7 +203,7 @@ sub new { | |
$_zstatus = $zlib->inflate(\$input, \$message); | |
return unless $_zstatus == Z_OK || $_zstatus == Z_BUF_ERROR; | |
} while ( $_zstatus == Z_OK && length $input ); | |
- $on_json_message->($message); | |
+ $on_json_fragment->($message); | |
} else { | |
die "Don't know how to decode $headers->{'content-encoding'}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment