Skip to content

Instantly share code, notes, and snippets.

@Logic-gate
Created November 22, 2015 17:53
Show Gist options
  • Save Logic-gate/22bfc075a6bffe1f90e8 to your computer and use it in GitHub Desktop.
Save Logic-gate/22bfc075a6bffe1f90e8 to your computer and use it in GitHub Desktop.
Habib LabReport CLI: This is a reversed engineered program designed to aid registered patients with their personal lab results. It uses the same service that Dr. ALHABIB (Android APP/WSDL) does with the exception of limitation; it will only display your lab results.
#!/usr/bin/env python
# HabibLabReport.py V 0.1 - Habib LabReport CLI
# Copyright (C) <2014> mad_dev(A'mmer Almadani)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Report any issues with this script to
'''
create a new file called habib.conf
Copy and Paste the following to habib.conf:
[PATIENT]
hospitalidentificationid = Your Hospital ID
patientidentificationid = Your National Identifiation
patientmobilenumber = Your Mobile Number
[SYS]
logintokenid = Leave Empty
tokenid = Leave Empty
stamp = Leave Empty
'''
import urllib2
import json
import npyscreen
import datetime
import ConfigParser
import os
import re
from prettytable import PrettyTable
class HabibWebService():
def ServicesUrl(self):
url = 'http://87.101.227.137/Services/'
return url
def ActionUrl(self, action):
if action == 'Authentication':
url = "Authentication.svc/REST/"
elif action == 'GetPatient':
url = "Patients.svc/REST/"
return url
def HabibServices(self, service):
if service == 'CheckPatientAuthentication':
REST = 'CheckPatientAuthentication'
elif service == 'CheckActivationCode':
REST = 'CheckActivationCode'
elif service == 'GetPatientLabOrders':
REST = 'GetPatientLabOrders'
elif service == 'GetPatientLabResults':
REST = 'GetPatientLabResults'
else:
pass
return REST
def dump(self, option, token, InvoiceNo, OrderNo):
if option == 'CheckPatientAuthenticationDump':
JsonData = json.dumps({"PatientMobileNumber":ReadConfig()[2],
"PatientIdentificationID":ReadConfig()[1],
"LanguageID":1,
"IPAdress":"10.10.10.10",
"VersionID":1.1,
"Channel":3 })
elif option == 'CheckActivationCodeDump':
code = raw_input('SMS CODE: ')
JsonData = json.dumps({"activationCode": str(code),
"PatientIdentificationID":ReadConfig()[1],
"PatientMobileNumber":ReadConfig()[2],
"LanguageID":1,
"LogInTokenID":ReadConfig()[3],
"stamp":ReadConfig()[5],
"IPAdress":"10.10.10.10",
"VersionID":1.1,
"Channel":3,
"TokenID":"",
"SessionID":""})
elif option == 'GetPatientLabOrdersDump':
JsonData = json.dumps({"PatientID":ReadConfig()[0],
"LanguageID":1,
"stamp":ReadConfig()[5],
"IPAdress":"10.10.10.10",
"VersionID":1.1,
"Channel":3,
"PatientOutSA":0,
"PatientTypeID":1,
"TokenID":ReadConfig()[4],
"SessionID":""})
elif option == 'GetPatientLabResultsDump':
JsonData = json.dumps({"ProjectID":"16",
"SetupID":"102000",
"OrderNo":str(OrderNo),
"InvoiceNo":str(InvoiceNo),
"PatientID":ReadConfig()[0],
"LanguageID":1,
"stamp":ReadConfig()[5],
"IPAdress":"10.10.10.10",
"VersionID":1.1,
"Channel":3,
"PatientOutSA":0,
"PatientTypeID":1,
"TokenID":ReadConfig()[4],
"SessionID":""})
return JsonData
def URL(self, action, service):
url = self.ServicesUrl()
svc = self.ActionUrl(action)
REST= self.HabibServices(service)
urlToPost = url + svc + REST
return str(urlToPost)
def HabibWeb(self, url, dump_option, token, InvoiceNo, OrderNo):
req = urllib2.Request(url)
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, self.dump(dump_option, token, InvoiceNo, OrderNo))
for i in response:
#return i
op = open('JSON', 'w+')
op.write(i)
op.close
return i
def GetTokens(self):
LoginToken = json.loads(self.HabibWeb(self.URL('Authentication', 'CheckPatientAuthentication'), 'CheckPatientAuthenticationDump', None, None, None))
WriteConfig('LogInTokenID', LoginToken['LogInTokenID'])
Data = json.loads(self.HabibWeb(self.URL('Authentication', 'CheckActivationCode'), 'CheckActivationCodeDump', ReadConfig()[3], None, None))
WriteConfig('TokenID', Data['AuthenticationTokenID'])
table_patient = PrettyTable(["Patient ID",
"National Identification Number",
"First Name",
"Middle Name",
"Last Name",
"Date of Birth"])
table_contact = PrettyTable(["Phone (Home)",
"Phone (Office)",
"Phone (Mobile)",
"Phone (Fax)",
"Email"])
table_emergency = PrettyTable(["Blood Group",
"Emergency Contact Name",
"Phone (Emergency Contact)"])
table_patient.padding_width = 1
table_contact.padding_width = 1
table_emergency.padding_width = 1
table_patient.add_row([Data['List'][0]['PatientID'],
Data['List'][0]['PatientIdentificationNo'],
Data['List'][0]['FirstName'],
Data['List'][0]['MiddleName'],
Data['List'][0]['LastName'],
ConvertTimeStamp(Data['List'][0]['DateofBirth'])])
table_contact.add_row([DeleteWhiteSpace(Data['List'][0]['PhoneResi']),
DeleteWhiteSpace(Data['List'][0]['PhoneOffice']),
DeleteWhiteSpace(Data['List'][0]['MobileNumber']),
DeleteWhiteSpace(Data['List'][0]['FaxNumber']),
Data['List'][0]['EmailAddress']])
table_emergency.add_row([ Data['List'][0]['BloodGroup'],
Data['List'][0]['EmergencyContactName'],
Data['List'][0]['EmergencyContactNo']])
print table_patient
print '\n'
print table_contact
print '\n'
print table_emergency
return Data
#OPERATIONS
def GetLabReport(self):
report = json.loads(self.HabibWeb(self.URL('GetPatient', 'GetPatientLabOrders'), 'GetPatientLabOrdersDump', ReadConfig()[4], None, None))
table = PrettyTable(["Doctor's Name", "Invoice Number", "Order Number", "Order Date"])
table.padding_width = 1
for i in report['ListPLO']:
table.add_row([i['DoctorName'], i['InvoiceNo'], i['OrderNo'], ConvertTimeStamp(i['OrderDate'])])
print table
return report
def GetLabResult(self):
print '\n'
InvoiceNo = raw_input('Invoice Number: ')
OrderNo = raw_input('Order Number: ')
report = json.loads(self.HabibWeb(self.URL('GetPatient', 'GetPatientLabResults'), 'GetPatientLabResultsDump',ReadConfig()[4], InvoiceNo, OrderNo))
table = PrettyTable(["Test Name", "Result", "Range"])
table.align["Test Name"] = "l"
table.padding_width = 1
for i in report['ListPLR']:
table.add_row([i['Description'], i['ResultValue'], i['ReferanceRange']])
print table
if __name__ == '__main__':
p = str(os.path.dirname(os.path.abspath(__file__)))
stamp = datetime.datetime.now().strftime("'%Y-%m-%dT%H:%M:%SZ'") #Note to Habib Developers. ZONE should be set to a fixed offset
def ConvertTimeStamp(time):
nm = re.split(r'[/()+a-zA-Z]', time)
return datetime.datetime.fromtimestamp(int(nm[6])/1000).strftime('%Y-%m-%d')
def DeleteWhiteSpace(string):
regex = re.sub(r"\s+", "", string)
return regex
def ReadConfig():
config = ConfigParser.ConfigParser()
config.read(str(p)+'/habib.conf')
PatientID = config.get("PATIENT", 'HospitalIdentificationID') #Lowercase in habib.conf
PatientIdentificationID = config.get("PATIENT", "PatientIdentificationID")
PatientMobileNumber = config.get("PATIENT", "PatientMobileNumber")
LogInTokenID = config.get("SYS", "LogInTokenID")
TokenID = config.get("SYS", "TokenID")
Stamp = config.get("SYS", "Stamp")
return PatientID, PatientIdentificationID, PatientMobileNumber, LogInTokenID, TokenID, Stamp
def WriteConfig(string, var):
config = ConfigParser.RawConfigParser()
config.read(str(p)+'/habib.conf')
config.set("SYS", string, var)
with open(str(p)+'/habib.conf', 'w') as configfile:
config.write(configfile)
def ReadJson(dump, obj, doOK):
f = open(dump, 'r')
JSON = f.read()
if obj in JSON:
doOK
else:
pass
WriteConfig('stamp', stamp)
Habib = HabibWebService()
print '''\033[95mHabib LabReport CLI:
This is a reversed engineered program designed to aid registered patients with their personal lab results.
It uses the same service that Dr. ALHABIB (Android APP) does with the exception of limitation; it will only display your lab results.'''
print '\n\033[97mPlease Wait...'
try:
print '\n\033[92mTrying to log in using the TOKEN from the last session\033[0m'
Habib.GetLabReport()
ReadJson('JSON', '"IsAuthenticated":true', Habib.GetLabResult())
except:
print '\n\033[92mGetting new TOKEN...\033[0m'
Habib.GetTokens()
Habib.GetLabReport()
Habib.GetLabResult()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment