#!/usr/bin/python
# ^^^^^^^ PATH TO PYTHON.  Not tested on 3.x.
import pwd, time, os, sys, smtplib
from xml.dom.minidom import parseString 
from email.mime.text import MIMEText

global debug, dpath

# VISONIC ALARM RECEIVER

######################

DRYRUNTEST=False

#Configuration:
debug = 0	# 1 - Enable debug raw data log  0 - Don't log raw data
semail = 1	# 1 - Enable e-mail 	0 - log to e-mail file
elist=['luca.malgeri@cern.ch']	# Default e-mail addresses to be added to visonic xml user list
efrom = 'malgeri.home@gmail.com'	# From address
subject_prefix = "Event detected from alarm system:"	# Subject for e-mail
eserver = "smtp.gmail.com"	# Outgoing mail server on port 25 (does not support auth or ssl)
eport = 587
epasswd = "Tremiti1"

# it allows monospace fonts (i.e. nice formatting)

body_header="""
<html>
<body>
<pre style="font: monospace">
"""

body_footer="""
</pre>
</body>
</html>
"""

# Security:
secmode = 0	# 0 - No security   1 - Match Account  2 - Match Serial   3 - Match Both
valid_accounts = ['000000',"001234"] # List of valid accounts 'account #','account #', etc
valid_serials = ['111111','222222']   # List of valid serial numbers, same format as above
##################################################################################################



def email(efrom, subject, eserver, elist,body):
	global debug

	for addy in elist:
		if addy != "":
			# Create a text/plain message
			msg = MIMEText(body,'html')
			msg['Subject'] = subject
			msg['From'] = efrom
			msg['To'] = addy
	
			s = smtplib.SMTP(eserver,eport)
			s.ehlo()
			s.starttls()
			s.login(efrom,epasswd)
			s.sendmail(efrom, addy, msg.as_string())
			s.close()
 			# s.quit()


if DRYRUNTEST:
        ip="192.168.1.110"
        data="""<?xml version='1.0'?>
<notify>
<pmax_account>001234</pmax_account>
<index>16988</index>
<serial>052eeb</serial>
<time>1459461082</time>
<priority>2</priority>
<event id='85' type='Disarmed'/>
<profile id='3' type='Open / Close'/>
<device id='3' type='User'/>
<location id='1' type='admin'/>
<zone id='1'/>
<partition>1</partition>
<forward_automation>true</forward_automation>
<userlist>
        <user name='admin' email='ownermailbox@hotmail.com' phone='555 666 777' is_sms='0' is_mms='0' is_email='1'/>
        <user name='carmen' email='wifemailbox@gmail.com' phone='555 777 888' is_sms='0' is_mms='0' is_email='0'/>
        <user name='juan' email='neigbourgmailbox@yahoo.com' phone='555 555 555' is_sms='0' is_mms='0' is_email='1'/>
      </userlist>
</notify>
"""        
else:        
        ip = sys.argv[1]  # get remote IP
	data = sys.argv[2]
        

data = data.replace('"',"'")

# proper xml handling
#print data
dom=parseString(data)

eventtags=['pmax_account','index','serial','time','priority']
tagname=[]
for tag in eventtags:
        node=dom.getElementsByTagName(tag)
        if len(node)>0:
                tagname.append(node[0].firstChild.data)
        else:
                tagname.append('None')

pmax_account=tagname[0]
index       =tagname[1]
serial      =tagname[2]
ptime       =tagname[3]
priority    =tagname[4]

infos=['event','profile','device','location','zone']
eventinfo=[]
eventattr=[]

for info in infos:
        node=dom.getElementsByTagName(info)
        if len(node)>0:
                eventinfo.append(node[0].getAttribute('id'))
                eventattr.append(node[0].getAttribute('type'))
        else:
                eventinfo.append('None')
                eventattr.append('None')
                

event_id    =eventinfo[0]
event_type  =eventattr[0]
profile_id  =eventinfo[1]
profile_type=eventattr[1]
device_id   =eventinfo[2]
device_type =eventattr[2]
location_id   =eventinfo[3]
location_type =eventattr[3]
zone_id   =eventinfo[4]
zone_type =eventattr[4]

users={}
# now get the users
node=dom.getElementsByTagName("userlist")
if len(node)>0:
        usernodes=node[0].getElementsByTagName("user")
        for usernode in usernodes:
                if usernode.getAttribute('is_email') == "1":
                        users[usernode.getAttribute('name')]=usernode.getAttribute('email')


#print pmax_account
#print index
#print serial
#print ptime
#print priority
#print event_id
#print event_type
#print profile_id
#print profile_type
#print device_id
#print device_type
#print location_id
#print location_type
#print zone_id
#print zone_type

#for user in users.keys():
#        print user," ",users[user]


#See if we are using server time or sent timestamp and make it into a strtime
timestamp = time.asctime(time.localtime(float(ptime)))

for user in users.keys():
        elist.append(str(users[user]))

#print elist
#print "<br> username="+pwd.getpwuid(os.getuid()).pw_name 


if secmode == 1:
        # if not valid pmaxaccount
        if pmax_account not in valid_accounts:
                print str(ip) + " " + str(account) + " " + str(serial) + " Access Denied!\n"
                sys.exit(0)
if secmode == 2:
        if serial not in valid_serials:
                print str(ip) + " " + str(account) + " " + str(serial) + " Access Denied!\n"
                sys.exit(0)
if secmode == 3:
        if (serial not in valid_serials) or (pmax_account not in valid_accounts):
                print str(ip) + " " + str(account) + " " + str(serial) + " Access Denied!\n"
                sys.exit(0)

# Where we would send the e-mail

subject=subject_prefix+" "+event_type+" "+profile_type+" "+zone_id+" "+timestamp
#body= "Detected event type: "+event_type    +"  (id="+event_id    +")\n"
#body+="            Profile: "+profile_type  +"  (id="+profile_id  +")\n"
#body+="             Device: "+device_type   +"  (id="+device_id   +")\n"
#body+="           Location: "+location_type +"  (id="+location_id +")\n"
#body+="               Zone: "+zone_id +"\n"
#body+="               Time: "+timestamp


body=body_header+"\n"
body+="%20s: %12s (id=%3s)\n" % ("Detected event type",event_type,event_id)
body+="%20s: %12s (id=%3s)\n" % ("Profile",profile_type,profile_id)
body+="%20s: %12s (id=%3s)\n" % ("Device",device_type,device_id)
body+="%20s: %12s (id=%3s)\n" % ("Location",location_type,location_id)
body+="%20s: %12s \n" % ("Zone",zone_id)
body+="%20s: %25s \n" % ("Time",timestamp)
body+=body_footer

if semail == 1:
#        print "Sending email"
        email(efrom, subject, eserver,elist, body)
#        print "---"
#        print body
#        print "---"
        #        print "Email sent"		
else:
        print "Not sending e-mail"
        print "Email parameters:"
        print "efrom:"+efrom
        print "subject:"+subject
        print "eserver:"+eserver
        print "elist:",elist
        print "body:"
        print body

# print "status =0&ka_time =480&allow =0&id =119254&"
