forked from asib/polar-flow-export
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolar-export.py
More file actions
69 lines (58 loc) · 2.23 KB
/
polar-export.py
File metadata and controls
69 lines (58 loc) · 2.23 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
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import re
import time
import sys
import os
AUTH_URL = "https://auth.polar.com"
FLOW_URL = "https://flow.polar.com"
def login(driver, username, password):
driver.get("%s/login" % AUTH_URL)
driver.find_element_by_id("username").send_keys(username)
driver.find_element_by_id("password").send_keys(password)
driver.find_element(By.CSS_SELECTOR, '[data-testid="login-button"]').click()
def get_exercise_ids(driver, year, month):
driver.get("%s/diary/%s/month/%s" % (FLOW_URL, year, month))
time.sleep(2)
ids = map(
# The subscript removes the prefix
lambda e: e.get_attribute("href")[len("https://flow.polar.com/training/analysis2/"):],
driver.find_elements_by_xpath("//div[@class='event event-month exercise']/a")
)
return ids
def export_exercise(driver, exercise_id, output_dir):
def _load_cookies(session, cookies):
for cookie in cookies:
session.cookies.set(cookie['name'], cookie['value'])
s = requests.Session()
_load_cookies(s, driver.get_cookies())
def _get_filename(r):
regex = r"filename=\"([\w._-]+)\""
return re.search(regex, r.headers['Content-Disposition']).group(1)
r = s.get("%s/api/export/training/tcx/%s" % (FLOW_URL, exercise_id))
tcx_data = r.text
filename = _get_filename(r)
outfile = open(os.path.join(output_dir, filename), 'w')
outfile.write(tcx_data)
outfile.close()
print("Wrote file %s" % filename)
def run(driver, username, password, month, year, output_dir):
login(driver, username, password)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
time.sleep(5)
exercise_ids = get_exercise_ids(driver, year, month)
for ex_id in exercise_ids:
export_exercise(driver, ex_id, output_dir)
if __name__ == "__main__":
try:
(username, password, month, year, output_dir) = sys.argv[1:]
except ValueError:
sys.stderr.write(("Usage: %s <username> <password> <month> <year> <output_dir>\n") % sys.argv[0])
sys.exit(1)
driver = webdriver.Chrome()
try:
run(driver, username, password, month, year, output_dir)
finally:
driver.quit()