#!/usr/bin/python

"""
Ini punya mandiri
"""

import urllib2
import urllib
import cookielib
import re
import sys
from datetime import datetime, timedelta

#Ganti username dengan username anda
USERNAME = "user123"
#Ganti pin dengan pin anda
PIN = "123123"
#Ganti pake norek anda
NOREK = "1111111111111"
#Hari
DAYS = 7


#Please do not edit below this line or you will be eaten by the dragons
#-----------------------------------------------------------------------

cookie_handler = urllib2.HTTPCookieProcessor()
https_handler = urllib2.HTTPSHandler(debuglevel=0)
redirect_handler= urllib2.HTTPRedirectHandler()
urllib2.install_opener(urllib2.build_opener(redirect_handler,cookie_handler,https_handler))

ACCOUNT_ID = None

def get_urllib( url, postdata=None):
    headers = { 'User-Agent' : 'Mozilla/5.0 (X11; Linux i686 (x86_64); rv:2.0b4pre) Gecko/20100812 Minefield/4.0b4pre' }
    req = urllib2.Request(url, postdata, headers)
    resp = urllib2.urlopen(req)    
    return resp

def do_logout():
    """Do logout
    If we not do this, other instance cannot running
    """
    logout_url = "https://ib.bankmandiri.co.id/retail/Logout.do?action=result"
    resp = get_urllib(logout_url)
    s = resp.read()
    if 'Terima kasih Anda telah menggunakan Layanan INTERNET BANKING MANDIRI.' in s:
        print "Logout Success"
    else:
        print "Logout Failed"

def get_account_id():
    global ACCOUNT_ID,NOREK
    
    trx_url = "https://ib.bankmandiri.co.id/retail/TrxHistoryInq.do?action=form"
    resp = get_urllib(trx_url)
    s = resp.read()
    m = re.compile(r'<option value="([^"]+)">'+NOREK+'.*?</option>', re.I|re.S).search(s)
    if m:
        ACCOUNT_ID = m.group(1).strip()
        print "Account ID = " + ACCOUNT_ID
    else:
        raise ValueError( "Nomer rekening tidak ada atau salah - Silahkan cek via website." )


def do_login():
    """Do login
    """
    url = "https://ib.bankmandiri.co.id/retail/Login.do?action=form&lang=in_ID"
    resp = get_urllib(url)
    result = resp.read()
    m = re.compile( r'<form name="LoginForm" method="post" action="([^"]+)">', re.I|re.S ).search(result)
    if not m:
        raise ValueError( "Login URL not match, could be redesigned web page" )
    
    login_url = m.group(1)
    if not login_url.startswith("https://ib.bankmandiri.co.id"):
        login_url = "https://ib.bankmandiri.co.id" + login_url

    post_data = {
        "action":"result",
        "userID":USERNAME,
        "password":PIN,
        "image.x":74,
        "image.y":7,
    }
    resp = get_urllib(login_url, urllib.urlencode(post_data))
    result = resp.read()
    if '/retail/Welcome.do?action=result' not in result:
        raise ValueError( "Login failed, please check your username and password" )
        
    print "Login Success, retrieving Account ID"
    get_account_id()


def do_fetch_transaction():
    """Fetch transaction as HTML
    """
    
    if ACCOUNT_ID is None:
        get_account_id()

    trx_url = "https://ib.bankmandiri.co.id/retail/TrxHistoryInq.do"
    today = datetime.today()
    delta = timedelta(DAYS)
    last_month = today - delta

    post_data = {
        "action":"result",
        "fromAccountID":ACCOUNT_ID,
        "searchType":"R",
        "fromDay":last_month.day,
        "fromMonth":last_month.month,
        "fromYear":last_month.year,
        "toDay":today.day,
        "toMonth":today.month,
        "toYear":today.year,
        "sortType":"Date",
        "orderBy":"ASC",
    }
    
    resp = get_urllib(trx_url, urllib.urlencode(post_data))
    result = resp.read()
    #f = open("out.txt", 'wb')
    #f.write(result)
    #f.close()
    
    result = re.compile('<script.*?>(.*?)</script>', re.S).sub('', result)
    filename = "mandiri-%s%s%s.html" % (today.year,today.month,today.day)
    f = open(filename, 'wb')
    f.write(result)
    f.close()
    print "saved to: %s" % filename


def do_fetch_csv():
    """Fetch transaction as CSV
    """
    do_fetch_transaction()
    
    post_data = {
        "downloadType":"CSV",
        "action":"download",
    }
    
    trx_url = "https://ib.bankmandiri.co.id/retail/TrxHistoryInq.do"
    resp = get_urllib(trx_url, urllib.urlencode(post_data))
    result = resp.read()
    #f = open("out.txt", 'wb')
    #f.write(result)
    #f.close()
    
    today = datetime.today()
    filename = "mandiri-%s%s%s.csv" % (today.year,today.month,today.day)
    f = open(filename, 'wb')
    f.write(result)
    f.close()
    print "saved to: %s" % filename
    

if __name__ == "__main__":
    try:
        do_login()
        do_fetch_csv()
        do_logout()
    except urllib2.HTTPError, e:
        print "error: %s" % e.code
        do_logout()
    except urllib2.URLError, e:
        print "error: %s" % e.reason
        do_logout()
    except:
        print "error: %s" % str(sys.exc_info()[1])
        try:
            do_logout()
        except:
            print "logout error: %s" % str(sys.exc_info()[1])
    
    

