-
Notifications
You must be signed in to change notification settings - Fork 1
/
CovSurvey
executable file
·238 lines (189 loc) · 8.75 KB
/
CovSurvey
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/python3
"""
__| __|
( _ \\ \ /\__ \ | | _|\ \ / -_) | |
\___|\___/ \_/ ____/\_,_|_| \_/\___|\_, |
___/ XIX
"""
# this Programme require highly network connexion to work well
import os
import sys
import pip # require pip on your system ` sudo apt install python3-pip`
import json
import subprocess
from time import sleep
import logging as log
try :
import requests
except :
pip.main(["install" , "requests"])
# The whole programme is based in this config file
#+ to set the main attributes
CFG_FILE = "covset.cfg"
# A container for collecting data from API
setup_data =dict()
# parse the configuration file to do different processing to extract the essential data
if os.path.exists(CFG_FILE) and os.path.getsize(CFG_FILE) > 0x000 :
with open ( CFG_FILE , "r" ) as s_setup : # s_setup as static_setup
# initializing setup_data
# that's contain the default config setup
# it automaticly convert to dict type to better use
setup_data =json.loads(s_setup.read())
else :
log.error("file Missing ... ")
sys.exit(3)
# mapping values
current_country = setup_data["local_country"]
api_services = setup_data["services"]["apis"]
attr_data = setup_data["main_attr"]
geoloc = setup_data["services"]["location_service"]
mesgout = lambda mesg : print("|-> {}".format(mesg))
# default method to do query from API url
default_query = lambda url_args="countries" : api_services["main"]+url_args
# generic method to make request
# but sometime it's crash due to a slow network connexion
# or bad connexion or the remote service is overloaded ...
make_request = lambda args : requests.get(args).json()
main_attr_data = attr_data[0:4]
# set allowed arguments
allowed_argument = list(attr_data)
# tracking user location to get metadata
# by making request using ip address
def tracker () -> str :
mesgout("fetching your location ... ")
track_users_loc = make_request(geoloc[0x001])
user_ip , user_city , user_region , loc = (
track_users_loc["ip"] , # user ip address [used in the script]
track_users_loc["city"], # user city location [not yet used in the script ][data available]
track_users_loc["region"], # user region location [not yet used in the script ][data available]
track_users_loc["loc"] # user coord location [not yet used in the script ][data available]
)
# get current location user by using his ip address ...
define_user = ""
try :
# sometime request failed i don't know why ...
# may be my network is slow !!?
define_user = make_request(geoloc[0x00]+user_ip)["data"]
except :
mesgout("retrying ... [ no request on time ]")
sleep(2)
subprocess.call(["python3" , sys.argv[0]])
return define_user["country_name"]
def set_covset_once () -> None :
global current_country
# write the configuration once
# by default the local_country is null to avoid static value
# when user location was it's make a stream to rewrite
# config file ...
if len(current_country) == 0x00 or current_country == "None" :
mesgout("Setting up your location ...")
setup_data["local_country"]=tracker()
current_country = setup_data["local_country"]
with open (CFG_FILE , "w") as save_loc :
json.dump(setup_data ,save_loc)
subprocess.call(["python3" , sys.argv[0]])
def set_new_location ( location :str , *contries_list ) :
# give an opportunity to set new location
if location in contries_list :
setup_data["local_country"] = location
# rewrite the config file
with open ( CFG_FILE , "w" ) as save_new_location :
mesgout("setting new location to {}".format(location))
json.dump(setup_data , save_new_location)
# generic method to get related data about the current country
# passed on parameter ...
def find_country ( country :str , *countries_list:list ) :
if country in countries_list :
country_pos = countries_list.index(country)
return make_request(default_query())[country_pos]
def usage () :
basename = sys.argv[0x00].split("/")
print("{} [ option or country name ] ".format(basename[-1]))
extra_args = [ "World", "list", "help" , "location"]
allowed_argument.extend(extra_args)
print("options list : \033[4m")
for argument in allowed_argument :
if argument == extra_args[-1] :
mesgout("{} <country name>".format(argument))
else : mesgout(argument)
print("\033[0m")
def suggest (user_args , *args_stdin:list ) :
# suggesting user by doing some research by coutry name
# ex : sys.argv[0] chi
# suggesting - > china or chile
incre=0
for args in args_stdin :
if user_args in args_stdin: break
arg_match = args[0:len(user_args)]
if arg_match == user_args.capitalize():
mesgout("did you mean -> \033[4;34m{}\033[0m ".format(args))
# make a nice display
formatted_row = '{:<10} | {:<10} | {:>10} | {:>10} | {:<10}| {:<10}| {:<10} |'
data=None
country = None
def main () :
# collect all list of countries
countries_list = [ c["country"] for c in make_request(default_query()) if c["country"]]
global data , formatted_row , country
# possibility to change your current location
# to another location if you want
if len(sys.argv) == 0x003 :
if sys.argv[1].lower() == "location" :
new_location = (sys.argv[2].lower().capitalize() , sys.argv[2].upper() ) [len(sys.argv[0x02]) <= 3 ]
set_new_location(new_location , *countries_list)
# if no argument was set
# your current location will be used
# to make http request and get the related data ...
if len(sys.argv) == 0x001 :
set_covset_once()
country = current_country # (tracker() , current_country)[ current_country is not None ]
data = find_country( country , *countries_list )
# Otherwise when user specify a country
# an http request w'll be made and fetch the data
# related to the country passed as argument
if len(sys.argv) == 0x002 :
by_country = (sys.argv[0x001].lower().capitalize() ,sys.argv[0x001].upper())[len(sys.argv[0x001]) <= 0x003]
if by_country == "World" :
data = make_request(default_query("all"))
formatted_row = "|".join(formatted_row.split("|")[0:4])
elif by_country in countries_list:
mesgout("fill country collection list ... ")
# catch the index of the current country passed
# + as parameter and get the data in that position
data = find_country( by_country , *countries_list )
elif by_country.lower() in allowed_argument or by_country.lower() == "todaycases":
country = current_country
data = find_country( country , *countries_list )[(by_country.lower(),by_country[:5].lower() +by_country[5:].capitalize())[by_country.lower() == "todaycases"]]
elif by_country.lower() == "list" :
for c in countries_list :
print("\033[4m {} \033[0m".format(c))
elif by_country.lower() == "h" or by_country =="help" : usage()
else :
log.warning("\033[1;33mUnknow argument... \033[0m")
suggest(by_country , *countries_list)
usage()
sys.exit(2)
try :
main()
except TypeError :
pass
except : pass
# mesgout("[ retrying request ]")
# subprocess.call(["python3" , sys.argv[0]])
# display of data according to arguments
e_data = list ()
if data is not None and type(data) is not int and type(data) is not str:
if len(sys.argv) == 2 and sys.argv[0x001].lower().capitalize() == "World" :
print(formatted_row.format(*main_attr_data))
for es_data in main_attr_data :
e_data.append(data[es_data])
print(formatted_row.format(*e_data))
else :
print(formatted_row.format(*attr_data))
for es_data in attr_data:
e_data.append(data[es_data])
print(formatted_row.format(*e_data))
elif data is None :
print("...")
else :
print(data)