Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calendar #43

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export default defineConfig(({ mode }) => {
server: {
port: VITE_DEV_PORT,
proxy: {
'^/api/': { target: `http://localhost:${SERVER_PORT}`, ws: true },
'^/(api|calendar)': { target: `http://localhost:${SERVER_PORT}`, ws: true },
},
},
build: {
Expand Down
3 changes: 3 additions & 0 deletions server/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import express, { type RequestHandler } from 'express';
import expressWs from 'express-ws';

import apiRouter from './api';
import calendarRouter from './calendar';

const app = express();
expressWs(app);
Expand All @@ -25,6 +26,8 @@ app.use(corsConfig);

app.use('/api', apiRouter(SERVER_DOMAIN));

app.use('/calendar', calendarRouter(SERVER_DOMAIN));

// Support history api
app.use(
history({
Expand Down
86 changes: 86 additions & 0 deletions server/calendar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import 'moment-timezone';

import express from 'express';
import ical from 'ical-generator';
import moment from 'moment-timezone';

import eagerIterator from './eager-iterator';
import { getSportIcon } from './sport-icons';
import { Strava } from './strava';

export default function calendarRouter(domain: string): express.Router {
const router = express.Router();

const mkRequestLogin = (res: express.Response) => async () => {
res.status(403).send('Not logged in');
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Handle logging in

return false;
};

router.get('/', async (req: express.Request, res: express.Response) => {
const token = req.cookies.token;
const requestLogin = mkRequestLogin(res);
if (token && (await new Strava(domain, token, requestLogin).hasToken())) {
const webcalDomain = domain.replace(/\w+(?=:\/\/)/, 'webcal');
const pathWithSlash = req.originalUrl.replace(/\/?$/, '/');
const fullPath = webcalDomain + pathWithSlash + token + '.ics';
res.redirect(fullPath);
} else {
await requestLogin();
}
});

router.get('/:token.ics', async (req: express.Request, res: express.Response) => {
const strava = new Strava(domain, req.params.token, mkRequestLogin(res));

res.type('text/calendar; charset=UTF-8');

const cal = ical({ name: 'Strava activities' });
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Add proper caching of ical (only fetch new activities, e.g. from past week)
  • Clear old caches after certain time
  • Handle logout through GUI
  • Add link to GUI


for await (const activity of eagerIterator(strava.getStravaActivities())) {
const startTime = moment(activity.start_date).tz(activity.timezone.split(' ')[1]);
const location = activity.start_latlng.join(', ');
Copy link
Owner Author

@c-harding c-harding May 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Consider geocoding here


const twoDigits = (val: number) => String(val.toFixed(0)).padStart(2, '0');

const toHms = (totalSeconds: number) => {
const hours = Math.floor(totalSeconds / 60 / 60),
minutes = Math.floor(totalSeconds / 60) % 60,
seconds = totalSeconds % 60;
return (hours ? [hours, twoDigits(minutes), twoDigits(seconds)] : [minutes, twoDigits(seconds)]).join(':');
};

const descriptionFields = {
'Elapsed time': activity.elapsed_time && `${toHms(activity.elapsed_time)}`,
'Moving time': activity.moving_time && `${toHms(activity.moving_time)}`,
Distance: activity.distance && `${(activity.distance / 1000).toFixed(2)} km`,
'Elevation gain': activity.total_elevation_gain && `${activity.total_elevation_gain.toFixed(0)} m`,
'Average speed':
activity.average_speed &&
activity.sport_type !== 'Run' &&
`${(activity.average_speed * 3.6).toFixed(1)} km/h`,
'Average pace':
activity.average_speed && activity.sport_type === 'Run' && `${toHms(1000 / activity.average_speed)}/km`,
'Average heart rate': activity.has_heartrate && `${activity.average_heartrate?.toFixed(0)} bpm`,
'Max heart rate': activity.has_heartrate && `${activity.max_heartrate?.toFixed(0)} bpm`,
};
const descriptionData = Object.entries(descriptionFields)
.filter(([, value]) => value)
.map(([label, value]) => `${label}: ${value}`)
.join('\n');

cal.createEvent({
summary: `${activity.name} ${getSportIcon(activity)}`,
location: location,
timezone: startTime.tz(),
start: startTime,
end: moment(startTime).add(activity.elapsed_time, 'seconds'),
url: `https://strava.com/activities/${activity.id}`,
description: descriptionData,
});
}

cal.serve(res);
});

return router;
}
4 changes: 4 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
"cookie-parser": "^1.4.7",
"express": "^4.21.1",
"express-ws": "^5.0.2",
"ical-generator": "^3.4.2",
"moment": "^2.29.4",
"moment-timezone": "^0.5.40",
"node-fetch": "^2.7.0",
"proper-lockfile": "^4.1.2",
"uuid": "^9.0.1"
Expand All @@ -30,6 +33,7 @@
"@types/cookie-parser": "^1.4.7",
"@types/express": "^4.17.21",
"@types/express-ws": "^3.0.5",
"@types/luxon": "^2.3.2",
"@types/node": "^20.17.7",
"@types/node-fetch": "^2.6.12",
"@types/uuid": "^9.0.8",
Expand Down
80 changes: 80 additions & 0 deletions server/sport-icons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { SummaryActivity } from './strava/model';

export function getSportIcon(source: SummaryActivity): string {
switch (source.sport_type) {
case 'Run':
case 'VirtualRun':
case 'TrailRun':
return '🏃';
case 'Walk':
return '🚶';
case 'Ride':
case 'EBikeRide':
case 'VirtualRide':
case 'Handcycle':
case 'Velomobile':
return '🚲';
case 'Swim':
return '🏊';
case 'AlpineSki':
case 'BackcountrySki':
case 'NordicSki':
return '⛷️';
case 'Snowboard':
return '🏂';
case 'IceSkate':
case 'Snowshoe':
return '⛸️';
case 'Skateboard':
return '🛹';
case 'RockClimbing':
return '🧗';
case 'Surfing':
case 'Windsurf':
case 'Kitesurf':
case 'StandUpPaddling':
return '🏄';
case 'Canoeing':
case 'Kayaking':
case 'Rowing':
case 'VirtualRow':
return '🛶';
case 'Sail':
return '⛵';
case 'Golf':
return '🏌';
case 'Soccer':
return '⚽';
case 'Crossfit':
case 'Elliptical':
case 'WeightTraining':
case 'HighIntensityIntervalTraining':
case 'Pilates':
case 'StairStepper':
return '🏋';
case 'Yoga':
return '🧘';
case 'Wheelchair':
return '🧑‍🦽';
case 'Hike':
return '🥾';
case 'Badminton':
return '🏸';
case 'Tennis':
return '🎾';
case 'EMountainBikeRide':
case 'MountainBikeRide':
case 'GravelRide':
return '🚵';
case 'InlineSkate':
return '🛼';
case 'TableTennis':
case 'Pickleball':
case 'Racquetball':
case 'Squash':
return '🏓';
case 'Workout':
default:
return '';
}
}
6 changes: 5 additions & 1 deletion server/strava/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export class Strava {
/**
* Fetches your data from the Strava API
*/
async *getStravaActivities(start?: number, end?: number): AsyncGenerator<unknown, void, undefined> {
async *getStravaActivities(start?: number, end?: number): AsyncGenerator<SummaryActivity, void, undefined> {
for await (const page of this.getStravaActivitiesPages(start, end)) {
yield* page;
}
Expand Down Expand Up @@ -99,6 +99,10 @@ export class Strava {
return await this.rawApi.get(`/activities/${id}`);
}

hasToken(): Promise<boolean> {
return this.rawApi.hasToken();
}

async logout(global?: boolean);
async logout(global: true, athlete: number);
async logout(global = false, athlete?: number) {
Expand Down
9 changes: 9 additions & 0 deletions server/strava/raw-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ export default class RawStravaApi {
};
}

async hasToken(): Promise<boolean> {
try {
await this.loadCache();
return true;
} catch (e) {
return false;
}
}

private async rawStravaAPI(endpoint: string, query: Record<string, string | number | undefined> = {}) {
const API_BASE = 'https://www.strava.com/api/v3';
const queryString = (Object.entries(query).filter(([, value]) => value) as [string, string | number][])
Expand Down
29 changes: 29 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,11 @@
resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee"
integrity sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==

"@types/luxon@^2.3.2":
version "2.4.0"
resolved "https://registry.yarnpkg.com/@types/luxon/-/luxon-2.4.0.tgz#897d3abc23b68d78b69d76a12c21e01eb5adab95"
integrity sha512-oCavjEjRXuR6URJEtQm0eBdfsBiEcGBZbq21of8iGkeKxU1+1xgKuFPClaBZl2KB8ZZBSWlgk61tH6Mf+nvZVw==

"@types/mapbox__point-geometry@*", "@types/mapbox__point-geometry@^0.1.4":
version "0.1.4"
resolved "https://registry.yarnpkg.com/@types/mapbox__point-geometry/-/mapbox__point-geometry-0.1.4.tgz#0ef017b75eedce02ff6243b4189210e2e6d5e56d"
Expand Down Expand Up @@ -2576,6 +2581,13 @@ [email protected]:
statuses "2.0.1"
toidentifier "1.0.1"

ical-generator@^3.4.2:
version "3.6.1"
resolved "https://registry.yarnpkg.com/ical-generator/-/ical-generator-3.6.1.tgz#097e9b4124de5554912ad30d341bdba644f6c312"
integrity sha512-tEH0OTNn00Mp61DcTxIFR+5fhsAivKk1LWAJUAbkMCI+M4yu+cZzT5X8rZf3b5PzFkMogh0zj3PsFh9bHvGGIQ==
dependencies:
uuid-random "^1.3.2"

[email protected]:
version "0.4.24"
resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b"
Expand Down Expand Up @@ -3117,6 +3129,18 @@ minimist@^1.2.0, minimist@^1.2.6:
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c"
integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==

moment-timezone@^0.5.40:
version "0.5.40"
resolved "https://registry.yarnpkg.com/moment-timezone/-/moment-timezone-0.5.40.tgz#c148f5149fd91dd3e29bf481abc8830ecba16b89"
integrity sha512-tWfmNkRYmBkPJz5mr9GVDn9vRlVZOTe6yqY92rFxiOdWXbjaR0+9LwQnZGGuNR63X456NqmEkbskte8tWL5ePg==
dependencies:
moment ">= 2.9.0"

"moment@>= 2.9.0", moment@^2.29.4:
version "2.29.4"
resolved "https://registry.yarnpkg.com/moment/-/moment-2.29.4.tgz#3dbe052889fe7c1b2ed966fcb3a77328964ef108"
integrity sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==

[email protected]:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
Expand Down Expand Up @@ -4264,6 +4288,11 @@ [email protected]:
resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713"
integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==

uuid-random@^1.3.2:
version "1.3.2"
resolved "https://registry.yarnpkg.com/uuid-random/-/uuid-random-1.3.2.tgz#96715edbaef4e84b1dcf5024b00d16f30220e2d0"
integrity sha512-UOzej0Le/UgkbWEO8flm+0y+G+ljUon1QWTEZOq1rnMAsxo2+SckbiZdKzAHHlVh6gJqI1TjC/xwgR50MuCrBQ==

uuid@^9.0.1:
version "9.0.1"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-9.0.1.tgz#e188d4c8853cc722220392c424cd637f32293f30"
Expand Down