#!/usr/bin/env python
from urllib import urlencode
from urllib2 import urlopen
from md5 import md5
from datetime import datetime
import sys

password="Fritz!Box password"
if len(sys.argv) > 1:
    password = sys.argv[1]

def create_response(challenge):
    m = md5(challenge.encode('iso8859-1').encode('utf-16le'))
    return m.hexdigest()

class Call:
    def __init__(self, data):
        self.type_str = ['Unknown', 'Incoming', 'Missed']
        type, date, self.name, self.number, self.extension, self.out_clid, self.duration = map(str.strip, data.split(';'))
        self.type = int(type)
        self.date = datetime.strptime(date,'%d.%m.%y %H:%M')

    def get_name(self):
        return self.name

    def get_date(self):
        return self.date

    def to_string(self):
        return str(self.date) + ' : ' + self.type_str[self.type] + ' call from ' + self.name

# Get a challenge from the login page
data = urlencode({"getpage" : "../html/de/menus/menu2.html", 
    "errorpage" : "../html/index.html" ,
    "var:lang" : "de",
    "var:pagename" : "home",
    })
f = urlopen("http://fritz.box/cgi-bin/webcm", data)
challenge_page = f.readlines()
f.close()
# Create a response
response = None
for line in challenge_page:
    if "var challenge =" in line:
        challenge = line.split('"',3)[1].strip()
        response = challenge + '-' + create_response(challenge + '-' + password)

data = urlencode({"getpage" : "../html/de/menus/menu2.html", 
    "errorpage" : "../html/index.html" ,
    "var:lang" : "de",
    "var:pagename" : "home",
    "login:command/response" : response,
    })
# Get a session ID
sid = None
f = urlopen("http://fritz.box/cgi-bin/webcm", data)
for l in f.readlines():
    if "<input type=\"hidden\" name=\"sid\" value=\"" in l:
        sid=l.split('"')[5]
        break
# Check if we have a valid session id
if sid == '0000000000000000':
    print 'No session id found, check your password.'
    sys.exit(1)
f.close()
# Use the session ID to fetch the calllog, you could also do other stuff with this I guess
f = urlopen("http://fritz.box/cgi-bin/webcm?getpage=../html/de/FRITZ!Box_Anrufliste.csv&sid=" + sid)
lines = f.readlines()
f.close()
for call in map(str.strip,lines[3:]):
    if call:
        print Call(call).to_string()

