Difference between revisions of "Twitter recording status"

From MythTV Official Wiki
Jump to: navigation, search
(PHP example using OAuth authentication: Update script)
 
(12 intermediate revisions by 5 users not shown)
Line 1: Line 1:
It's fairly simple to set up a user job to send out recording status updates via TwitterPaste the following code into a file (for example, twitter.pl)
+
== Introduction ==
 +
 
 +
It's fairly simple to set up a user job to send out recording status updates via Twitter:
 +
 
 +
# Paste one of the following code examples into a file (for example /usr/local/bin/mythtv-twitter).
 +
# Make the file executable: <code>chmod +x /usr/local/bin/mythtv-twitter</code>
 +
# If using OAuth authentication, you will need to register an application for twitter at http://dev.twitter.com/ and grab the application and user OAuth keys. See http://dev.twitter.com/pages/oauth_single_token for an explanation of the OAuth keys you need to provide.
 +
# Add any required authentication credentials in the file.
 +
# Create a user job in the MythTV set (see below).
 +
 
 +
'''NOTE:''' Twitter has turned off Basic Authentication : http://countdowntooauth.com/, so any of the examples ''not'' using OAuth authentication no longer work.
 +
 
 +
== Configuring MythTV ==
 +
 
 +
Stop your backend and run mythtv-setup.  In step 1, General, you must adjust two options.  First, you must allow the new user job to be run on this backend.  For example, if your new User Job is the first one, tick the "Allow User Job #1 on this backend."  On the User Job setup page, give your job a name, such as "Post-record Twitter."  Then you can use something like the following command line:
  
 
<pre>
 
<pre>
 +
/usr/local/bin/mythtv-twitter "Finished recording %TITLE% (%SUBTITLE%) on %CHANID% at %ENDTIMEISO%.  Backend was %HOSTNAME%."
 +
</pre>
 +
 +
You can insert information as you wish, using any of the variables from [[User Jobs]].  Complete the setup and you will now have a user job which you can set to run at the end of individual or all recording rules. you can now edit your recording rules and set the user job to run at the end of each recording to update your twitter status.
 +
 +
'''NOTE:''' Some people regard Twitter as a handy news resource and search on tags based on things they like to keep up on - say MythTV for example. Inserting #MythTV in your userjob twitter script makes all your recording tweets appear in the search feed meaning that people who genuinely want to follow real news items have to add the username your script uses to their filter.  As of 11th November 2009 the filter string is quite short but as time goes by it'll get longer.  '''PLEASE''' choose a different tag, or no tag at all. The majority of people wanting to follow #MythTV items are probably not interested in what you record or watch ;-) Infact it's probably completely unnecessary to even mention MythTV in automated tweets.  Anybody using the script knows what program they use to record their TV, after all.
 +
 +
== Example scripts ==
 +
 +
=== Perl example using OAuth authentication ===
 +
 +
There's also a cpan prerequisite : $ sudo perl -MCPAN -force -e "install Net::Twitter::OAuth" (http://search.cpan.org/~miyagawa/Net-Twitter-OAuth-0.02/lib/Net/Twitter/OAuth.pm)
 +
{{Perl|mythtv-twitter-perl-oauth|<pre>
 
#!/usr/bin/perl
 
#!/usr/bin/perl
use LWP::UserAgent;
+
 
 +
use Net::Twitter::OAuth;
 +
 
 +
my $client = Net::Twitter::OAuth->new(
 +
    consumer_key    => '',
 +
    consumer_secret => '',
 +
);
 +
 
 +
$client->access_token('');
 +
$client->access_token_secret('');
 +
 
 
my $output = shift @ARGV;
 
my $output = shift @ARGV;
 
my $browser = LWP::UserAgent->new;
 
my $url = 'http://twitter.com/statuses/update.json';
 
$browser->credentials('twitter.com:80', 'Twitter API', 'username', 'password');
 
$response = $browser->get("http://twitter.com/account/verify_credentials.json");
 
my $response = $browser->post($url, {status => $output});
 
</pre>
 
  
Edit the username and password to match your twitter user and password. Save the file, make it executable, and put it somewhere in your path.  In this example we'll put the file in /usr/bin.
+
$client->update({ status => $output });
 +
</pre>}}
 +
 
 +
 
 +
