Skip to content

Commit

Permalink
feat: api for updating custom status and location (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexieyizhe authored Dec 20, 2020
1 parent 7e6e6bd commit 462950f
Show file tree
Hide file tree
Showing 19 changed files with 314 additions and 121 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/refresh.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Refresh
run: curl https://alexxie.com/api/api/refresh-now-playing
run: curl https://alexxie.com/api/refresh-now-playing
Binary file removed public/favicon-away.jpg
Binary file not shown.
5 changes: 3 additions & 2 deletions src/components/Bio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const Container = styled('div')`
`;

const Bio: FC = () => {
const { talkingPoint } = useSiteContext();
const { talkingPoint, currentCity } = useSiteContext();

return (
<Container>
Expand All @@ -37,7 +37,8 @@ const Bio: FC = () => {
<span className="dynamic">
<DynamicTime />
</span>{' '}
for me; I'm <DynamicCurrentStatus />
for me in <span className="dynamic">{currentCity}</span>
; I'm <DynamicCurrentStatus />
</Text>
</p>

Expand Down
9 changes: 7 additions & 2 deletions src/components/DynamicCurrentStatus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,14 @@ const nowPlayingMarkup = ({
};

const DynamicCurrentStatus: FC = memo(() => {
const { nowPlayingData, activity, spotifyToken } = useSiteContext();
const {
nowPlayingData,
customStatus,
activity,
spotifyToken,
} = useSiteContext();
const [statuses, setStatuses] = useState<(TNowPlayingData | string)[]>([
nowPlayingData ?? `probably ${activity}`,
nowPlayingData ?? customStatus ?? `probably ${activity}`,
]);

const refetchNp = useCallback(async () => {
Expand Down
2 changes: 1 addition & 1 deletion src/components/Heading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const H1 = styled('h1')`
margin-bottom: 32px;
@media only screen and (max-width: 600px) {
font-size: 32px;
font-size: 40px;
}
`;

Expand Down
19 changes: 19 additions & 0 deletions src/pages/api/refresh-now-playing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { NextApiRequest, NextApiResponse } from 'next';

import { StorageClient } from 'services/_server_';

export default async function handler(_: NextApiRequest, res: NextApiResponse) {
res.setHeader('Content-Type', 'application/json');

try {
const client = new StorageClient();
const { token } = await client.getSpotifyCredentials();
client.disconnect();

res.statusCode = 200;
res.end(JSON.stringify({ success: !!token }));
} catch (e) {
res.statusCode = 500;
res.end(JSON.stringify({ reason: JSON.stringify(e) }));
}
}
9 changes: 0 additions & 9 deletions src/pages/api/refresh-now-playing.tsx

This file was deleted.

50 changes: 50 additions & 0 deletions src/pages/api/update-location.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { NextApiRequest, NextApiResponse } from 'next';

import { authMiddleware, StorageClient, StorageKey } from 'services/_server_';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
res.setHeader('Content-Type', 'application/json');

const newLocation = req.query['loc'];
const newISODate = req.query['isoDate'] as string;

if (newLocation && newISODate) {
try {
const [hourDiff, minDiff] = [
Number(newISODate.slice(-6, -3)),
Number(newISODate.slice(-2)),
];

// get minutes from milliseconds
const offsetMins = hourDiff * 60 + minDiff;

console.log(
`Setting new location to ${newLocation} and offset to ${offsetMins}`
);
const client = new StorageClient();
const locOk = await client.set(StorageKey.CURRENT_CITY, newLocation);
const dateOk = await client.set(
StorageKey.CURRENT_UTC_OFFSET_MINS,
offsetMins
);
client.disconnect();

res.statusCode = 200;
res.end(
JSON.stringify({
success: !!locOk && !!dateOk,
location: newLocation,
offset: offsetMins,
})
);
} catch (e) {
res.statusCode = 500;
res.end(JSON.stringify({ reason: JSON.stringify(e.msg) }));
}
} else {
res.statusCode = 400;
res.end(JSON.stringify({ reason: 'No date and/or location provided!' }));
}
};

export default authMiddleware(handler);
28 changes: 28 additions & 0 deletions src/pages/api/update-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { NextApiRequest, NextApiResponse } from 'next';

import { authMiddleware, StorageClient, StorageKey } from 'services/_server_';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
res.setHeader('Content-Type', 'application/json');

const status = req.query['status'];

if (status) {
try {
const client = new StorageClient();
const statusSetOk = await client.set(StorageKey.STATUS, status);
client.disconnect();

res.statusCode = 200;
res.end(JSON.stringify({ success: !!statusSetOk, status }));
} catch (e) {
res.statusCode = 500;
res.end(JSON.stringify({ reason: JSON.stringify(e) }));
}
} else {
res.statusCode = 400;
res.end(JSON.stringify({ reason: 'No status provided!' }));
}
};

export default authMiddleware(handler);
14 changes: 10 additions & 4 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { InferGetStaticPropsType } from 'next';
import Head from 'next/head';
import dynamic from 'next/dynamic';

import { getNowPlayingDataServerSide, StorageClient } from 'services/_server_';
import {
getNowPlayingDataServerSide,
StorageClient,
StorageKey,
} from 'services/_server_';

import 'services/theme';
import { SiteContextProvider } from 'services/site/context';
Expand Down Expand Up @@ -75,8 +79,9 @@ export async function getStaticProps() {
console.debug('Retreving now playing data and timezone...');
const client = new StorageClient();
const { token } = await client.getSpotifyCredentials();
const currentTimeZone = await client.getTimezone();
const customStatus = await client.getStatus();
const currentOffset = await client.getTimezoneOffset();
const currentCity = await client.getCurrentCity();
const customStatus = await client.get(StorageKey.STATUS);
client.disconnect();

const nowPlayingData = await getNowPlayingDataServerSide(token);
Expand All @@ -85,7 +90,8 @@ export async function getStaticProps() {
props: {
nowPlayingData,
spotifyToken: token,
currentTimeZone,
currentOffset,
currentCity,
customStatus,
},
revalidate: 60, // regenerate page at most every minute
Expand Down
91 changes: 0 additions & 91 deletions src/services/_server_.ts

This file was deleted.

3 changes: 3 additions & 0 deletions src/services/_server_/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './now-playing';
export * from './middleware';
export * from './storage';
17 changes: 17 additions & 0 deletions src/services/_server_/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { NextApiRequest, NextApiResponse } from 'next';

const authMiddleware = (handler) => (
req: NextApiRequest,
res: NextApiResponse
) => {
if (!req.query['token'] || req.query['token'] !== process.env.API_TOKEN) {
res.statusCode = 401;
res.statusMessage = 'Unauthorized';
res.end();
return false;
}

handler(req, res);
};

export { authMiddleware };
13 changes: 13 additions & 0 deletions src/services/_server_/now-playing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { createCanvas, Image as CanvasImage } from 'canvas';

import { getNowPlaying } from 'services/now-playing';

const SERVER_SIDE_COLOR_OPTIONS = {
canvasBuilder: () => createCanvas(64, 64),
imageClass: CanvasImage,
};

const getNowPlayingDataServerSide = async (accessToken: string) =>
getNowPlaying(accessToken, SERVER_SIDE_COLOR_OPTIONS);

export { getNowPlayingDataServerSide };
Loading

0 comments on commit 462950f

Please sign in to comment.