#!/usr/bin/env python

import urllib
import string
import smtplib
import rxb 
import re 
import time


from htmllib import *
from cStringIO import StringIO

G_DEBUG = 1
G_FROM = '"The gnut killer" <honey@7thguard.net>'
G_TO = '"A humble 7g reader" <kowalski@kowalski.com>'
G_LASTONE = 0
G_MINUTE = 60
G_TAIMAUT = G_MINUTE * 20

from html2text import HTML2Text

def html2text(s):
    parser = HTML2Text()
    parser.feed(s)
    parser.close()
    return parser.result



def sendmesycz(mesycz):
    server = smtplib.SMTP('localhost')
    server.sendmail(G_FROM,G_TO,html2text(mesycz))
    server.quit()
    if G_DEBUG == 1: print "mail sent"

def getpejcz(urlik):
    a=urllib.urlopen("http://7thguard.net/news.php?id=" + urlik)
    if G_DEBUG == 1: print "getting news no ", urlik
    b=a.read()
    for i in range (len(b)):
	pat = rxb.label.spam(rxb.exactly("<!-- tabelka z treścią -->"))
	pat.search(b)
	d = pat.after
    return d

def get7list():
    a=urllib.urlopen("http://7thguard.net")
    if G_DEBUG == 1: print "index opened"
    b=a.read()
    c=string.split(b,'<div class="head"')
    numberlist = []
    for i in range (len(c)):
	pat = rxb.label.spam(rxb.exactly("id="))
	pat.search(c[i])
	d = pat.after
	pat2 = rxb.label.spam(rxb.some(rxb.digit))
	pat2.search(pat.after)
	numberlist.append(pat2.found)
    return numberlist

def poczontek():
    d = get7list()
    d.reverse()
    for i in d[0:(len(d)-1)]:
	l = getpejcz(i)
        sendmesycz(l)
    G_LASTONE = eval(i)

	

poczontek()

x = 0
while x == 0:
    time.sleep(G_TAIMAUT)
    d = get7list()
    d.reverse()
    print d
    for i in d[0:(len(d)-1)]:
	if eval(i) > G_LASTONE:
	    print "found a new news:", i
	    l = getpejcz(str(i))
	    sendmesycz(l)
	    G_LASTONE = eval(i)