=== PHP example using OAuth authentication ===
 +
 
 +
This script uses Horde's Twitter and OAuth libraries. To install the dependencies with PEAR run:
  
 
<pre>
 
<pre>
chmod +x twitter.pl
+
pear channel-discover pear.horde.org
cp twitter.pl /usr/bin/
+
pear install horde/horde_service_twitter horde/horde_autoloader horde/horde_serialize
 
</pre>
 
</pre>
 +
{{PHP|mythtv-twitter-php-oauth|<pre>
 +
#!/usr/bin/env php
 +
<?php
  
Stop your backend and run mythtv-setup.  In step 1, General, you must adjust two options.  First, you must allow the new user job to be run on this backend. For example, if your new User Job is the first one, tick the "Allow User Job #1 on this backend."  On the User Job setup page, give your job a name, such as "Post-record Twitter."  Then you can use something like the following command line:
+
/* Keys - these are obtained when registering for the service */
 +
$keys = array(
 +
    'consumer_key'        => '',
 +
    'consumer_secret'    => '',
 +
    'access_token'        => '',
 +
    'access_token_secret' => ''
 +
);
 +
 
 +
/* Enable autoloading. */
 +
require 'Horde/Autoloader/Default.php';
 +
 
 +
/* Create the Twitter client */
 +
$twitter = Horde_Service_Twitter::create(array('oauth' => $keys));
  
<pre>
+
/* Send tweet */
/usr/bin/twitter.pl "Finished recording %TITLE% (%SUBTITLE%) on %CHANID% at %ENDTIMEISO%.  Backend was %HOSTNAME%."
+
try {
</pre>
+
    $twitter->statuses->update($argv[1]);
 +
} catch (Horde_Service_Twitter_Exception $e) {
 +
    $error = Horde_Serialize::unserialize($e->getMessage(), Horde_Serialize::JSON);
 +
    if (is_object($error)) {
 +
        echo "$error->error\n";
 +
    } else {
 +
        echo $e->getMessage() . "\n";
 +
    }
 +
    exit(1);
 +
}
  
You can insert information as you wish, using any of the variables from [[User Jobs]].  Complete the setup and you will now have a user job which you can set to run at the end of individual or all recording rules. you can now edit your recording rules and set the user job to run at the end of each recording to update your twitter status.
+
exit(0);
 +
</pre>}}
  
'''NOTE:''' Some people regard Twitter as a handy news resource and search on tags based on things they like to keep up on - say MythTV for example. Inserting #MythTV in your userjob twitter script makes all your recording tweets appear in the search feed meaning that people who genuinely want to follow real news items have to add the username your script uses to their filter.  As of 11th November 2009 the filter string is quite short but as time goes by it'll get longer.  '''PLEASE''' choose a different tag, or no tag at all. The majority of people wanting to follow #MythTV items are probably not interested in what you record or watch ;-)
+
=== Perl example using Basic authentication (defunct) ===
  
A more complete Twitter user job script is possible which tweets the actual channel nameSave the script as twitter.pl, mark it as executable as before & set the user job to run as <pre> twitter.pl starttime=%STARTTIME% chanid=%CHANID%</pre>
+
{{Perl|mythtv-twitter-perl-basic|<pre>
 +
#!/usr/bin/perl
 +
use LWP::UserAgent;
 +
my $output = shift;
 +
   
 +
my $browser = LWP::UserAgent->new;
 +
my $url = 'http://twitter.com/statuses/update.json';
 +
$browser->credentials('twitter.com:80', 'Twitter API', 'username', 'password');
 +
$response = $browser->get("http://twitter.com/account/verify_credentials.json");
 +
my $response = $browser->post($url, {status => $output});
 +
</pre>}}
  
  
<pre>
+
=== Advanced Perl example using Basic authentication (defunct) ===
 +
 
 +
