Strava: обзор приложения для бега и велоспорта

Содержание:

Access

All calls to the Strava API require an defining the athlete and application making the call. Any registered Strava user can obtain an access_token by first creating an application at https://www.strava.com/settings/api.

The API application settings page provides a public access token to get started. See the Authentication page for more information about generating access tokens and the OAuth authorization flow.

Generally speaking, a Strava API application only has access to a user’s data after the user has authorized the application to use it. Segment and segment leaderboard data is available to all applications.

OAuth Overview

When OAuth is initiated, the user is prompted by the application to log in on the Strava website and to give consent to the requesting application. A user can opt out of the scopes requested by the application.

After the user accepts or rejects the authorization request, Strava redirects the user to a URL specified by the application. If the user authorized the application, the URL query string will include an authorization code and the scope accepted by the user. Apps should check which scopes a user has accepted. Applications complete the authorization process by exchanging the authorization code for a refresh token and short-lived access token.

Access tokens are used by applications to obtain and modify Strava resources on behalf of the authenticated athlete. Refresh tokens are used to obtain new access tokens when older ones expire.

Note that Google Sign-in will not work for applications using a mobile webview. See Google’s blog post for further information and ways to work around that limitation.

Conventions

Object representations

Depending on the type of request, objects will be returned in meta, summary or detailed representations. The representation of the returned object is indicated by the resource_state attribute.

Resource states, in increasing levels of detail.

  1. meta
  2. summary
  3. detailed

Pagination

Requests that return multiple items will be paginated to 30 items by default. The page parameter can be used to specify further pages or offsets. The per_page may also be used for custom page sizes up to 200. Note that in certain cases, the number of items returned in the response may be lower than the requested page size, even when that page is not the last. If you need to fully go through the full set of results, prefer iterating until an empty page is returned.

Polylines

Activity, segment and route API requests may include summary polylines of their respective paths. The values are string encodings of the latitude and longitude points using the Google encoded polyline algorithm format.

Dates

Dates and times follow the ISO 8601 standard, unless noted. A few examples:

  • 2015-08-23T15:46:20Z
  • 2018-06-24T09:54:13-07:00

For some resources the attribute is provided as a convenience. It represents the UTC version of the local start time of the event. Displaying this value as UTC will show the correct local start time. The local time zone is also provided for some resources and can be used along with the start_date to achieve this as well.

Request methods

Where possible, API V3 strives to use appropriate HTTP verbs for each action.

  • HEAD can be issued against any resource to get just the HTTP header info
  • GET used for retrieving resources
  • POST used for creating resources, or performing custom actions
  • PUT used for updating or replacing resources
  • DELETE used for removing resources

Status codes

Here is a list of our common status codes.

  • 200 Successful request
  • 201 Your activity/etc. was successfully created
  • 401 Unauthorized
  • 403 Forbidden; you cannot access
  • 404 Not found; the requested asset does not exist, or you are not authorized to see it
  • 429 Too Many Requests; you have exceeded rate limits
  • 500 Strava is having issues, please check https://status.strava.com

Как работает приложение Strava?

Итак, вы зарегистрировались в Strava. С чего начать? Настраивая свой профиль, добавьте личные параметры вроде роста и веса, чтобы приложение могло более точно анализировать ваши занятия. У пользователей также есть возможность добавить свое снаряжение, чтобы отслеживать, сколько уже километров “набегано” вот в тех кроссовках, а сколько вот в этих. Обычно для предотвращения травм рекомендуется менять кроссовки каждые 500–800 км, и приложение вам об этом сообщит.


Главная страница сервиса в веб-версии

Для того чтобы фиксировать свои тренировки в приложении, достаточно рабочего GPS. Сервис предложит выбрать тип активности (бег, велосипед, заплыв и пр.), после чего можно смело нажимать на кнопку «Запись». Во время тренировки, в случае если вы сделаете остановку, активируется функция «Автопауза».

Своему пользователю Strava автоматически рассчитывает пульсовые зоны, основываясь на его возрасте, но в веб-версии также доступно настроить их самому. Дополнительные знания о вас позволят приложению выводить коэффициент сложности тренировки – так называемое «Относительное усилие».

Как это работает? Во время тренировки ваш пульс отслеживается и сравнивается с максимальным. Относительное усилие покажет, насколько усердно вы занимались. Так, показатель будет высоким, если спортсмен долго занимался в своей «красной зоне». Впрочем, нужно заметить, что такая функция будет доступна только пользователям платной версии. На странице каждой тренировки спортсмен увидит, как менялись его темп или скорость, сердцебиение, каденс и мощность. Варьировать все эти данные можно при помощи ползунка, которым выделяются интересующие промежутки времени.

Тренировочные планы к марафону и полумарафону. Скачайте и начните подготовку сегодня.


Анализ велосипедной тренировки

В платной версии, называемой также Summit, на радость беспокоящимся за атлета родственникам есть к тому же функция Beacon, благодаря которой можно в реальном времени делиться данными о своем местоположении с членами семьи, друзьями, тренером, врачом.

Одной из интересных социальных составляющих приложения выступает сервис Strava Flybys, позволяющий увидеть на экране компьютера, как пользователь проходил записанный маршрут и кто тренировался рядом. Нередко участники используют Flybys для анализа гонки или другого массового спортивного мероприятия: на экране отображается положение всех участников, у кого есть эта активность в Strava, и можно понять, когда начала разворачиваться драма гонки, или же, как и где вы разминулись на тренировке с тем или иным спортсменом.

Возможности Strava на записи тренировок по GPS не заканчиваются. С ваших часов в программу могут подгружаться данные занятий в зале, в бассейне, на беговой дорожке, велостанке, на скалодроме. Пробежка на беговой дорожке или тренировка на велотренажере попадет в вашу общую беговую/велосипедную статистику.

В Strava нет планировщика занятий, но есть календарь, показывающий количество часов по месяцам, а также годовую статистику. В мобильной версии воспользуйтесь опцией «Тренировка», которая не даст вам «заблудиться» в проведенных занятиях. Нужно отметить, что такие данные сервис открывает лишь собственнику аккаунта, поэтому, если вашим тренировочным процессом руководит тренер, увидеть такую детальную информацию он не сможет.


Календарь тренировок покажет, какие объемы в часах выполняет спортсмен

Возвращаясь к нашему атлету, добавим, что на главном экране приложения, как веб, так и в мобильной версии, отслеживается объем занятий текущего месяца и недели в километрах и часах. Мотивируя не забрасывать выбранный вид спорта, приложение покажет вам сравнение текущего месяца занятий с прошлым. На скриншоте ниже показано, что пользователь приложения в феврале занимался на велосипеде в общей сложности 18 часов 53 минуты, а на текущий месяц имеет 2 часа 38 минут занятий, временно показывая снижение объема тренировок относительно объема на ту же дату прошлого месяца.

Статистика на месяц в мобильном приложении
Статистика по объему занятий за неделю в веб-версии

Token Exchange

Strava will respond to the authorization request by redirecting the user agent to the provided.

If access is denied, will be included in the query string.

If access is accepted, and parameters will be included in the query string. The parameter contains the authorization code required to complete the authentication process. is short lived and can only be used once. The application must now call the with its client ID and client secret to exchange the authorization code for a refresh token and short-lived access token.

The parameter will be always included in the response if it was initially provided by the application.

Request Parameters
client_id

required integer, in query

The application’s ID, obtained during registration.
client_secret

required string, in query

The application’s secret, obtained during registration.
code

required string, in query

The parameter obtained in the redirect.
grant_type

required string, in query

The grant type for the request. For initial authentication, must always be «authorization_code».

Example cURL Request

Response Parameters

A refresh token, access token, and access token expiration date will be issued upon successful authentication.

expires_at

integer

The number of seconds since the epoch when the provided access token will expire
expires_in

integer

Seconds until the short-lived access token will expire
refresh_token

string

The refresh token for this user, to be used to get the next access token for this user. Please expect that this value can change anytime you retrieve a new access token. Once a new refresh token code has been returned, the older code will no longer work.
athlete

string

A summary of athlete information

Example Response

Швейцарская стратегия

Страву часто называют социальной сетью для атлетов, и такие социальные аспекты были ещё до появления Фейсбука. «В своей основе спорт всегда был социальным, – говорит Куорлс – это поддержка, мотивация, товарищество, соревновательный характер и контролируемость». Такие вещи как таблица лидеров и беговые клубы очень влияют на это – «Представьте, что вам нужно встать утром с постели, когда на улице всё ещё темно и холодно и прыгнуть в бассейн. Другие атлеты будут вас мотивировать».

На вопрос, будет ли Страва делать собственные гаджеты? Куорлс сказал, что таких планов нет: «Это не наша сильная сторона. У нас есть множество партнёров, которые делают интересные вещи в этом направление. Мы будем придерживаться стратегии Швейцарии и оставаться открытой платформой».

Касательно других данных, которые Страва могла бы интегрировать в приложение, Куорлс сказал, что Страву интересуют данные поверметров, данные касающиеся формы и техники с блоков, которые могут крепиться к обуви или одежде — такие как Garmin Running Dynamics Pod. «Мы заинтригованы поверметрами в беге. Мы думаем это станет популярным у серьезных атлетов, не уверен будут ли обычные бегуны пользоваться такими технологиями, но всё возможно.» Возможность получить данные по каждому шагу спортсмена, может очень повлиять на эффективность спортивных занятий, особенно для тех кто готовиться к марафону.

«Я очень многому научился, изучая технику бега. Я думаю есть способы измерить правильную постановку стопы, осанку и так далее, но опять таки, на сколько это будет актуально, ещё под вопросом. Также существуют AI тренеры (искусственный интелект), например в таких девайсах как LifeBeam Vi. Страва ищет возможности для партнёрских отношений в этой области, но развивать свои технологии не будет.

И конечно стоит ожидать больше приложений на разных девайсах. Приложение для Apple Watch выглядит немного упрощённым, но Куорлс нас заверил, что так и должно быть: «Я не думаю что нужно копировать приложение с телефона на часы. Люди хотят иметь возможность записать тренировку, поставить паузу и остановить её. Часы это дополнение к телефону.»

«Частью социального аспекта Стравы есть возможность поделиться моментами триумфа с друзьями, и важную роль играют фото» — говорит Куорлс. Смарт часы не дают возможности сделать фото — это то что отличает их от смартфонов. «Люди предпочитают иметь камеру с собой. Например, камеру Google Clip можно прицепить на одежду, или, скажем, на голову, а встроенный интеллект сам сделает фото в идеальный момент».

Но если вернуться к началу статьи, Куорлс видит потенциал в отслеживании восстановления после тренировки. «Я часто смотрю на экран восстановления на моих часах Garmin. Похожая функция есть для премиум аккаунтов Strava на веб страничке. Но я хочу внедрить эти данные на другие девайсы и для большего числа пользователей. »

Details About Requesting Access

On both web and mobile the authorization page will prompt the user to grant your application access to their data. Scopes requested by the application are shown as checked boxes, but the user may opt out of any requested scopes. If an application relies on specific scopes to function properly, the application should make that clear before and after authentication.

client_id

required integer, in query

The application’s ID, obtained during registration.
redirect_uri

required string, in query

URL to which the user will be redirected after authentication. Must be within the callback domain specified by the application. and are white-listed.
response_type

required string, in query

Must be .
approval_prompt

string, in query

or , use to always show the authorization prompt even if the user has already authorized the current application, default is .
scope

required string, in query

Requested scopes, as a comma delimited string, e.g. «activity:read_all,activity:write». Applications should request only the scopes required for the application to function normally. The scope activity:read is required for activity webhooks.

  • : read public segments, public routes, public profile data, public posts, public events, club feeds, and leaderboards
  • :read private routes, private segments, and private events for the user
  • : read all profile information even if the user has set their profile visibility to Followers or Only You
  • : update the user’s weight and Functional Threshold Power (FTP), and access to star or unstar segments on their behalf
  • : read the user’s activity data for activities that are visible to Everyone and Followers, excluding privacy zone data
  • : the same access as , plus privacy zone data and access to read the user’s activities with visibility set to Only You
  • : access to create manual activities and uploads, and access to edit any activities that are visible to the app, based on activity read access level
