forked from atorman/elfPy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelf.py
More file actions
executable file
·219 lines (185 loc) · 7.38 KB
/
elf.py
File metadata and controls
executable file
·219 lines (185 loc) · 7.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# Connected App information: fill it in by creating a connected app
# https://help.salesforce.com/articleView?id=connected_app_create.htm&language=en_US&type=0
#Imports
import urllib.request
import json
import ssl
import getpass
import os
import sys
import gzip
import time
from io import StringIO
import base64
# login function
def login():
''' Login to salesforce service using OAuth2 '''
# username = ''
# password = ''
# clientId = ''
# clientSecret = ''
# prompt for username, password, consumer key and consumer secret
# while len(username) < 1:
print('Remember, you need data from a Connected App')
username = input('Username: ')
# while len(password) < 1:
password = getpass.getpass('Password and Token:')
# while len(clientId) < 1:
clientId = input('Consumer key: ')
# while len(clientSecret) < 1:
clientSecret = input('Consumer secret: ')
instanceType = input('Instance type (login by default): ')
redirectURI = input('Redirect URI (from your App Connected, "http://localhost:4200/" by default): ')
# check to see if anything was entered and if not, default values
# change default values for username and password to your own
if len(username) < 1:
username = 'your@email.com'
password = 'PasswordToken'
clientId = 'YourConsumerKey'
clientSecret = 'YourClientSecret'
redirectURI = 'http://localhost:4200/'
print('Using default username and credentials: {0}'.format(username))
else:
print('Using user inputed username and credentials: {0}'.format(username))
# Use 'login' by default
if len(instanceType) < 1:
instanceType = 'login'
print('check point')
# create a new salesforce REST API OAuth request
url = 'https://' + instanceType + '.salesforce.com/services/oauth2/token'
dataUnencoded = {
'grant_type': 'password',
'client_id': clientId,
'client_secret': clientSecret,
'redirect_uri': redirectURI,
'username': username,
'password': password
}
data = urllib.parse.urlencode(dataUnencoded).encode("utf-8")
headers = {'X-PrettyPrint' : '1'}
# call salesforce REST API and pass in OAuth credentials
req = urllib.request.Request(url, data, headers = headers)
try:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
res = urllib.request.urlopen(req, context = ctx)
res_dict = json.load(res)
res.close()
except urllib.error.URLError as e:
if(e.reason == 'Bad Request'):
print('Error: {0}, check input data'.format(e.reason))
else:
print('Error: {0}'.format(e.reason))
sys.exit()
# return OAuth access token necessary for additional REST API calls
access_token = res_dict['access_token']
instance_url = res_dict['instance_url']
return access_token, instance_url
# download function
def download_elf():
''' Query salesforce service using REST API '''
# login and retrieve access_token and day
access_token, instance_url = login()
day = input('\nDate range (e.g. Last_n_Days:2, Today, Tomorrow):\n')
# check to see if anything was entered and if not, default values
if len(day) < 1:
day = 'Last_n_Days:2'
print('Using default date range: {0} \n'.format(day))
else:
print('Using user inputed date range: {0} \n'.format(day))
# query Ids from Event Log File
url = instance_url+'/services/data/v41.0/query?q=SELECT+Id+,+EventType+,+Logdate+From+EventLogFile+Where+LogDate+=+'+day
headers = {'Authorization' : 'Bearer ' + access_token, 'X-PrettyPrint' : '1'}
req = urllib.request.Request(url, None, headers = headers)
res = urllib.request.urlopen(req)
res_dict = json.load(res)
# capture record result size to loop over
total_size = res_dict['totalSize']
# provide feedback if no records are returned
if total_size < 1:
print('No records were returned for {0}'.format(day))
sys.exit()
# create a directory for the output
dir = input("Output directory: ")
# check to see if anything
if len(dir) < 1:
dir = 'elf'
print('\ndefault directory name used: {0}'.format(dir))
else:
print('\ndirectory name used: {0}'.format(dir))
# If directory doesn't exist, create one
if not os.path.exists(dir):
os.makedirs(dir)
# close connection
res.close
# check to see if the user wants to download it compressed
# compress = input('\nUse compression (y/n)\n').lower()
# print(compress)
# Disabled compress validation meanwhile...
compress = 'n'
# check to see if anything
if len(compress) < 1:
compress = 'yes'
print('\ndefault compression being used: {0}'.format(compress))
else:
print('\ncompression being used: {0}'.format(compress))
# loop over json elements in result and download each file locally
for i in range(total_size):
# pull attributes out of JSON for file naming
ids = res_dict['records'][i]['Id']
types = res_dict['records'][i]['EventType']
dates = res_dict['records'][i]['LogDate']
# create REST API request
url = instance_url+'/services/data/v41.0/sobjects/EventLogFile/'+ids+'/LogFile'
# provide correct compression header
if (compress == 'y') or (compress == 'yes'):
headers = {'Authorization' : 'Bearer ' + access_token, 'X-PrettyPrint' : '1', 'Accept-encoding' : 'gzip'}
print('Using gzip compression\n')
else:
headers = {'Authorization' : 'Bearer ' + access_token, 'X-PrettyPrint' : '1'}
print('Not using gzip compression\n')
# begin profiling
start = time.time()
# open connection
req = urllib.request.Request(url, None, headers)
res = urllib.request.urlopen(req)
print('********************************')
# provide feedback to user
print('Downloading: ' + dates[:10] + '-' + types + '.csv to ' + os.getcwd() + '/' + dir + '\n')
# print the response to see the content type
# print res.info()
# if the response is gzip-encoded as expected
# compression code from http://bit.ly/pyCompression
if res.info().get('Content-Encoding') == 'gzip':
# buffer results
html = res.read()
decodedHtml = html.decode('iso-8859-1')#.encode('UTF-8')
# decodedHtml = decodedHtml.decode('UTF-8')
print('HTML=>', decodedHtml)
buf = StringIO(decodedHtml)
# gzip decode the response
f = gzip.GzipFile(fileobj=buf)
# print data
data = f.read()
# close buffer
buf.close()
else:
# buffer results
buf = StringIO(res.read().decode('utf-8'))
# get the value from the buffer
data = buf.getvalue()
#print data
buf.close()
# write buffer to CSV with following naming convention yyyy-mm-dd-eventtype.csv
file = open(dir + '/' +dates[:10]+'-'+types+'.csv', 'w')
file.write(data)
# end profiling
end = time.time()
secs = end - start
#msecs = secs * 1000 # millisecs
#print 'elapsed time: %f ms' % msecs
print('Total download time: %f seconds\n' % secs)
file.close
i = i + 1
# close connection
res.close
download_elf()