Skip to content

Commit ead2272

Browse files
committed
2 parents 9442754 + dde4ea8 commit ead2272

File tree

5 files changed

+107
-5
lines changed

5 files changed

+107
-5
lines changed
1.68 KB
Binary file not shown.

src/Dockerfile

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,19 @@ RUN pip install --no-cache-dir -r requirements.txt
1515
# Install pg_dump
1616
RUN apt-get update && apt-get -y install postgresql-client
1717

18+
# Install Chrome and chromedriver
19+
# Install wget
20+
RUN apt-get install -y wget
21+
# Download and Install chrome
22+
RUN wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
23+
RUN apt-get install -y ./google-chrome-stable_current_amd64.deb
24+
# Download and Install chromedriver. The version here depends on what what version of chrome gets installed above !
25+
RUN wget https://chromedriver.storage.googleapis.com/104.0.5112.79/chromedriver_linux64.zip
26+
RUN unzip chromedriver_linux64.zip
27+
RUN mv chromedriver /usr/bin/chromedriver
28+
RUN chown root:root /usr/bin/chromedriver
29+
RUN chmod +x /usr/bin/chromedriver
30+
1831
# define the port number the container should expose
1932
EXPOSE 5000
2033

src/main_data_autosynch.py

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,35 @@ def auto_synch(ath_un, db_name, db_host, superuser_un, superuser_pw, gc_username
145145
finally:
146146
if conn is not None:
147147
conn.close()
148-
#Periodic daily auto_synch(2days)
149-
else:
150-
start_date = datetime.datetime.today() - datetime.timedelta(days=2) #PG: start_day = one day before yesterday
148+
#Periodic daily auto_synch(2 days back from last_synch)
149+
#Retrieve last_synch from db_info, subtract 2 days and use as a start date for the autosynch
150+
else:
151+
sql_select_last_synch ="""
152+
SELECT last_synch FROM db_info WHERE db_name= %s;
153+
"""
154+
try:
155+
params = config(filename="encrypted_settings.ini", section="postgresql", encr_pass=encr_pass)
156+
postgres_db = params.get("database")
157+
postgres_un = params.get("user")
158+
postgres_pw = params.get("password")
159+
postgres_host = params.get("host")
160+
161+
conn_localhost = psycopg2.connect(host=postgres_host, dbname=postgres_db, user=postgres_un, password=postgres_pw)
162+
cur_localhost = conn_localhost.cursor()
163+
cur_localhost.execute(sql_select_last_synch,(db_name,))
164+
conn_localhost.commit()
165+
result = cur_localhost.fetchone()
166+
last_synch_str = result[0]
167+
last_synch_dt = datetime.datetime.strptime(last_synch_str,"%Y-%m-%d %H:%M:%S")
168+
start_date = last_synch_dt - datetime.timedelta(days=2) #PG: start_day = 2 days before last_synch
169+
except (Exception, psycopg2.DatabaseError) as error:
170+
with ErrorStdoutRedirection(ath_un):
171+
print((str(datetime.datetime.now()) + ' [' + sys._getframe().f_code.co_name + ']' + ' Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + ' ' + str(error)))
172+
finally:
173+
if conn_localhost is not None:
174+
conn_localhost.close
175+
176+
#start_date = datetime.datetime.today() - datetime.timedelta(days=2) #PG: start_day = one day before yesterday
151177
#Calculate end_date
152178
end_date = datetime.datetime.today() - datetime.timedelta(days=1) #PG: end_date = yesterday
153179
end_date_today = datetime.datetime.today() #"PG: end_date_today = today

src/mfp_data_download_db_insert.py

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,69 @@ def dwnld_insert_nutrition(mfp_username,mfp_password,ath_un,start_date,end_date,
5858
print("Attempting to login to MFP...")
5959
with ProgressStdoutRedirection(ath_un):
6060
print("Attempting to login to MFP...")
61+
62+
#----------- 2022/08/29 --------
63+
# The below code is to incorporate Selenium to retrieve the login cookies, instantiate the cookiejar and pass to myfitnesspall.Client().
64+
# It is a temporary workaround to address MFP introducing hidden captcha on 25th of Aug.
65+
# For this to work you will need to download the chromedriver that matches the version of yur chrome browser, and place it in /work_dir/temp/.
66+
# https://chromedriver.chromium.org/getting-started
67+
from selenium import webdriver
68+
from selenium.webdriver.chrome.options import Options
69+
from http.cookiejar import Cookie,CookieJar
70+
import time
71+
72+
def to_cookielib_cookie(selenium_cookie):
73+
if 'expiry' in selenium_cookie:
74+
expires=selenium_cookie['expiry']
75+
else:
76+
expires=None
77+
return Cookie(
78+
version=0,
79+
name=selenium_cookie['name'],
80+
value=selenium_cookie['value'],
81+
port='80',
82+
port_specified=False,
83+
domain=selenium_cookie['domain'],
84+
domain_specified=True,
85+
domain_initial_dot=False,
86+
path=selenium_cookie['path'],
87+
path_specified=True,
88+
secure=selenium_cookie['secure'],
89+
expires=expires,
90+
discard=False,
91+
comment=None,
92+
comment_url=None,
93+
rest=None,
94+
rfc2109=False
95+
)
96+
97+
def put_cookies_in_jar(selenium_cookies, cookie_jar):
98+
for cookie in selenium_cookies:
99+
cookie_jar.set_cookie(to_cookielib_cookie(cookie))
100+
101+
cj = CookieJar()
102+
options = Options()
103+
options.add_argument('--no-sandbox')
104+
options.add_argument('--headless')
105+
options.add_argument('--disable-dev-shm-usage')
106+
options.add_argument("user-data-dir={}".format(PID_FILE_DIR+'selenium'))
107+
driver = webdriver.Chrome(PID_FILE_DIR+'chromedriver.exe',options=options)# Modify this line if your chromedrive executable is located at a different path. The dafault location is /work_dir/temp.
108+
driver.get('https://www.myfitnesspal.com/account/login')
109+
email = driver.find_element("id","email")
110+
email.send_keys(mfp_username) #Email id
111+
password = driver.find_element("id","password")
112+
password.send_keys(mfp_password) #Password
113+
time.sleep(3)
114+
login = driver.find_element("id","password")
115+
login.submit() #Logging In
116+
time.sleep(3)
117+
cookies = driver.get_cookies()
118+
put_cookies_in_jar(cookies,cj)
119+
120+
#----------- END Selenium workaround ---------------
121+
61122
try:
62-
client = myfitnesspal.Client(mfp_username,mfp_password)
123+
client = myfitnesspal.Client(cookiejar=cj) # 2022/08/29 Selenium workaround: addedd "cookiejar=cj".
63124
except ValueError as e:
64125
with ErrorStdoutRedirection(ath_un):
65126
print((str(datetime.datetime.now()) + ' [' + sys._getframe().f_code.co_name + ']' + ' Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + '-E1- ' + str(e)))
@@ -71,6 +132,8 @@ def dwnld_insert_nutrition(mfp_username,mfp_password,ath_un,start_date,end_date,
71132
with ProgressStdoutRedirection(ath_un):
72133
print('MFP Login successful! Proceeding...')
73134

135+
driver.quit() # 2022/08/29 Selenium workaround: Close the selenium session
136+
74137
mfp_user_insert(mfp_username,encrypted_pwd,ath_un,db_host,db_name,superuser_un,superuser_pw,encr_pass) #PG: insert MFP user details into database
75138

76139
# read DB connection parameters from ini file

src/requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ numpy
1818
dropbox==11.0.0
1919
Flask
2020
func_timeout==4.3.5
21-
myfitnesspal==1.16.6
21+
myfitnesspal==2.0.0
2222
mechanize==0.4.5
2323
dicttoxml==1.7.4
2424
psutil==5.8.0

0 commit comments

Comments
 (0)