state

string, in query

Returned in the redirect URI. Useful if the authentication is done from various points in an app.

Дополнительная мотивация

Несмотря на то, что приложение не обладает планировщиком занятий, однако имеет опцию «Задачи», распространяющуюся на бег и велосипед. Например, задача Run Climbing Challenge предлагает всем бегунам в течение месяца набрать 2000 метров высоты. Есть также миссии, нацеливающие спортсменов пробежать в этом месяце полумарафон или же провести длинный заезд на 100 км.

Все участники, выполнившие задачу, получают виртуальный значок победителя. В ходе соревнования можно отслеживать свою позицию глобально – среди всех пользователей, присоединившихся к челленджу, – а также с выборкой: среди подписок, по стране, по клубу, по весу, возрасту.

Для поддержания уровня мотивации своих пользователей сервис предлагает им соревноваться друг с другом на сегментах за «Рекорд участка» (РУ) или за звание «Царь горы» (ЦГ). Участки создают сами пользователи, а затем, каждый раз, когда по нему проедут или пробегут, в рейтинговой таблице сохраняется лучший результат каждого участника. У пользователя же остается весь архив его собственных результатов на том или ином сегменте, что позволяет увидеть свой прогресс за все время пользования приложением.

Сравнительная статистика спортсменов по бегу (слева) и велосипеду (справа)

Поскольку Strava задумывалась разработчиками как социальный инструмент, в веб-версии при просмотре страницы какого-либо атлета, если он не скрывает свои данные настройками конфиденциальности, будет доступно сравнение своих показателей с результатами выбранного участника. Вкупе с сегментами такая функция социализирует наши занятия и в некоторой степени превращает их в виртуальные соревнования, однако пользователям необходимо знать меру.

Впрочем, на участников, чьи рекорды явно неправдоподобны, есть возможность подать жалобу. Делается это на странице тренировки, вызвавшей подозрение. Самый частый бан – установление рекорда на сегменте при помощи транспорта.

Refreshing Expired Access Tokens

Access tokens expire six hours after they are created, so they must be refreshed in order for an application to maintain access to a user’s resources. Every time you get a new access token, we return a new refresh token as well. If you need to make a request, we recommend checking to see if the short-lived access token has expired. If it has expired, request a new short-lived access token with the last received refresh token.

To refresh an access token, applications should call the endpoint, specifying and including the application’s refresh token for the user as an additional parameter. If the application has an access token for the user that expires in more than one hour, the existing access token will be returned. If the application’s access tokens for the user are expired or will expire in one hour (3,600 seconds) or less, a new access token will be returned. In this case, both the newer and older access tokens can be used until they expire.

A refresh token is issued back to the application after all successful requests to the endpoint. The refresh token may or may not be the same refresh token used to make the request. Applications should persist the refresh token contained in the response, and always use the most recent refresh token for subsequent requests to obtain a new access token. Once a new refresh token is returned, the older refresh token is invalidated immediately.

Request Parameters
client_id

required integer, in query

The application’s ID, obtained during registration.
client_secret

required string, in query

The application’s secret, obtained during registration.
grant_type

required string, in query

The grant type for the request. When refreshing an access token, must always be «refresh_token».
refresh_token

required string, in query

The refresh token for this user, to be used to get the next access token for this user. Please expect that this value can change anytime you retrieve a new access token. Once a new refresh token code has been returned, the older code will no longer work.

Example cURL Request

Response Parameters
access_token

string

The short-lived access token
expires_at

integer

The number of seconds since the epoch when the provided access token will expire
expires_in

integer

Seconds until the short-lived access token will expire
refresh_token

string

The refresh token for this user, to be used to get the next access token for this user. Please expect that this value can change anytime you retrieve a new access token. Once a new refresh token code has been returned, the older code will no longer work.

Example Response

How to Store Short-Lived Access Tokens and Refresh Tokens
  • Storing the scopes your athletes accept is great in case you get unexpected results (for example: why am I not getting activities for this user?)
  • In general, we recommend storing short-lived access tokens and refresh tokens in separate tables
  • Note: This is just a recommendation and may not be the best implementation given your use case.

