| 1 | #!/usr/bin/perl |
|---|
| 2 | use strict; |
|---|
| 3 | use warnings; |
|---|
| 4 | |
|---|
| 5 | use DBI; |
|---|
| 6 | use LWP::UserAgent; |
|---|
| 7 | |
|---|
| 8 | my $dbh = DBI->connect( 'DBI:mysql:myopenarchive:localhost:3306', 'user', |
|---|
| 9 | 'pass' ); |
|---|
| 10 | |
|---|
| 11 | $dbh->do("set names utf8"); |
|---|
| 12 | |
|---|
| 13 | $dbh->do( |
|---|
| 14 | "insert into tweet_counter |
|---|
| 15 | select id, 0, null from documents |
|---|
| 16 | left join tweet_counter using(id) |
|---|
| 17 | where count is null" |
|---|
| 18 | ); |
|---|
| 19 | |
|---|
| 20 | my $sth = $dbh->prepare( |
|---|
| 21 | "select * from tweet_counter left join documents using(id) |
|---|
| 22 | where count=(select min(count) |
|---|
| 23 | from tweet_counter) order by count desc, rand()" |
|---|
| 24 | ); |
|---|
| 25 | $sth->execute(); |
|---|
| 26 | my $document_info = {}; |
|---|
| 27 | while ( my $str = $sth->fetchrow_hashref ) { |
|---|
| 28 | next unless $str->{title}; |
|---|
| 29 | $document_info = $str; |
|---|
| 30 | last; |
|---|
| 31 | } |
|---|
| 32 | |
|---|
| 33 | $sth = $dbh->prepare("update tweet_counter set count=count + 1 where id=?"); |
|---|
| 34 | $sth->execute( $document_info->{id} ); |
|---|
| 35 | |
|---|
| 36 | my $title = $document_info->{title}; |
|---|
| 37 | my $url = get_short_url( |
|---|
| 38 | "http://www.myopenarchive.org/documents/view/$document_info->{id}"); |
|---|
| 39 | |
|---|
| 40 | my $format = "[Featured on MyOA]%s %s"; |
|---|
| 41 | my $status = sprintf $format, $title, $url; |
|---|
| 42 | |
|---|
| 43 | my $USER = 'user'; |
|---|
| 44 | my $PASSWORD = 'pass'; |
|---|
| 45 | my $ua = LWP::UserAgent->new( agent => 'Bot-TweetFeed', keep_alive => 1 ); |
|---|
| 46 | $ua->credentials( 'twitter.com:80', 'Twitter API', $USER, $PASSWORD ); |
|---|
| 47 | $ua->post( 'http://twitter.com/statuses/update.xml', { status => $status } ); |
|---|
| 48 | |
|---|
| 49 | sub get_short_url { |
|---|
| 50 | my $url = shift; |
|---|
| 51 | my $ua = LWP::UserAgent->new(); |
|---|
| 52 | my $rs = $ua->get("http://tinyurl.com/api-create.php?url=$url"); |
|---|
| 53 | return $rs->content; |
|---|
| 54 | |
|---|
| 55 | } |
|---|
| 56 | |
|---|
| 57 | exit 0; |
|---|