本文整理汇总了Python中tapiriik.services.interchange.UploadedActivity.ServiceData方法的典型用法代码示例。如果您正苦于以下问题:Python UploadedActivity.ServiceData方法的具体用法?Python UploadedActivity.ServiceData怎么用?Python UploadedActivity.ServiceData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tapiriik.services.interchange.UploadedActivity
的用法示例。
在下文中一共展示了UploadedActivity.ServiceData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
activities = []
exclusions = []
for act in self._getActivities(serviceRecord, exhaustive=exhaustive):
activity = UploadedActivity()
activity.StartTime = dateutil.parser.parse(act['startDateTimeLocal'])
activity.EndTime = activity.StartTime + timedelta(seconds=act['duration'])
_type = self._activityMappings.get(act['activityType'])
if not _type:
exclusions.append(APIExcludeActivity("Unsupported activity type %s" % act['activityType'],
activity_id=act["activityId"],
user_exception=UserException(UserExceptionType.Other)))
activity.ServiceData = {"ActivityID": act['activityId']}
activity.Type = _type
activity.Notes = act['notes']
activity.GPS = bool(act.get('startLatitude'))
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Kilometers, value=act['distance'])
activity.Stats.Energy = ActivityStatistic(ActivityStatisticUnit.Kilocalories, value=act['calories'])
if 'heartRateMin' in act:
activity.Stats.HR = ActivityStatistic(ActivityStatisticUnit.BeatsPerMinute, min=act['heartRateMin'],
max=act['heartRateMax'], avg=act['heartRateAverage'])
activity.Stats.MovingTime = ActivityStatistic(ActivityStatisticUnit.Seconds, value=act['duration'])
if 'temperature' in act:
activity.Stats.Temperature = ActivityStatistic(ActivityStatisticUnit.DegreesCelcius,
avg=act['temperature'])
activity.CalculateUID()
logger.debug("\tActivity s/t %s", activity.StartTime)
activities.append(activity)
return activities, exclusions
示例2: _create_activity
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def _create_activity(self, data):
activity = UploadedActivity()
activity.Name = data.get("name")
activity.StartTime = pytz.utc.localize(datetime.strptime(data.get("start_at"), "%Y-%m-%dT%H:%M:%SZ"))
activity.EndTime = activity.StartTime + timedelta(0, float(data.get("duration")))
sport_id = data.get("sport_id")
activity.Type = self._reverseActivityMappings.get(int(sport_id), ActivityType.Other) if sport_id else ActivityType.Other
distance = data.get("distance")
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Kilometers, value=float(distance) if distance else None)
activity.Stats.MovingTime = ActivityStatistic(ActivityStatisticUnit.Seconds, value=float(data.get("total_time_in_seconds")))
avg_speed = data.get("average_speed")
max_speed = data.get("max_speed")
activity.Stats.Speed = ActivityStatistic(ActivityStatisticUnit.KilometersPerHour, avg=float(avg_speed) if avg_speed else None, max=float(max_speed) if max_speed else None)
avg_hr = data.get("average_heart_rate")
max_hr = data.get("maximum_heart_rate")
activity.Stats.HR.update(ActivityStatistic(ActivityStatisticUnit.BeatsPerMinute, avg=float(avg_hr) if avg_hr else None, max=float(max_hr) if max_hr else None))
calories = data.get("calories")
activity.Stats.Energy = ActivityStatistic(ActivityStatisticUnit.Kilocalories, value=int(calories) if calories else None)
activity.ServiceData = {"ActivityID": data.get("id")}
logger.debug("\tActivity s/t {}: {}".format(activity.StartTime, activity.Type))
activity.CalculateUID()
return activity
示例3: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, svcRec, exhaustive=False):
dbcl = self._getClient(svcRec)
if not svcRec.Authorization["Full"]:
syncRoot = "/"
else:
syncRoot = svcRec.Config["SyncRoot"]
cache = cachedb.dropbox_cache.find_one({"ExternalID": svcRec.ExternalID})
if cache is None:
cache = {"ExternalID": svcRec.ExternalID, "Structure": [], "Activities": {}}
if "Structure" not in cache:
cache["Structure"] = []
self._folderRecurse(cache["Structure"], dbcl, syncRoot)
activities = []
exclusions = []
for dir in cache["Structure"]:
for file in dir["Files"]:
path = file["Path"]
if svcRec.Authorization["Full"]:
relPath = path.replace(syncRoot, "", 1)
else:
relPath = path.replace("/Apps/tapiriik/", "", 1) # dropbox api is meh api
existing = [(k, x) for k, x in cache["Activities"].items() if x["Path"] == relPath] # path is relative to syncroot to reduce churn if they relocate it
existing = existing[0] if existing else None
if existing is not None:
existUID, existing = existing
if existing and existing["Rev"] == file["Rev"]:
# don't need entire activity loaded here, just UID
act = UploadedActivity()
act.UID = existUID
act.StartTime = datetime.strptime(existing["StartTime"], "%H:%M:%S %d %m %Y %z")
if "EndTime" in existing: # some cached activities may not have this, it is not essential
act.EndTime = datetime.strptime(existing["EndTime"], "%H:%M:%S %d %m %Y %z")
else:
logger.debug("Retrieving %s (%s)" % (path, "outdated meta cache" if existing else "not in meta cache"))
# get the full activity
try:
act, rev = self._getActivity(svcRec, dbcl, path)
except APIExcludeActivity as e:
logger.info("Encountered APIExcludeActivity %s" % str(e))
exclusions.append(e)
continue
del act.Laps
act.Laps = [] # Yeah, I'll process the activity twice, but at this point CPU time is more plentiful than RAM.
cache["Activities"][act.UID] = {"Rev": rev, "Path": relPath, "StartTime": act.StartTime.strftime("%H:%M:%S %d %m %Y %z"), "EndTime": act.EndTime.strftime("%H:%M:%S %d %m %Y %z")}
tagRes = self._tagActivity(relPath)
act.ServiceData = {"Path": path, "Tagged":tagRes is not None}
act.Type = tagRes if tagRes is not None else ActivityType.Other
logger.debug("Activity s/t %s" % act.StartTime)
activities.append(act)
cachedb.dropbox_cache.update({"ExternalID": svcRec.ExternalID}, cache, upsert=True)
return activities, exclusions
示例4: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
cookies = self._get_cookies(record=serviceRecord)
activities = []
exclusions = []
pageUri = self.OpenFitEndpoint + "/fitnessActivities.json"
while True:
logger.debug("Req against " + pageUri)
res = requests.get(pageUri, cookies=cookies)
res = res.json()
for act in res["items"]:
activity = UploadedActivity()
activity.ServiceData = {"ActivityURI": act["uri"]}
if len(act["name"].strip()):
activity.Name = act["name"]
activity.StartTime = dateutil.parser.parse(act["start_time"])
if isinstance(activity.StartTime.tzinfo, tzutc):
activity.TZ = pytz.utc # The dateutil tzutc doesn't have an _offset value.
else:
activity.TZ = pytz.FixedOffset(activity.StartTime.tzinfo._offset.total_seconds() / 60) # Convert the dateutil lame timezones into pytz awesome timezones.
activity.StartTime = activity.StartTime.replace(tzinfo=activity.TZ)
activity.EndTime = activity.StartTime + timedelta(seconds=float(act["duration"]))
activity.Stats.MovingTime = ActivityStatistic(ActivityStatisticUnit.Time, value=timedelta(seconds=float(act["duration"]))) # OpenFit says this excludes paused times.
# Sometimes activities get returned with a UTC timezone even when they are clearly not in UTC.
if activity.TZ == pytz.utc:
# So, we get the first location in the activity and calculate the TZ from that.
try:
firstLocation = self._downloadActivity(serviceRecord, activity, returnFirstLocation=True)
except APIExcludeActivity:
pass
else:
activity.CalculateTZ(firstLocation)
activity.AdjustTZ()
logger.debug("Activity s/t " + str(activity.StartTime))
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Meters, value=float(act["total_distance"]))
types = [x.strip().lower() for x in act["type"].split(":")]
types.reverse() # The incoming format is like "walking: hiking" and we want the most specific first
activity.Type = None
for type_key in types:
if type_key in self._activityMappings:
activity.Type = self._activityMappings[type_key]
break
if not activity.Type:
exclusions.append(APIExcludeActivity("Unknown activity type %s" % act["type"], activityId=act["uri"]))
continue
activity.CalculateUID()
activities.append(activity)
if not exhaustive or "next" not in res or not len(res["next"]):
break
else:
pageUri = res["next"]
return activities, exclusions
示例5: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
#https://connect.garmin.com/modern/proxy/activitylist-service/activities/search/activities?limit=20&start=0
page = 1
pageSz = 100
activities = []
exclusions = []
while True:
logger.debug("Req with " + str({"start": (page - 1) * pageSz, "limit": pageSz}))
res = self._request_with_reauth(lambda session: session.get("https://connect.garmin.com/modern/proxy/activitylist-service/activities/search/activities", params={"start": (page - 1) * pageSz, "limit": pageSz}), serviceRecord)
try:
res = res.json()
except ValueError:
res_txt = res.text # So it can capture in the log message
raise APIException("Parse failure in GC list resp: %s - %s" % (res.status_code, res_txt))
for act in res:
activity = UploadedActivity()
# stationary activities have movingDuration = None while non-gps static activities have 0.0
activity.Stationary = act["movingDuration"] is None
activity.GPS = act["hasPolyline"]
activity.Private = act["privacy"]["typeKey"] == "private"
activity_name = act["activityName"]
logger.debug("Name " + activity_name if activity_name is not None else "Untitled" + ":")
if activity_name is not None and len(activity_name.strip()) and activity_name != "Untitled": # This doesn't work for internationalized accounts, oh well.
activity.Name = activity_name
activity_description = act["description"]
if activity_description is not None and len(activity_description.strip()):
activity.Notes = activity_description
activity.StartTime = pytz.utc.localize(datetime.strptime(act["startTimeGMT"], "%Y-%m-%d %H:%M:%S"))
if act["elapsedDuration"] is not None:
activity.EndTime = activity.StartTime + timedelta(0, float(act["elapsedDuration"])/1000)
else:
activity.EndTime = activity.StartTime + timedelta(0, float(act["duration"]))
logger.debug("Activity s/t " + str(activity.StartTime) + " on page " + str(page))
if "distance" in act and act["distance"] and float(act["distance"]) != 0:
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Meters, value=float(act["distance"]))
activity.Type = self._resolveActivityType(act["activityType"]["typeKey"])
activity.CalculateUID()
activity.ServiceData = {"ActivityID": int(act["activityId"])}
activities.append(activity)
logger.debug("Finished page " + str(page))
if not exhaustive or len(res) == 0:
break
else:
page += 1
return activities, exclusions
示例6: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
activities = []
session = self._get_session(record=serviceRecord)
session.headers.update({"Accept": "application/json"})
workouts_resp = session.get("https://api.trainerroad.com/api/careerworkouts")
if workouts_resp.status_code != 200:
if workouts_resp.status_code == 401:
raise APIException("Invalid login", block=True, user_exception=UserException(UserExceptionType.Authorization, intervention_required=True))
raise APIException("Workout listing error")
cached_record = cachedb.trainerroad_meta.find_one({"ExternalID": serviceRecord.ExternalID})
if not cached_record:
cached_workout_meta = {}
else:
cached_workout_meta = cached_record["Workouts"]
workouts = workouts_resp.json()
for workout in workouts:
# Un/f their API doesn't provide the start/end times in the list response
# So we need to pull the extra data, if it's not already cached
workout_id = str(workout["Id"]) # Mongo doesn't do non-string keys
if workout_id not in cached_workout_meta:
meta_resp = session.get("https://api.trainerroad.com/api/careerworkouts?guid=%s" % workout["Guid"])
# We don't need everything
full_meta = meta_resp.json()
meta = {key: full_meta[key] for key in ["WorkoutDate", "WorkoutName", "WorkoutNotes", "TotalMinutes", "TotalKM", "AvgWatts", "Kj"]}
cached_workout_meta[workout_id] = meta
else:
meta = cached_workout_meta[workout_id]
activity = UploadedActivity()
activity.ServiceData = {"ID": int(workout_id)}
activity.Name = meta["WorkoutName"]
activity.Notes = meta["WorkoutNotes"]
activity.Type = ActivityType.Cycling
# Everything's in UTC
activity.StartTime = dateutil.parser.parse(meta["WorkoutDate"]).replace(tzinfo=pytz.utc)
activity.EndTime = activity.StartTime + timedelta(minutes=meta["TotalMinutes"])
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Kilometers, value=meta["TotalKM"])
activity.Stats.Power = ActivityStatistic(ActivityStatisticUnit.Watts, avg=meta["AvgWatts"])
activity.Stats.Energy = ActivityStatistic(ActivityStatisticUnit.Kilojoules, value=meta["Kj"])
activity.Stationary = False
activity.GPS = False
activity.CalculateUID()
activities.append(activity)
cachedb.trainerroad_meta.update({"ExternalID": serviceRecord.ExternalID}, {"ExternalID": serviceRecord.ExternalID, "Workouts": cached_workout_meta}, upsert=True)
return activities, []
示例7: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
logger.debug("Checking motivato premium state")
self._applyPaymentState(serviceRecord)
logger.debug("Motivato DownloadActivityList")
session = self._get_session(record=serviceRecord)
activities = []
exclusions = []
self._rate_limit()
retried_auth = False
#headers = {'X-App-With-Tracks': "true"}
headers = {}
res = session.post(self._urlRoot + "/api/workouts/sync", headers=headers)
if res.status_code == 403 and not retried_auth:
retried_auth = True
session = self._get_session(serviceRecord, skip_cache=True)
try:
respList = res.json();
except ValueError:
res_txt = res.text # So it can capture in the log message
raise APIException("Parse failure in Motivato list resp: %s" % res.status_code)
for actInfo in respList:
if "duration" in actInfo:
duration = self._durationToSeconds(actInfo["duration"])
else:
continue
activity = UploadedActivity()
if "time_start" in actInfo["metas"]:
startTimeStr = actInfo["training_at"] + " " + actInfo["metas"]["time_start"]
else:
startTimeStr = actInfo["training_at"] + " 00:00:00"
activity.StartTime = self._parseDateTime(startTimeStr)
activity.EndTime = self._parseDateTime(startTimeStr) + timedelta(seconds=duration)
activity.Type = self._reverseActivityMappings[actInfo["discipline_id"]]
activity.Stats.TimerTime = ActivityStatistic(ActivityStatisticUnit.Seconds, value=duration)
if "distance" in actInfo:
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Kilometers, value=float(actInfo["distance"]))
#activity.Stats.Speed = ActivityStatistic(ActivityStatisticUnit.KilometersPerSecond, value=1.0/float(actInfo["metas"]["pace"]))
activity.ServiceData={"WorkoutID": int(actInfo["id"])}
activity.CalculateUID()
logger.debug("Generated UID %s" % activity.UID)
activities.append(activity)
return activities, exclusions
示例8: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, svcRecord, exhaustive=False):
activities = []
exclusions = []
url = self.SingletrackerDomain + "getRidesByUserId"
extID = svcRecord.ExternalID
payload = {"userId": extID}
headers = {
'content-type': "application/json",
'cache-control': "no-cache",
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
try:
reqdata = response.json()
except ValueError:
raise APIException("Failed parsing Singletracker list response %s - %s" % (resp.status_code, resp.text))
for ride in reqdata:
activity = UploadedActivity()
activity.StartTime = datetime.strptime(
datetime.utcfromtimestamp(ride["startTime"]).strftime('%Y-%m-%d %H:%M:%S'), "%Y-%m-%d %H:%M:%S")
if "stopTime" in ride:
activity.EndTime = datetime.strptime(
datetime.utcfromtimestamp(ride["stopTime"]).strftime('%Y-%m-%d %H:%M:%S'), "%Y-%m-%d %H:%M:%S")
activity.ServiceData = {"ActivityID": ride["rideId"], "Manual": "False"}
activity.Name = ride["trackName"]
logger.debug("\tActivity s/t %s: %s" % (activity.StartTime, activity.Name))
activity.Type = ActivityType.MountainBiking
if "totalDistance" in ride:
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Meters, value=ride["totalDistance"])
if "avgSpeed" in ride:
activity.Stats.Speed = ActivityStatistic(ActivityStatisticUnit.MetersPerSecond,
avg=ride["avgSpeed"])
activity.Notes = None
activity.GPS = True
activity.Private = False
activity.Stationary = False # True = no sensor data
activity.CalculateUID()
activities.append(activity)
return activities, exclusions
示例9: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
session = self._get_session(serviceRecord)
list_params = self._with_auth(session, {"count": 20, "offset": 1})
activities = []
exclusions = []
while True:
list_resp = session.get("https://api.nike.com/me/sport/activities", params=list_params)
list_resp = list_resp.json()
for act in list_resp["data"]:
activity = UploadedActivity()
activity.ServiceData = {"ID": act["activityId"]}
if act["status"] != "COMPLETE":
exclusions.append(APIExcludeActivity("Not complete", activityId=act["activityId"], permanent=False, userException=UserException(UserExceptionType.LiveTracking)))
continue
activity.StartTime = dateutil.parser.parse(act["startTime"]).replace(tzinfo=pytz.utc)
activity.EndTime = activity.StartTime + self._durationToTimespan(act["metricSummary"]["duration"])
tz_name = act["activityTimeZone"]
# They say these are all IANA standard names - they aren't
if tz_name in self._timezones:
tz_name = self._timezones[tz_name]
activity.TZ = pytz.timezone(tz_name)
if act["activityType"] in self._activityMappings:
activity.Type = self._activityMappings[act["activityType"]]
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Kilometers, value=float(act["metricSummary"]["distance"]))
activity.Stats.Strides = ActivityStatistic(ActivityStatisticUnit.Strides, value=int(act["metricSummary"]["steps"]))
activity.Stats.Energy = ActivityStatistic(ActivityStatisticUnit.Kilocalories, value=float(act["metricSummary"]["calories"]))
activity.CalculateUID()
activities.append(activity)
if len(list_resp["data"]) == 0 or not exhaustive:
break
list_params["offset"] += list_params["count"]
return activities, exclusions
示例10: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, svcRec, exhaustive=False):
dbcl = self._getClient(svcRec)
if not svcRec.Authorization["Full"]:
syncRoot = "/"
else:
syncRoot = svcRec.Config["SyncRoot"]
cache = cachedb.dropbox_cache.find_one({"ExternalID": svcRec.ExternalID})
if cache is None:
cache = {"ExternalID": svcRec.ExternalID, "Structure": [], "Activities": {}}
if "Structure" not in cache:
cache["Structure"] = []
self._folderRecurse(cache["Structure"], dbcl, syncRoot)
activities = []
exclusions = []
for dir in cache["Structure"]:
for file in dir["Files"]:
path = file["Path"]
if svcRec.Authorization["Full"]:
relPath = path.replace(syncRoot, "", 1)
else:
relPath = path.replace("/Apps/tapiriik/", "", 1) # dropbox api is meh api
hashedRelPath = self._hash_path(relPath)
if hashedRelPath in cache["Activities"]:
existing = cache["Activities"][hashedRelPath]
else:
existing = None
if not existing:
# Continue to use the old records keyed by UID where possible
existing = [
(k, x) for k, x in cache["Activities"].items() if "Path" in x and x["Path"] == relPath
] # path is relative to syncroot to reduce churn if they relocate it
existing = existing[0] if existing else None
if existing is not None:
existUID, existing = existing
existing["UID"] = existUID
if existing and existing["Rev"] == file["Rev"]:
# don't need entire activity loaded here, just UID
act = UploadedActivity()
act.UID = existing["UID"]
try:
act.StartTime = datetime.strptime(existing["StartTime"], "%H:%M:%S %d %m %Y %z")
except:
act.StartTime = datetime.strptime(
existing["StartTime"], "%H:%M:%S %d %m %Y"
) # Exactly one user has managed to break %z :S
if "EndTime" in existing: # some cached activities may not have this, it is not essential
act.EndTime = datetime.strptime(existing["EndTime"], "%H:%M:%S %d %m %Y %z")
else:
logger.debug(
"Retrieving %s (%s)" % (path, "outdated meta cache" if existing else "not in meta cache")
)
# get the full activity
try:
act, rev = self._getActivity(svcRec, dbcl, path)
except APIExcludeActivity as e:
logger.info("Encountered APIExcludeActivity %s" % str(e))
exclusions.append(strip_context(e))
continue
try:
act.EnsureTZ()
except:
pass # We tried.
if hasattr(act, "OriginatedFromTapiriik") and not act.CountTotalWaypoints():
# This is one of the files created when TCX export was hopelessly broken for non-GPS activities.
# Right now, no activities in dropbox from tapiriik should be devoid of waypoints - since dropbox doesn't receive stationary activities
# In the future when this changes, will obviously have to modify this code to also look at modification dates or similar.
if ".tcx.summary-data" in path:
logger.info("...summary file already moved")
else:
logger.info("...moving summary-only file")
dbcl.file_move(path, path.replace(".tcx", ".tcx.summary-data"))
continue # DON'T include in listing - it'll be regenerated
del act.Laps
act.Laps = (
[]
) # Yeah, I'll process the activity twice, but at this point CPU time is more plentiful than RAM.
cache["Activities"][hashedRelPath] = {
"Rev": rev,
"UID": act.UID,
"StartTime": act.StartTime.strftime("%H:%M:%S %d %m %Y %z"),
"EndTime": act.EndTime.strftime("%H:%M:%S %d %m %Y %z"),
}
tagRes = self._tagActivity(relPath)
act.ServiceData = {"Path": path, "Tagged": tagRes is not None}
act.Type = tagRes if tagRes is not None else ActivityType.Other
logger.debug("Activity s/t %s" % act.StartTime)
activities.append(act)
if "_id" in cache:
cachedb.dropbox_cache.save(cache)
#.........这里部分代码省略.........
示例11: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, svcRecord, exhaustive=False):
activities = []
exclusions = []
url = self.SetioDomain + "getRunsByUserId"
extID = svcRecord.ExternalID
payload = {"userId": extID}
headers = {
'content-type': "application/json",
'cache-control': "no-cache",
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
try:
reqdata = response.json()
except ValueError:
raise APIException("Failed parsing Setio list response %s - %s" % (resp.status_code, resp.text))
for ride in reqdata:
activity = UploadedActivity()
activity.StartTime = datetime.strptime(
datetime.utcfromtimestamp(ride["startTimeStamp"]).strftime('%Y-%m-%d %H:%M:%S'), "%Y-%m-%d %H:%M:%S")
if "stopTimeStamp" in ride:
activity.EndTime = datetime.strptime(
datetime.utcfromtimestamp(ride["stopTimeStamp"]).strftime('%Y-%m-%d %H:%M:%S'), "%Y-%m-%d %H:%M:%S")
activity.ServiceData = {"ActivityID": ride["runId"], "Manual": "False"}
activity.Name = ride["programName"]
logger.debug("\tActivity s/t %s: %s" % (activity.StartTime, activity.Name))
activity.Type = ActivityType.Running
if "totalDistance" in ride:
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Meters, value=ride["totalDistance"])
if "averageCadence" in ride:
activity.Stats.Cadence.update(
ActivityStatistic(ActivityStatisticUnit.RevolutionsPerMinute, avg=ride["averageCadence"]))
if "averageSpeed" in ride:
activity.Stats.Speed = ActivityStatistic(ActivityStatisticUnit.MetersPerSecond,
avg=ride["averageSpeed"])
# get comment
url = self.SetioDomain + "getRunComment"
payload = { "userId": extID, "runId": activity.ServiceData["ActivityID"]}
headers = {
'content-type': "application/json",
'cache-control': "no-cache",
}
streamdata = requests.post(url, data=json.dumps(payload), headers=headers)
if streamdata.status_code == 500:
raise APIException("Internal server error")
if streamdata.status_code == 403:
raise APIException("No authorization to download activity", block=True,
user_exception=UserException(UserExceptionType.Authorization,
intervention_required=True))
activity.Notes = None
if streamdata.status_code == 200: # Ok
try:
commentdata = streamdata.json()
except:
raise APIException("Stream data returned is not JSON")
if "comment" in commentdata:
activity.Notes = commentdata["comment"]
activity.GPS = True
activity.Private = False
activity.Stationary = False # True = no sensor data
activity.CalculateUID()
activities.append(activity)
return activities, exclusions
示例12: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
"""
GET List of Activities as JSON File
URL: http://app.velohero.com/export/workouts/json
Parameters:
user = username
pass = password
date_from = YYYY-MM-DD
date_to = YYYY-MM-DD
"""
activities = []
exclusions = []
discoveredWorkoutIds = []
params = self._add_auth_params({}, record=serviceRecord)
limitDateFormat = "%Y-%m-%d"
if exhaustive:
listEnd = datetime.now() + timedelta(days=1.5) # Who knows which TZ it's in
listStart = datetime(day=1, month=1, year=1980) # The beginning of time
else:
listEnd = datetime.now() + timedelta(days=1.5) # Who knows which TZ it's in
listStart = listEnd - timedelta(days=20) # Doesn't really matter
params.update({"date_from": listStart.strftime(limitDateFormat), "date_to": listEnd.strftime(limitDateFormat)})
logger.debug("Requesting %s to %s" % (listStart, listEnd))
res = requests.get(self._urlRoot + "/export/workouts/json", params=params)
if res.status_code != 200:
if res.status_code == 403:
raise APIException("Invalid login", block=True, user_exception=UserException(UserExceptionType.Authorization, intervention_required=True))
raise APIException("Unable to retrieve activity list")
res.raise_for_status()
try:
res = res.json()
except ValueError:
raise APIException("Could not decode activity list")
if "workouts" not in res:
raise APIException("No activities")
for workout in res["workouts"]:
workoutId = int(workout["id"])
if workoutId in discoveredWorkoutIds:
continue # There's the possibility of query overlap
discoveredWorkoutIds.append(workoutId)
if workout["file"] is not "1":
logger.debug("Skip workout with ID: " + str(workoutId) + " (no file)")
continue # Skip activity without samples (no PWX export)
activity = UploadedActivity()
logger.debug("Workout ID: " + str(workoutId))
# Duration (dur_time)
duration = self._durationToSeconds(workout["dur_time"])
activity.Stats.TimerTime = ActivityStatistic(ActivityStatisticUnit.Seconds, value=duration)
# Start time (date_ymd, start_time)
startTimeStr = workout["date_ymd"] + " " + workout["start_time"]
activity.StartTime = self._parseDateTime(startTimeStr)
# End time (date_ymd, start_time) + dur_time
activity.EndTime = self._parseDateTime(startTimeStr) + timedelta(seconds=duration)
# Sport (sport_id)
if workout["sport_id"] in self._reverseActivityMappings:
activity.Type = self._reverseActivityMappings[workout["sport_id"]]
else:
activity.Type = ActivityType.Other
# Distance (dist_km)
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Kilometers, value=float(workout["dist_km"]))
# Workout is hidden
activity.Private = workout["hide"] == "1"
activity.ServiceData = {"workoutId": workoutId}
activity.CalculateUID()
activities.append(activity)
return activities, exclusions
示例13: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
#http://connect.garmin.com/proxy/activity-search-service-1.0/json/activities?&start=0&limit=50
session = self._get_session(record=serviceRecord)
page = 1
pageSz = 100
activities = []
exclusions = []
while True:
logger.debug("Req with " + str({"start": (page - 1) * pageSz, "limit": pageSz}))
self._rate_limit()
retried_auth = False
while True:
res = session.get("http://connect.garmin.com/proxy/activity-search-service-1.0/json/activities", params={"start": (page - 1) * pageSz, "limit": pageSz})
# It's 10 PM and I have no clue why it's throwing these errors, maybe we just need to log in again?
if res.status_code == 403 and not retried_auth:
retried_auth = True
session = self._get_session(serviceRecord, skip_cache=True)
else:
break
try:
res = res.json()["results"]
except ValueError:
res_txt = res.text # So it can capture in the log message
raise APIException("Parse failure in GC list resp: %s" % res.status_code)
if "activities" not in res:
break # No activities on this page - empty account.
for act in res["activities"]:
act = act["activity"]
activity = UploadedActivity()
# Don't really know why sumSampleCountTimestamp doesn't appear in swim activities - they're definitely timestamped...
activity.Stationary = "sumSampleCountSpeed" not in act and "sumSampleCountTimestamp" not in act
activity.GPS = "endLatitude" in act
activity.Private = act["privacy"]["key"] == "private"
try:
activity.TZ = pytz.timezone(act["activityTimeZone"]["key"])
except pytz.exceptions.UnknownTimeZoneError:
activity.TZ = pytz.FixedOffset(float(act["activityTimeZone"]["offset"]) * 60)
logger.debug("Name " + act["activityName"]["value"] + ":")
if len(act["activityName"]["value"].strip()) and act["activityName"]["value"] != "Untitled": # This doesn't work for internationalized accounts, oh well.
activity.Name = act["activityName"]["value"]
if len(act["activityDescription"]["value"].strip()):
activity.Notes = act["activityDescription"]["value"]
# beginTimestamp/endTimestamp is in UTC
activity.StartTime = pytz.utc.localize(datetime.utcfromtimestamp(float(act["beginTimestamp"]["millis"])/1000))
if "sumElapsedDuration" in act:
activity.EndTime = activity.StartTime + timedelta(0, round(float(act["sumElapsedDuration"]["value"])))
elif "sumDuration" in act:
activity.EndTime = activity.StartTime + timedelta(minutes=float(act["sumDuration"]["minutesSeconds"].split(":")[0]), seconds=float(act["sumDuration"]["minutesSeconds"].split(":")[1]))
else:
activity.EndTime = pytz.utc.localize(datetime.utcfromtimestamp(float(act["endTimestamp"]["millis"])/1000))
logger.debug("Activity s/t " + str(activity.StartTime) + " on page " + str(page))
activity.AdjustTZ()
if "sumDistance" in act and float(act["sumDistance"]["value"]) != 0:
activity.Stats.Distance = ActivityStatistic(self._unitMap[act["sumDistance"]["uom"]], value=float(act["sumDistance"]["value"]))
activity.Type = self._resolveActivityType(act["activityType"]["key"])
activity.CalculateUID()
activity.ServiceData = {"ActivityID": int(act["activityId"])}
activities.append(activity)
logger.debug("Finished page " + str(page) + " of " + str(res["search"]["totalPages"]))
if not exhaustive or int(res["search"]["totalPages"]) == page:
break
else:
page += 1
return activities, exclusions
示例14: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
oauthSession = self._oauthSession(serviceRecord)
activities = []
exclusions = []
page_url = "https://api.endomondo.com/api/1/workouts"
while True:
resp = oauthSession.get(page_url)
try:
respList = resp.json()["data"]
except ValueError:
raise APIException("Error decoding activity list resp %s %s" % (resp.status_code, resp.text))
for actInfo in respList:
activity = UploadedActivity()
activity.StartTime = self._parseDate(actInfo["start_time"])
print("Activity s/t %s" % activity.StartTime)
if "is_tracking" in actInfo and actInfo["is_tracking"]:
exclusions.append(APIExcludeActivity("Not complete", activityId=actInfo["id"], permanent=False, userException=UserException(UserExceptionType.LiveTracking)))
continue
if "end_time" in actInfo:
activity.EndTime = self._parseDate(actInfo["end_time"])
if actInfo["sport"] in self._activityMappings:
activity.Type = self._activityMappings[actInfo["sport"]]
# "duration" is timer time
if "duration_total" in actInfo:
activity.Stats.TimerTime = ActivityStatistic(ActivityStatisticUnit.Seconds, value=float(actInfo["duration_total"]))
if "distance_total" in actInfo:
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Kilometers, value=float(actInfo["distance_total"]))
if "calories_total" in actInfo:
activity.Stats.Energy = ActivityStatistic(ActivityStatisticUnit.Kilocalories, value=float(actInfo["calories_total"]))
activity.Stats.Elevation = ActivityStatistic(ActivityStatisticUnit.Meters)
if "altitude_max" in actInfo:
activity.Stats.Elevation.Max = float(actInfo["altitude_max"])
if "altitude_min" in actInfo:
activity.Stats.Elevation.Min = float(actInfo["altitude_min"])
if "total_ascent" in actInfo:
activity.Stats.Elevation.Gain = float(actInfo["total_ascent"])
if "total_descent" in actInfo:
activity.Stats.Elevation.Loss = float(actInfo["total_descent"])
activity.Stats.Speed = ActivityStatistic(ActivityStatisticUnit.KilometersPerHour)
if "speed_max" in actInfo:
activity.Stats.Speed.Max = float(actInfo["speed_max"])
if "heart_rate_avg" in actInfo:
activity.Stats.HR = ActivityStatistic(ActivityStatisticUnit.BeatsPerMinute, avg=float(actInfo["heart_rate_avg"]))
if "heart_rate_max" in actInfo:
activity.Stats.HR.update(ActivityStatistic(ActivityStatisticUnit.BeatsPerMinute, max=float(actInfo["heart_rate_max"])))
if "cadence_avg" in actInfo:
activity.Stats.Cadence = ActivityStatistic(ActivityStatisticUnit.RevolutionsPerMinute, avg=int(actInfo["cadence_avg"]))
if "cadence_max" in actInfo:
activity.Stats.Cadence.update(ActivityStatistic(ActivityStatisticUnit.RevolutionsPerMinute, max=int(actInfo["cadence_max"])))
if "title" in actInfo:
activity.Name = actInfo["title"]
activity.ServiceData = {"WorkoutID": int(actInfo["id"])}
activity.CalculateUID()
activities.append(activity)
paging = resp.json()["paging"]
if "next" not in paging or not paging["next"] or not exhaustive:
break
else:
page_url = paging["next"]
return activities, exclusions
示例15: DownloadActivityList
# 需要导入模块: from tapiriik.services.interchange import UploadedActivity [as 别名]
# 或者: from tapiriik.services.interchange.UploadedActivity import ServiceData [as 别名]
def DownloadActivityList(self, serviceRecord, exhaustive=False):
headers = self._getAuthHeaders(serviceRecord)
activities = []
exclusions = []
pageUri = self.OpenFitEndpoint + "/fitnessActivities.json"
activity_tz_cache_raw = cachedb.sporttracks_meta_cache.find_one({"ExternalID": serviceRecord.ExternalID})
activity_tz_cache_raw = activity_tz_cache_raw if activity_tz_cache_raw else {"Activities":[]}
activity_tz_cache = dict([(x["ActivityURI"], x["TZ"]) for x in activity_tz_cache_raw["Activities"]])
while True:
logger.debug("Req against " + pageUri)
res = requests.get(pageUri, headers=headers)
try:
res = res.json()
except ValueError:
raise APIException("Could not decode activity list response %s %s" % (res.status_code, res.text))
for act in res["items"]:
activity = UploadedActivity()
activity.ServiceData = {"ActivityURI": act["uri"]}
if len(act["name"].strip()):
activity.Name = act["name"]
# Longstanding ST.mobi bug causes it to return negative partial-hour timezones as "-2:-30" instead of "-2:30"
fixed_start_time = re.sub(r":-(\d\d)", r":\1", act["start_time"])
activity.StartTime = dateutil.parser.parse(fixed_start_time)
if isinstance(activity.StartTime.tzinfo, tzutc):
activity.TZ = pytz.utc # The dateutil tzutc doesn't have an _offset value.
else:
activity.TZ = pytz.FixedOffset(activity.StartTime.tzinfo.utcoffset(activity.StartTime).total_seconds() / 60) # Convert the dateutil lame timezones into pytz awesome timezones.
activity.StartTime = activity.StartTime.replace(tzinfo=activity.TZ)
activity.EndTime = activity.StartTime + timedelta(seconds=float(act["duration"]))
activity.Stats.TimerTime = ActivityStatistic(ActivityStatisticUnit.Seconds, value=float(act["duration"])) # OpenFit says this excludes paused times.
# Sometimes activities get returned with a UTC timezone even when they are clearly not in UTC.
if activity.TZ == pytz.utc:
if act["uri"] in activity_tz_cache:
activity.TZ = pytz.FixedOffset(activity_tz_cache[act["uri"]])
else:
# So, we get the first location in the activity and calculate the TZ from that.
try:
firstLocation = self._downloadActivity(serviceRecord, activity, returnFirstLocation=True)
except APIExcludeActivity:
pass
else:
try:
activity.CalculateTZ(firstLocation, recalculate=True)
except:
# We tried!
pass
else:
activity.AdjustTZ()
finally:
activity_tz_cache[act["uri"]] = activity.StartTime.utcoffset().total_seconds() / 60
logger.debug("Activity s/t " + str(activity.StartTime))
activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Meters, value=float(act["total_distance"]))
types = [x.strip().lower() for x in act["type"].split(":")]
types.reverse() # The incoming format is like "walking: hiking" and we want the most specific first
activity.Type = None
for type_key in types:
if type_key in self._activityMappings:
activity.Type = self._activityMappings[type_key]
break
if not activity.Type:
exclusions.append(APIExcludeActivity("Unknown activity type %s" % act["type"], activityId=act["uri"], userException=UserException(UserExceptionType.Other)))
continue
activity.CalculateUID()
activities.append(activity)
if not exhaustive or "next" not in res or not len(res["next"]):
break
else:
pageUri = res["next"]
logger.debug("Writing back meta cache")
cachedb.sporttracks_meta_cache.update({"ExternalID": serviceRecord.ExternalID}, {"ExternalID": serviceRecord.ExternalID, "Activities": [{"ActivityURI": k, "TZ": v} for k, v in activity_tz_cache.items()]}, upsert=True)
return activities, exclusions