A more complete Twitter user job script is possible which tweets the actual channel name. Set the user job to run as <pre>/usr/local/bin/mythtv-twitter starttime=%STARTTIME% chanid=%CHANID%</pre>
 +
{{Perl|mythtv-twitter-perl-basic-advanced|<pre>
 
#!/usr/bin/perl
 
#!/usr/bin/perl
 
use LWP::UserAgent;
 
use LWP::UserAgent;
Line 40: Line 114:
 
use MythTV;
 
use MythTV;
  
$connect = undef;
+
my $connect;
$debug = 0;
+
my $debug = 0;
$title="";
+
my $title="";
$subtitle="";
+
my $subtitle="";
$newsubtitle="";
+
my $newsubtitle="";
$starttime="";
+
my $starttime="";
$chanid="";
+
my $chanid="";
  
 
##################################
 
##################################
Line 54: Line 128:
 
##################################
 
##################################
  
$usage = "\nHow to use twitter.pl \n\ twitter.pl starttime=%STARTTIME% chanid=%CHANID% debug\n"
+
my $usage = "\nHow to use twitter.pl \n\ twitter.pl starttime=%STARTTIME% chanid=%CHANID% debug\n"
        ."\n%CHANID% = channel ID associated with the recording\n"
+
    ."\n%CHANID% = channel ID associated with the recording\n"
        ."%STARTTIME% = recording start time in either 'yyyy-mm-dd hh:mm:ss' or 'yyyymmddhhmmss' format\n"
+
    ."%STARTTIME% = recording start time in either 'yyyy-mm-dd hh:mm:ss' or 'yyyymmddhhmmss' format\n"
        ."debug = enable debugging information - outputs which commands would be run etc\n";
+
    ."debug = enable debugging information - outputs which commands would be run etc\n";
  
 
# get this script's ARGS
 
# get this script's ARGS
 
#
 
#
  
$num = $#ARGV + 1;
+
my $num = @ARGV;
  
 
# if user hasn't passed enough arguments, die and print the usage info
 
# if user hasn't passed enough arguments, die and print the usage info
  
 
if ($num le "1") {
 
if ($num le "1") {
        die "$usage";
+
    die "$usage";
 
}
 
}
  
Line 75: Line 149:
  
 
foreach (@ARGV){
 
foreach (@ARGV){
     if ($_ =~ m/debug/) {
+
     if (/debug/) {
 
         $debug = 1;
 
         $debug = 1;
 
     }
 
     }
     elsif ($_ =~ m/starttime/) {
+
     elsif (/starttime/) {
         $starttime = (split(/\=/,$_))[1];
+
         $starttime = (split(/=/))[1];
 
     }
 
     }
     elsif ($_ =~ m/chanid/) {
+
     elsif (/chanid/) {
         $chanid = (split(/\=/,$_))[1];
+
         $chanid = (split(/=/))[1];
 
     }
 
     }
 
}
 
}
  
 
# connect to backend
 
# connect to backend
my $myth = new MythTV();
+
my $myth = MythTV->new;
 
# connect to database
 
# connect to database
$connect = $myth->{'dbh'};
+
my $connect = $myth->{dbh};
  
$query = "SELECT name FROM channel WHERE chanid=$chanid";
+
my $query = "SELECT name FROM channel WHERE chanid=$chanid";
$query_handle = $connect->prepare($query);
+
my $query_handle = $connect->prepare($query);
$query_handle->execute() || die "Unable to query channel table";
+
$query_handle->execute  or die "Unable to query channel table";
  
 
my ($channame) = $query_handle->fetchrow_array;
 
my ($channame) = $query_handle->fetchrow_array;
Line 99: Line 173:
 
$query = "SELECT title, subtitle, endtime FROM recorded WHERE chanid=$chanid and starttime='$starttime'";
 
$query = "SELECT title, subtitle, endtime FROM recorded WHERE chanid=$chanid and starttime='$starttime'";
 
$query_handle = $connect->prepare($query);
 
$query_handle = $connect->prepare($query);
$query_handle->execute() || die "Unable to query settings table";
+
$query_handle->execute  or die "Unable to query settings table";
  
 
$query_handle->bind_columns(undef, \$title, \$subtitle, \$endtime);
 
$query_handle->bind_columns(undef, \$title, \$subtitle, \$endtime);
$query_handle->fetch();
+
$query_handle->fetch;
  
 
if ($subtitle)
 
if ($subtitle)
 
{
 
{
$newsubtitle = " - ".$subtitle;
+
    $newsubtitle = " - ".$subtitle;
 
}
 
}
  
$output = "Finished recording $title $newsubtitle from $channame at $endtime";
+
my $output = "Finished recording $title $newsubtitle from $channame at $endtime";
    print "Chanid $chanid \n";
+
print "Chanid $chanid \n";
    print "Starttime $starttime \n";
+
print "Starttime $starttime \n";
    print "$output \n";
+
print "$output \n";
  
if ($debug)
+
unless ($debug)
 
{
 
{
 +
    my $browser = LWP::UserAgent->new;
 +
    my $url = 'http://twitter.com/statuses/update.json';
 +
    $browser->credentials('twitter.com:80', 'Twitter API', 'username', 'password');
 +
    $response = $browser->get("http://twitter.com/account/verify_credentials.json");
 +
    my $response = $browser->post($url, {status => $output});
 
}
 
}
else
+
</pre>}}
{
+
 
my $browser = LWP::UserAgent->new;
 
my $url = 'http://twitter.com/statuses/update.json';
 
$browser->credentials('twitter.com:80', 'Twitter API', 'username', 'password');
 
$response = $browser->get("http://twitter.com/account/verify_credentials.json");
 
my $response = $browser->post($url, {status => $output});
 
}
 