Интеграция Strava с другими программами

Не все пользователи пишут свою активность в Strava напрямую на смартфон, но сервис и на этот счет имеет огромную базу поддерживаемых программ. Вот лишь некоторые из них: Garmin, Zwift, Suunto, Amazfit, Fitbit, MIO, Polar, Tacx, TomTom, Wahoo. Таким образом, тренируясь с вашими любимыми часами, вы затем сможете просмотреть данные об активности инструментами Strava. Для этого нужно только связать собственную программу ваших часов со «Стравой».

Поддерживаемые «Стравой» устройства. Достаточно синхронизировать программу часов со Strava, чтобы тренировки автоматически дублировались в последней

Большой спорт в Strava

Чем Strava точно отличается от большинства аналогичных фитнес-приложений – это тем, что в ней нередко публикуют свои тренировки и гонки настоящие звезды видов спорта на выносливость. Аккаунты атлетов большого спорта будут помечены подписью «Профессиональный атлет». И если в России профи массово еще не пришли в этот сервис, на Западе спортсмены уже давно делятся с болельщиками своими маршрутами и данными тренировок. Вот так, например, выглядит страница 4-кратного победителя велогонки Тур дэ Франс Криса Фрума.

Не только профессиональные спортсмены «поселились» в Strava. Сервис стал дополнительной площадкой для компаний, гоночных команд и магазинов. В приложении для этого создана опция «Клубы». Создать свое сообщество может любой пользователь, но профессиональные, опять же как и в случае с про-атлетами, имеют специальную галочку и подпись «Подтвержденный клуб».

Для бегунов в компьютерной версии, кроме того, в разделе «Новинки» работает раздел «Беговые соревнования», где собраны самые «топовые» забеги. В профайле грядущего события будет указано число пользователей, подписавшихся на гонку, их цели. Забег можно обсудить с участниками, а в разделе «Еженедельная тренировка» почерпнуть информацию для подготовки.

Когда событие закончится, ко всему вышеперечисленному добавятся результаты подписавшихся. Наглядно на скриншоте со страницы Токийского марафона.

Client code

You will need to have a Java runtime installed on your machine to run Swagger. To generate client code, you first need to install Swagger Codegen 2.X. On macOS, you may use Homebrew:

To generate code in a given language, run and pass the following
parameters:

  • : Use for Strava’s API
  • : (optional) pass the settings or overrides you want the code generator to honor
  • : the target programming language you seek to generate code for (running by itself will print a list of available languages)
  • : where to write the resulting files

This example will generate Java code suitable to be packaged in an Android library:

Requesting Access

To initiate the flow, applications must redirect the user to Strava’s authorization page. The authorization endpoint is different for mobile and web applications.

Mobile applications

Our authentication flows are slightly different for Android and iOS due to App Store and Google Play Store guidelines and recommendations. Below you’ll find code samples for both platforms. Here are some details about mobile OAuth:

  • If a user does not have the Strava app installed, they should be redirected to mobile web to complete OAuth.
  • Mobile OAuth supports refresh tokens and short-lived access tokens. Mobile OAuth does not support forever access tokens.
  • Users must have version 75.0 or later of the Strava app installed in order to take advantage of mobile OAuth. Users without the Strava app or with an older app version will be brought to a web endpoint where they can authorize your app.
Android

Android apps can use an Implicit Intent to redirect users to the endpoint. The Strava app should open automatically if the user has it installed.

Sample code:

iOS

If the user does not have Strava installed, your app should use or , depending on which versions of iOS your app supports. If your app is linked on or after iOS 9.0, you must add in you app’s Info.plist file. It should be added under the key. Failure to do this will result in a crash when calling .

You should check first if your app can open the . If it can, the Strava app is installed and should handle the authentication. You can proceed by opening that same URL.

If your app is not able to open that URL, proceed with using the . You should use or to prevent the user from leaving your application to authenticate. Ensure that the is a registered url scheme in your application.

Sample code:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *