Skip to content

Commit

Permalink
update static resources
Browse files Browse the repository at this point in the history
  • Loading branch information
spencerattick committed Apr 10, 2024
1 parent b887558 commit 8e04d13
Show file tree
Hide file tree
Showing 19 changed files with 1,429 additions and 920 deletions.
6 changes: 5 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
VITE_SERVER_URL=http://localhost:3000
STRAVA_EXPIRATION_TIME=1683606397
STRAVA_CACHED_REFRESH_TOKEN=25bd1cf38e37ee07e53d446f10ef812daee4d9bc
STRAVA_CACHED_TOKEN=25b0ab3f4831c7fba452bfa39910b730db955be7
STRAVA_CLIENT_ID=105494
STRAVA_CLIENT_SECRET=aeca4b4832d195c467d23e1c465781eed04be76b
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules/
.DS_Store
.DS_Store
.env
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/src/test.js"
}
]
}
2 changes: 1 addition & 1 deletion assets/staticGoodreadsFeed.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion assets/staticMediumFeed.json

Large diffs are not rendered by default.

863 changes: 0 additions & 863 deletions dist/assets/index-049fdd1d.js

This file was deleted.

866 changes: 866 additions & 0 deletions dist/assets/index-5d1ad553.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Spencer's Portfolio</title>
<script type="module" crossorigin src="/assets/index-049fdd1d.js"></script>
<script type="module" crossorigin src="/assets/index-5d1ad553.js"></script>
<link rel="stylesheet" href="/assets/index-3e40f224.css">
</head>
<body>
Expand Down
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@fortawesome/react-fontawesome": "^0.2.0",
"@types/node": "^18.13.0",
"@vitejs/plugin-react": "^3.1.0",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
124 changes: 122 additions & 2 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ const express = require('express');
const app = express();
const { parse } = require('rss-to-json');
const path = require('path');

// [] see about not allowing * CORS requests
const dotenv = require('dotenv');
require('dotenv').config();
const fs = require('fs');

// Allow cross-origin requests from Vite
app.use(function(req, res, next) {
Expand Down Expand Up @@ -35,6 +36,125 @@ app.get('/api/feed', async (req, res) => {
}
});

//STRAVA ROUTE START
const isStravaTokenExpired = (currentExpirationTime) => {
console.log('IS STRAVA TOKEN EXPIRED')
const currentEpochTime = Date.now();
if (currentExpirationTime === 'undefined') {
return `There is an error with the currentEpirationTime, it's value is: ${currentExpirationTime}.`
}
return currentEpochTime > currentExpirationTime;
}

const generateNewToken = async () => {
console.log('Generating new token...');
const requestOptions = {
method: 'POST',
redirect: 'follow'
};
const requestURL = `https://www.strava.com/oauth/token?client_id=${process.env.STRAVA_CLIENT_ID}&client_secret=${process.env.STRAVA_CLIENT_SECRET}&grant_type=refresh_token&refresh_token=ReplaceWithRefreshToken&refresh_token=${process.env.STRAVA_CACHED_REFRESH_TOKEN}`;

try {
let response = await fetch(requestURL, requestOptions);
response = await response.json();
if (response.message === 'Bad Request') {
console.log(response);
return;
}
console.log('NO PROBLEM GETTING NEW TOKEN')
return {
refreshToken: await response.refresh_token,
expirationTime: await response.expires_at,
accessToken: await response.access_token
}
} catch (error) {
console.log(error);
}

}



const persistNewTokenData = async (newTokenData) => {
console.log('PERSIST NEW TOKEN DATA')
// Read the .env file
const envBuffer = fs.readFileSync('.env');
const envConfig = dotenv.parse(envBuffer);

// // // Update the relevant key with the new value
if (newTokenData.expirationTime) {
envConfig['STRAVA_EXPIRATION_TIME'] = newTokenData.expirationTime;
}
if (newTokenData.refreshToken) {
envConfig['STRAVA_CACHED_REFRESH_TOKEN'] = newTokenData.refreshToken;
}
if (newTokenData.accessToken) {
envConfig['STRAVA_CACHED_TOKEN'] = newTokenData.accessToken;
}

// const envText = Object.keys(envConfig).map(key => `${key}=${envConfig[key]}`).join('\n');
// try {
// await fs.promises.writeFile('.env', envText);
// console.log('File successfully written');
// } catch (error) {
// console.error('Error writing file:', error);
// }

};

const getStravaActivityData = async () => {
console.log('GET STRAVA ACTIVITY DATA')
console.log('Requesting activity data from Strava...');
let myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${process.env.STRAVA_CACHED_TOKEN}`);

const requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};

try {
const response = await fetch("https://www.strava.com/api/v3/athlete/activities", requestOptions);
return response.json();

} catch (error) {
console.log('error', error);
return;
}
}

//check to see if the expiration time has passed
const executeStravaLogic = async () => {
console.log('EXECUTE STRAVA LOGIC')
const isTokenExpired = isStravaTokenExpired(process.env.STRAVA_EXPIRATION_TIME);
console.log('TOKEN EXPIRED? ', isTokenExpired)

if (typeof isTokenExpired === 'string') {
console.log('Please resolve the error with the current expiration time stored in the .env file.');
return;
} else if (isTokenExpired) {
console.log('The expiration time has passed. Generating a new token...');
//if yes - generate a new token
const newTokenData = await generateNewToken();
if (!newTokenData.expirationTime) {
console.log('There was an error getting refresh token data.')
return;
}
//save the new token info to .env
persistNewTokenData(newTokenData);

}
// //make request to Strava activities endpoint
const stravaActivityData = await getStravaActivityData();
console.log(stravaActivityData[0].name);
};

app.get('/api/strava', executeStravaLogic);


//STRAVA ROUTE END

// Start the server
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
Expand Down
2 changes: 2 additions & 0 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Blog from './Blog';
import Contact from './Contact';
import Projects from './Projects';
import GoodReads from './GoodReads';
import Strava from './Strava';

// add movement that draws attention to important pieces of the site as you scroll

Expand All @@ -18,6 +19,7 @@ export default function App() {
<TechStack />
<Blog />
<GoodReads />
<Strava />
<Contact />
</div>
)
Expand Down
2 changes: 1 addition & 1 deletion src/Blog.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const getSixPostsOrMax = data => {
useEffect(() => {
async function fetchBlogPosts() {
try {
const response = await fetch(`${import.meta.env.VITE_SERVER_URL}/api/posts`);
const response = await fetch(`http://localhost:3000/api/posts`);
const data = await response.json();
setBlogPosts(getSixPostsOrMax(data));
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion src/GoodReads.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default function GoodReads() {

const fetchGoodReadsFeed = async () => {
try {
const response = await fetch(`${import.meta.env.VITE_SERVER_URL}/api/feed`);
const response = await fetch(`http://localhost:3000/api/feed`);
const data = await response.json();
setGoodReadsFeed(data);
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion src/Projects.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default function Projects() {
useEffect(() => {
async function fetchBlogPosts() {
try {
const response = await fetch(`${import.meta.env.VITE_SERVER_URL}/api/posts`);
const response = await fetch(`http://localhost:3000/api/posts`);
const data = await response.json();
setProjectPosts(getProjectPosts(data));
} catch (error) {
Expand Down
79 changes: 32 additions & 47 deletions src/Strava.jsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,32 @@
// https://developers.strava.com/docs/getting-started/#account

// get an API key




// FOLLOWING STEPS HERE: https://developers.strava.com/docs/getting-started/#oauth (this vid is pretty good: https://www.youtube.com/watch?v=sgscChKfGyg)


// 1. http://localhost/exchange_token?state=&code=62b8194da84fd2f4455851e52b26f49a1ca9991e&scope=read,read_all

// 2. curl --location --request POST 'https://www.strava.com/oauth/token?client_id=105494&client_secret=aeca4b4832d195c467d23e1c465781eed04be76b&code=62b8194da84fd2f4455851e52b26f49a1ca9991e&grant_type=authorization_code' \
// --header 'Authorization: Basic SXI5RjJySjRYWUhNRTNuYjJvSDhPYU5zaklNVlFmdzY6' \
// --data ''

// {
// "token_type": "Bearer",
// "expires_at": 1681258716,
// "expires_in": 21600,
// "refresh_token": "cc5a66ffbe22e42dac7aa175097485bffa03b123",
// "access_token": "b6ddf246cde306a6520efaf8c8686ce0d95cdfab",
// "athlete": {
// "id": 8470431,
// "username": "sattick",
// "resource_state": 2,
// "firstname": "Spencer",
// "lastname": "Attick",
// "bio": null,
// "city": "Oakland",
// "state": "California",
// "country": "United States",
// "sex": "M",
// "premium": false,
// "summit": false,
// "created_at": "2015-04-01T00:46:54Z",
// "updated_at": "2023-03-23T00:01:05Z",
// "badge_type_id": 0,
// "weight": 0.0,
// "profile_medium": "https://graph.facebook.com/1226490129/picture?height=256&width=256",
// "profile": "https://graph.facebook.com/1226490129/picture?height=256&width=256",
// "friend": null,
// "follower": null
// }
// }

3.
import React, { useEffect, useState } from 'react';
// import staticFeed from '../assets/staticGoodreadsFeed.json';

export default function Strava() {

const [stravaData, setStravaData] = useState([]);
const [error, setError] = useState(null);

useEffect(() => {
async function fetchStravaData() {
try {
const response = await fetch(`http://localhost:3000/api/strava`);
const data = await response.json();
setStravaData(data);
} catch (error) {
console.log(error);
setError(error);
}
}
fetchStravaData();
}, []);


return (
<div id="strava">
<h2>Strava</h2>
<div>
{JSON.stringify(stravaData[0])}
</div>
</div>
)
}
Loading

0 comments on commit 8e04d13

Please sign in to comment.