</pre>
 
  
= Python Implementation =
+
=== Python example using Basic authentication (defunct) ===
  
 
This is a script to tweet recordings currently taking place on the local backend. There are other scripts I have seen but all tweeted when watching LiveTV; this script only tweets actual recordings.
 
This is a script to tweet recordings currently taking place on the local backend. There are other scripts I have seen but all tweeted when watching LiveTV; this script only tweets actual recordings.
Line 133: Line 205:
 
I personally use it to tweet the recordings which in turn get pushed to my iPhone so I know a recording has started.
 
I personally use it to tweet the recordings which in turn get pushed to my iPhone so I know a recording has started.
  
The variables are given in the script.
+
'''NOTE:''' Twitter has limits to how many API calls can be made in an hour (150 I think). If this limit is reached the script will write to the log file and pause for 30 minutes.
Change them, chmod +x it and run.
 
  
PLEASE NOTE:
+
'''REQUIRES:''' python, python-twitter (Debian/Ubuntu: sudo apt-get install python python-twitter)
Twitter has limits to how many api calls can be made in an hour (150 I think). If this limit is reached the script will write to the log file and pause for 30 mins.
+
{{Python|mythtv-twitter-python-basic|
 
 
REQUIRES:
 
python, python-twitter
 
(Ubuntu: sudo apt-get install python python-twitter)
 
 
 
{{Python|mythtv_twitter_monitor.py|
 
 
<pre>
 
<pre>
 
#!/usr/bin/python
 
#!/usr/bin/python
Line 165: Line 230:
 
import os
 
import os
 
import logging
 
import logging
from MythTV import MythDB, MythBE
+
from MythTV import MythBE
  
 
###########################################################################
 
###########################################################################
Line 174: Line 239:
 
twlogin = 'user@domain.com'
 
twlogin = 'user@domain.com'
 
twpasswd = 'password'
 
twpasswd = 'password'
 
#Mythtv SQL database login
 
dbuser = 'mythtv'
 
dbpass = 'password'
 
  
 
#Location of the log file (Must be writeable by the user running this script)
 
#Location of the log file (Must be writeable by the user running this script)
Line 226: Line 287:
 
     # Connect to Twitter and MythTV backend.
 
     # Connect to Twitter and MythTV backend.
 
     twitter_h = twitter.Api(username=twlogin, password=twpasswd)
 
     twitter_h = twitter.Api(username=twlogin, password=twpasswd)
     myth_be = MythBE(db=MythDB(args=(('DBHostName','localhost'),
+
     myth_be = MythBE()
        ('DBName','mythconverg'), ('DBUserName','mythtv'),
 
        ('DBPassword',dbpass))))
 
  
 
     # Make a list of Encoder objects for encoders 1 and 2.
 
     # Make a list of Encoder objects for encoders 1 and 2.
 
     encoders = [Encoder(myth_be, x) for x in xrange(1, 3)]
 
     encoders = [Encoder(myth_be, x) for x in xrange(1, 3)]
  
     while 1:
+
     while True:
 
         # Obtain MythTV status info.
 
         # Obtain MythTV status info.
 
         conn = httplib.HTTPConnection('localhost:6544')
 
         conn = httplib.HTTPConnection('localhost:6544')
Line 261: Line 320:
  
 
[[Category:HOWTO]]
 
[[Category:HOWTO]]
[[Category:Scripts]]
+
[[Category:Perl Scripts]]
 +
[[Category:Python Scripts]]

Latest revision as of 14:25, 5 August 2013

Introduction

It's fairly simple to set up a user job to send out recording status updates via Twitter:

  1. Paste one of the following code examples into a file (for example /usr/local/bin/mythtv-twitter).
  2. Make the file executable: chmod +x /usr/local/bin/mythtv-twitter
  3. If using OAuth authentication, you will need to register an application for twitter at http://dev.twitter.com/ and grab the application and user OAuth keys. See http://dev.twitter.com/pages/oauth_single_token for an explanation of the OAuth keys you need to provide.
  4. Add any required authentication credentials in the file.
  5. Create a user job in the MythTV set (see below).

NOTE: Twitter has turned off Basic Authentication : http://countdowntooauth.com/, so any of the examples not using OAuth authentication no longer work.

Configuring MythTV

Stop your backend and run mythtv-setup. In step 1, General, you must adjust two options. First, you must allow the new user job to be run on this backend. For example, if your new User Job is the first one, tick the "Allow User Job #1 on this backend." On the User Job setup page, give your job a name, such as "Post-record Twitter." Then you can use something like the following command line:

/usr/local/bin/mythtv-twitter "Finished recording %TITLE% (%SUBTITLE%) on %CHANID% at %ENDTIMEISO%.  Backend was %HOSTNAME%."

You can insert information as you wish, using any of the variables from User Jobs. Complete the setup and you will now have a user job which you can set to run at the end of individual or all recording rules. you can now edit your recording rules and set the user job to run at the end of each recording to update your twitter status.

NOTE: Some people regard Twitter as a handy news resource and search on tags based on things they like to keep up on - say MythTV for example. Inserting #MythTV in your userjob twitter script makes all your recording tweets appear in the search feed meaning that people who genuinely want to follow real news items have to add the username your script uses to their filter. As of 11th November 2009 the filter string is quite short but as time goes by it'll get longer. PLEASE choose a different tag, or no tag at all. The majority of people wanting to follow #MythTV items are probably not interested in what you record or watch ;-) Infact it's probably completely unnecessary to even mention MythTV in automated tweets. Anybody using the script knows what program they use to record their TV, after all.

Example scripts

Perl example using OAuth authentication

There's also a cpan prerequisite : $ sudo perl -MCPAN -force -e "install Net::Twitter::OAuth" (http://search.cpan.org/~miyagawa/Net-Twitter-OAuth-0.02/lib/Net/Twitter/OAuth.pm)

Application-x-perl.png mythtv-twitter-perl-oauth
#!/usr/bin/perl

use Net::Twitter::OAuth;

my $client = Net::Twitter::OAuth->new(
    consumer_key    => '',
    consumer_secret => '',
);

$client->access_token('');
$client->access_token_secret('');

my $output = shift @ARGV;

$client->update({ status => $output });


PHP example using OAuth authentication

This script uses Horde's Twitter and OAuth libraries. To install the dependencies with PEAR run:

pear channel-discover pear.horde.org
pear install horde/horde_service_twitter horde/horde_autoloader horde/horde_serialize
Php.png mythtv-twitter-php-oauth
#!/usr/bin/env php
<?php

/* Keys - these are obtained when registering for the service */
$keys = array(
    'consumer_key'        => '',
    'consumer_secret'     => '',
    'access_token'        => '',
    'access_token_secret' => ''
);

/* Enable autoloading. */
require 'Horde/Autoloader/Default.php';

/* Create the Twitter client */
$twitter = Horde_Service_Twitter::create(array('oauth' => $keys));

/* Send tweet */
try {
    $twitter->statuses->update($argv[1]);
} catch (Horde_Service_Twitter_Exception $e) {
    $error = Horde_Serialize::unserialize($e->getMessage(), Horde_Serialize::JSON);
    if (is_object($error)) {
        echo "$error->error\n";
    } else {
        echo $e->getMessage() . "\n";
    }
    exit(1);
}

exit(0);

Perl example using Basic authentication (defunct)

Application-x-perl.png mythtv-twitter-perl-basic
#!/usr/bin/perl
use LWP::UserAgent;
my $output = shift;
 
my $browser = LWP::UserAgent->new;
my $url = 'http://twitter.com/statuses/update.json';
$browser->credentials('twitter.com:80', 'Twitter API', 'username', 'password');
$response = $browser->get("http://twitter.com/account/verify_credentials.json");
my $response = $browser->post($url, {status => $output});


Advanced Perl example using Basic authentication (defunct)

A more complete Twitter user job script is possible which tweets the actual channel name. Set the user job to run as
/usr/local/bin/mythtv-twitter starttime=%STARTTIME% chanid=%CHANID%
Application-x-perl.png mythtv-twitter-perl-basic-advanced
#!/usr/bin/perl
use LWP::UserAgent;
use DBI;
use DBD::mysql;
use MythTV;

my $connect;
my $debug = 0;
my $title="";
my $subtitle="";
my $newsubtitle="";
my $starttime="";
my $chanid="";

##################################
#                                #
#    Main code starts here !!    #
#                                #
##################################

my $usage = "\nHow to use twitter.pl \n\ twitter.pl starttime=%STARTTIME% chanid=%CHANID% debug\n"
    ."\n%CHANID% = channel ID associated with the recording\n"
    ."%STARTTIME% = recording start time in either 'yyyy-mm-dd hh:mm:ss' or 'yyyymmddhhmmss' format\n"
    ."debug = enable debugging information - outputs which commands would be run etc\n";

# get this script's ARGS
#

my $num = @ARGV;

# if user hasn't passed enough arguments, die and print the usage info

if ($num le "1") {
    die "$usage";
}

#
# Get all the arguments
#

foreach (@ARGV){
    if (/debug/) {
        $debug = 1;
    }
    elsif (/starttime/) {
        $starttime = (split(/=/))[1];
    }
    elsif (/chanid/) {
        $chanid = (split(/=/))[1];
    }
}

# connect to backend
my $myth = MythTV->new;
# connect to database
my $connect = $myth->{dbh};

my $query = "SELECT name FROM channel WHERE chanid=$chanid";
my $query_handle = $connect->prepare($query);
$query_handle->execute  or die "Unable to query channel table";

my ($channame) = $query_handle->fetchrow_array;

$query = "SELECT title, subtitle, endtime FROM recorded WHERE chanid=$chanid and starttime='$starttime'";
$query_handle = $connect->prepare($query);
$query_handle->execute  or die "Unable to query settings table";

$query_handle->bind_columns(undef, \$title, \$subtitle, \$endtime);
$query_handle->fetch;

if ($subtitle)
{
    $newsubtitle = " - ".$subtitle;
}

my $output = "Finished recording $title $newsubtitle from $channame at $endtime";
print "Chanid $chanid \n";
print "Starttime $starttime \n";
print "$output \n";

unless ($debug)
{
    my $browser = LWP::UserAgent->new;
    my $url = 'http://twitter.com/statuses/update.json';
    $browser->credentials('twitter.com:80', 'Twitter API', 'username', 'password');
    $response = $browser->get("http://twitter.com/account/verify_credentials.json");
    my $response = $browser->post($url, {status => $output});
}


Python example using Basic authentication (defunct)

This is a script to tweet recordings currently taking place on the local backend. There are other scripts I have seen but all tweeted when watching LiveTV; this script only tweets actual recordings.

I personally use it to tweet the recordings which in turn get pushed to my iPhone so I know a recording has started.

NOTE: Twitter has limits to how many API calls can be made in an hour (150 I think). If this limit is reached the script will write to the log file and pause for 30 minutes.

REQUIRES: python, python-twitter (Debian/Ubuntu: sudo apt-get install python python-twitter)

PythonIcon.png mythtv-twitter-python-basic

#!/usr/bin/python

###########################################################################
#
# This script will monitor mythtv for recordings and will tweet them.
# It detects recordings only. When watching liveTV it is not tweeted.
# Run on the mythtv backend.
#
# Christopher Kemp - chris.kemp05@gmail.com
# A lot of help from StephenF via http://ubuntuforums.org
#
# Written 2010
#
###########################################################################

import httplib
import twitter
import time
import os
import logging
from MythTV import MythBE

###########################################################################
############### Variables ################
###########################################################################

#Twitter Settings
twlogin = 'user@domain.com'
twpasswd = 'password'

#Location of the log file (Must be writeable by the user running this script)
log_file = '/path/to/logfile'

###########################################################################
############# End Variables ##############
###########################################################################

#Enable the log
logging.basicConfig(filename=log_file,level=logging.DEBUG)

#Get the hostname
behostname = os.uname()[1]

class Encoder(object):
    """Class to analyse MythTV encoder activity."""

    def is_recording(self, mythdata):
        return self.match in mythdata

    def current_recording(self, mythdata):
        """Returns whatever the encoder is currently recording."""

        if self.is_recording(mythdata):
            return str(self.back_end.getCurrentRecording(self.id))[10:-37]
        else:
            return None

    def new_recording(self, mythdata):
        """Returns None for all but new recordings."""

        rec = self.current_recording(mythdata)
        if rec == self.old_rec:
            return None
        else:
            self.old_rec = rec
            return rec

    def __init__(self, back_end, id):
        self.back_end = back_end
        self.id = id
        self.match = 'Encoder %d is local on %s and is recording' % (id,behostname)
        self.old_rec = None


def main():
    # Connect to Twitter and MythTV backend.
    twitter_h = twitter.Api(username=twlogin, password=twpasswd)
    myth_be = MythBE()

    # Make a list of Encoder objects for encoders 1 and 2.
    encoders = [Encoder(myth_be, x) for x in xrange(1, 3)]

    while True:
        # Obtain MythTV status info.
        conn = httplib.HTTPConnection('localhost:6544')
        conn.request('GET', '/')
        mythdata = conn.getresponse().read()

        # Check each encoder in turn.
        for enc in encoders:
            show = enc.new_recording(mythdata)
            if show is not None:
                #See if twitter can be reached
                try:
                    #If twitter can be reached then tweet show
                    twitter_h.PostUpdate('Recording: %s' % show)
                    time.sleep(120)
                except:
                    #What to do if twitter throws an error. Usually exceeding the api call limit.
                    #Limits are reset after an hour so sleep for half an hour
                    logging.warn('Couldnt log in to twitter. Has probably reached the api limit call. The script will sleep for 30 mins now and then carry on as normal.')
                    time.sleep(1800)


if __name__ == '__main__':
    main()