Skip to content

Commit 200813d

Browse files
committed
使用black完成代码format
1 parent 4da3f6d commit 200813d

File tree

4 files changed

+84
-65
lines changed

4 files changed

+84
-65
lines changed

run_page/codoon_sync.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -169,12 +169,7 @@ def tcx_output(fit_array, run_data):
169169
activity_id.text = fit_start_time # Codoon use start_time as ID
170170
activity.append(activity_id)
171171
# Creator
172-
activity_creator = ET.Element(
173-
"Creator",
174-
{
175-
"xsi:type": "Device_t"
176-
}
177-
)
172+
activity_creator = ET.Element("Creator", {"xsi:type": "Device_t"})
178173
activity.append(activity_creator)
179174
# Name
180175
activity_creator_name = ET.Element("Name")
@@ -230,12 +225,7 @@ def tcx_output(fit_array, run_data):
230225
altitude_meters.text = bytes.decode(i["elevation"])
231226
tp.append(altitude_meters)
232227
# Author
233-
author = ET.Element(
234-
"Author",
235-
{
236-
"xsi:type": "Application_t"
237-
}
238-
)
228+
author = ET.Element("Author", {"xsi:type": "Application_t"})
239229
training_center_database.append(author)
240230
author_name = ET.Element("Name")
241231
author_name.text = "Connect Api"

run_page/generator/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,9 +159,13 @@ def get_old_tracks_ids(self):
159159

160160
def get_old_tracks_dates(self):
161161
try:
162-
activities = self.session.query(Activity).order_by(Activity.start_date_local.desc()).all()
162+
activities = (
163+
self.session.query(Activity)
164+
.order_by(Activity.start_date_local.desc())
165+
.all()
166+
)
163167
return [str(a.start_date_local) for a in activities]
164168
except Exception as e:
165169
# pass the error
166170
print(f"something wrong with {str(e)}")
167-
return []
171+
return []

run_page/oppo_sync.py

Lines changed: 70 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,23 @@
1313
import requests
1414
from tzlocal import get_localzone
1515

16-
from config import GPX_FOLDER, JSON_FILE, SQL_FILE, run_map, start_point, TCX_FOLDER, UTC_TIMEZONE
16+
from config import (
17+
GPX_FOLDER,
18+
JSON_FILE,
19+
SQL_FILE,
20+
run_map,
21+
start_point,
22+
TCX_FOLDER,
23+
UTC_TIMEZONE,
24+
)
1725
from generator import Generator
1826
from utils import adjust_time
1927

2028
TOKEN_REFRESH_URL = "https://sport.health.heytapmobi.com/open/v1/oauth/token"
2129
OPPO_HEADERS = {
2230
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
2331
"Content-Type": "application/json",
24-
"Accept": "application/json"
32+
"Accept": "application/json",
2533
}
2634

2735
# Query brief version of sports records
@@ -102,13 +110,13 @@ def get_access_token(session, client_id, client_secret, refresh_token):
102110
headers = {
103111
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
104112
"Content-Type": "application/json",
105-
"Accept": "application/json"
113+
"Accept": "application/json",
106114
}
107115
data = {
108116
"clientId": client_id,
109117
"clientSecret": client_secret,
110118
"refreshToken": refresh_token,
111-
"grantType": "refreshToken"
119+
"grantType": "refreshToken",
112120
}
113121
r = session.post(TOKEN_REFRESH_URL, headers=headers, json=data)
114122
if r.ok:
@@ -129,29 +137,33 @@ def get_to_download_runs_ranges(session, sync_months, headers, start_timestamp):
129137
current_time = current_time + timedelta(days=-30)
130138
temp_start = int(current_time.timestamp() * 1000)
131139
sync_months = sync_months - 1
132-
result.extend(parse_brief_sport_data(session, headers, temp_start, temp_end))
140+
result.extend(
141+
parse_brief_sport_data(session, headers, temp_start, temp_end)
142+
)
133143
else:
134144
while start_datatime < current_time:
135145
temp_start = int(start_datatime.timestamp() * 1000)
136146
start_datatime = start_datatime + timedelta(days=30)
137147
temp_end = int(start_datatime.timestamp() * 1000)
138-
result.extend(parse_brief_sport_data(session, headers, temp_start, temp_end))
148+
result.extend(
149+
parse_brief_sport_data(session, headers, temp_start, temp_end)
150+
)
139151
return result
140152

141153

142154
def parse_brief_sport_data(session, headers, temp_start, temp_end):
143155
result = []
144156
r = session.get(
145-
BRIEF_SPORT_DATA_API.format(
146-
end_time=temp_end,
147-
start_time=temp_start
148-
),
149-
headers=headers
157+
BRIEF_SPORT_DATA_API.format(end_time=temp_end, start_time=temp_start),
158+
headers=headers,
150159
)
151160
if r.ok:
152161
sport_logs = r.json()["body"]
153162
for i in sport_logs:
154-
if i["sportMode"] in AVAILABLE_INDOOR_SPORT_MODE or i["sportMode"] in AVAILABLE_OUTDOOR_SPORT_MODE:
163+
if (
164+
i["sportMode"] in AVAILABLE_INDOOR_SPORT_MODE
165+
or i["sportMode"] in AVAILABLE_OUTDOOR_SPORT_MODE
166+
):
155167
result.append((i["startTime"], i["endTime"]))
156168
print(f"sync record: start_time: " + str(i["startTime"]))
157169
time.sleep(1) # spider rule
@@ -160,11 +172,7 @@ def parse_brief_sport_data(session, headers, temp_start, temp_end):
160172

161173
def get_single_run_data(session, headers, start, end):
162174
r = session.get(
163-
DETAILED_SPORT_DATA_API.format(
164-
end_time=end,
165-
start_time=start
166-
),
167-
headers=headers
175+
DETAILED_SPORT_DATA_API.format(end_time=end, start_time=start), headers=headers
168176
)
169177
if r.ok:
170178
return r.json()
@@ -207,7 +215,9 @@ def parse_raw_data_to_name_tuple(sport_data, with_gpx, with_tcx):
207215
else:
208216
print(f"ID {oppo_id} no gps data")
209217

210-
gps_data = [(item["latitude"], item["longitude"]) for item in other_data["gpsPoint"]]
218+
gps_data = [
219+
(item["latitude"], item["longitude"]) for item in other_data["gpsPoint"]
220+
]
211221
polyline_str = polyline.encode(gps_data) if gps_data else ""
212222
start_latlng = start_point(*gps_data[0]) if gps_data else None
213223
start_date = datetime.utcfromtimestamp(start_time / 1000)
@@ -257,10 +267,13 @@ def get_all_oppo_tracks(
257267
s = requests.Session()
258268
s, headers = get_access_token(s, client_id, client_secret, refresh_token)
259269

260-
last_timestamp = 0 if (last_track_date == 0) \
270+
last_timestamp = (
271+
0
272+
if (last_track_date == 0)
261273
else int(
262-
datetime.timestamp(
263-
datetime.strptime(last_track_date, "%Y-%m-%d %H:%M:%S")) * 1000
274+
datetime.timestamp(datetime.strptime(last_track_date, "%Y-%m-%d %H:%M:%S"))
275+
* 1000
276+
)
264277
)
265278

266279
runs = get_to_download_runs_ranges(s, sync_months, headers, last_timestamp + 1000)
@@ -270,14 +283,17 @@ def get_all_oppo_tracks(
270283
print(f"parsing oppo id {str(start)}-{str(end)}")
271284
try:
272285
run_data = get_single_run_data(s, headers, start, end)
273-
track = parse_raw_data_to_name_tuple(run_data, with_download_gpx, with_download_tcx)
286+
track = parse_raw_data_to_name_tuple(
287+
run_data, with_download_gpx, with_download_tcx
288+
)
274289
tracks.append(track)
275290
except Exception as e:
276291
print(f"Something wrong paring keep id {str(start)}-{str(end)}" + str(e))
277292
return tracks
278293

279294

280-
def switch(v): yield lambda *c: v in c
295+
def switch(v):
296+
yield lambda *c: v in c
281297

282298

283299
def map_oppo_fit_type_to_gpx_type(oppo_type):
@@ -344,7 +360,9 @@ def parse_points_to_gpx(sport_data, points_dict_list):
344360
cad = p.get("cad")
345361
if hr is not None or cad is not None:
346362
hr_str = f"""<gpxtpx:hr>{hr}</gpxtpx:hr>""" if hr is not None else ""
347-
cad_str = f"""<gpxtpx:cad>{p["cad"]}</gpxtpx:cad>""" if cad is not None else ""
363+
cad_str = (
364+
f"""<gpxtpx:cad>{p["cad"]}</gpxtpx:cad>""" if cad is not None else ""
365+
)
348366
gpx_extension = ET.fromstring(
349367
f"""<gpxtpx:TrackPointExtension xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1">
350368
{hr_str}
@@ -433,7 +451,9 @@ def parse_points_to_tcx(sport_data, points_dict_list):
433451
# local time
434452
start_time = sport_data["startTime"]
435453
start_date = datetime.utcfromtimestamp(start_time / 1000)
436-
fit_start_time = datetime.strftime(adjust_time(start_date, UTC_TIMEZONE), "%Y-%m-%dT%H:%M:%SZ")
454+
fit_start_time = datetime.strftime(
455+
adjust_time(start_date, UTC_TIMEZONE), "%Y-%m-%dT%H:%M:%SZ"
456+
)
437457

438458
# Root node
439459
training_center_database = ET.Element(
@@ -463,12 +483,7 @@ def parse_points_to_tcx(sport_data, points_dict_list):
463483
activity_id.text = fit_start_time # Codoon use start_time as ID
464484
activity.append(activity_id)
465485
# Creator
466-
activity_creator = ET.Element(
467-
"Creator",
468-
{
469-
"xsi:type": "Device_t"
470-
}
471-
)
486+
activity_creator = ET.Element("Creator", {"xsi:type": "Device_t"})
472487
activity.append(activity_creator)
473488
# Name
474489
activity_creator_name = ET.Element("Name")
@@ -494,24 +509,34 @@ def parse_points_to_tcx(sport_data, points_dict_list):
494509
break
495510

496511
if idx + 1 != len(points_dict_list):
497-
if item["distance"] < target_distance <= points_dict_list[idx + 1]["distance"]:
512+
if (
513+
item["distance"]
514+
< target_distance
515+
<= points_dict_list[idx + 1]["distance"]
516+
):
498517
lap_split_indexes.append(idx)
499518

500519
if len(lap_split_indexes) == 1:
501520
points_dict_list_chunks = [points_dict_list]
502521
else:
503522
for idx, item in enumerate(lap_split_indexes):
504523
if idx + 1 == len(lap_split_indexes):
505-
points_dict_list_chunks.append(points_dict_list[item: len(points_dict_list) - 1])
524+
points_dict_list_chunks.append(
525+
points_dict_list[item : len(points_dict_list) - 1]
526+
)
506527
else:
507-
points_dict_list_chunks.append(points_dict_list[item: lap_split_indexes[idx + 1]])
528+
points_dict_list_chunks.append(
529+
points_dict_list[item : lap_split_indexes[idx + 1]]
530+
)
508531

509532
current_distance = 0
510533
current_time = start_date
511534

512535
for item in points_dict_list_chunks:
513536
# Lap
514-
lap_start_time = datetime.strftime(adjust_time(item[0]["time"], UTC_TIMEZONE), "%Y-%m-%dT%H:%M:%SZ")
537+
lap_start_time = datetime.strftime(
538+
adjust_time(item[0]["time"], UTC_TIMEZONE), "%Y-%m-%dT%H:%M:%SZ"
539+
)
515540
activity_lap = ET.Element("Lap", {"StartTime": lap_start_time})
516541
activity.append(activity_lap)
517542

@@ -556,7 +581,9 @@ def parse_points_to_tcx(sport_data, points_dict_list):
556581
tp = ET.Element("Trackpoint")
557582
track.append(tp)
558583
# Time
559-
time_stamp = datetime.strftime(adjust_time(p["time"], UTC_TIMEZONE), "%Y-%m-%dT%H:%M:%SZ")
584+
time_stamp = datetime.strftime(
585+
adjust_time(p["time"], UTC_TIMEZONE), "%Y-%m-%dT%H:%M:%SZ"
586+
)
560587
time_label = ET.Element("Time")
561588
time_label.text = time_stamp
562589

@@ -595,7 +622,9 @@ def parse_points_to_tcx(sport_data, points_dict_list):
595622
longi.text = str(p["longitude"])
596623
position.append(longi)
597624
# Extensions
598-
if p.get("speed") is not None or (p.get("cad") is not None and sports_type == "Running"):
625+
if p.get("speed") is not None or (
626+
p.get("cad") is not None and sports_type == "Running"
627+
):
599628
extensions = ET.Element("Extensions")
600629
tp.append(extensions)
601630
tpx = ET.Element("ns3:TPX")
@@ -611,12 +640,7 @@ def parse_points_to_tcx(sport_data, points_dict_list):
611640
cad.text = str(round(p["cad"] / 2))
612641
tpx.append(cad)
613642
# Author
614-
author = ET.Element(
615-
"Author",
616-
{
617-
"xsi:type": "Application_t"
618-
}
619-
)
643+
author = ET.Element("Author", {"xsi:type": "Application_t"})
620644
training_center_database.append(author)
621645
author_name = ET.Element("Name")
622646
author_name.text = "Connect Api"
@@ -659,7 +683,7 @@ def run_oppo_sync(
659683
sync_months,
660684
old_tracks_dates[0] if old_tracks_dates else 0,
661685
with_download_gpx,
662-
with_download_tcx
686+
with_download_tcx,
663687
)
664688
generator.sync_from_app(new_tracks)
665689

@@ -690,7 +714,7 @@ def run_oppo_sync(
690714
type=int,
691715
default=6,
692716
dest="sync_months",
693-
help="oppo has limited the data retrieve, so the default months we can sync is 6."
717+
help="oppo has limited the data retrieve, so the default months we can sync is 6.",
694718
)
695719
options = parser.parse_args()
696720
run_oppo_sync(
@@ -699,5 +723,5 @@ def run_oppo_sync(
699723
options.refresh_token,
700724
options.sync_months,
701725
options.with_gpx,
702-
options.with_tcx
726+
options.with_tcx,
703727
)

run_page/tcx_to_garmin_sync.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,18 @@ def get_to_generate_files(last_time):
1616
file_names = os.listdir(TCX_FOLDER)
1717
tcx = TCXReader()
1818
tcx_files = [
19-
(tcx.read(os.path.join(TCX_FOLDER, i), only_gps=False), os.path.join(TCX_FOLDER, i))
19+
(
20+
tcx.read(os.path.join(TCX_FOLDER, i), only_gps=False),
21+
os.path.join(TCX_FOLDER, i),
22+
)
2023
for i in file_names
2124
if i.endswith(".tcx")
2225
]
2326
tcx_files_dict = {
2427
int(i[0].trackpoints[0].time.timestamp()): i[1]
2528
for i in tcx_files
2629
if len(i[0].trackpoints) > 0
27-
and int(i[0].trackpoints[0].time.timestamp()) > last_time
30+
and int(i[0].trackpoints[0].time.timestamp()) > last_time
2831
}
2932

3033
dict(sorted(tcx_files_dict.items()))
@@ -74,7 +77,5 @@ async def upload_tcx_files_to_garmin(options):
7477
help="if garmin account is cn",
7578
)
7679
loop = asyncio.get_event_loop()
77-
future = asyncio.ensure_future(
78-
upload_tcx_files_to_garmin(parser.parse_args())
79-
)
80+
future = asyncio.ensure_future(upload_tcx_files_to_garmin(parser.parse_args()))
8081
loop.run_until_complete(future)

0 commit comments

Comments
 (0)