Skip to content

Redundant api #80

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

Open
wants to merge 4 commits into
base: master
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hot-loader": "^4.13.0",
"sass": "^1.83.0",
"styled-components": "^5.3.3",
"use-keyboard-shortcut": "^1.1.4"
},
Expand Down
6 changes: 4 additions & 2 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TAppOptions } from './pages/types';

export const APOD_API_URL = 'https://api.nasa.gov/planetary/apod';
export const API_KEY = 'hPgI2kGa1jCxvfXjv6hq6hsYBQawAqvjMaZNs447';
export const REDUNDANT_URL = 'https://apod.redundantrobot.com/apod';
export const REDUNDANT_RANDOM_URL = `${REDUNDANT_URL}/random`;

export const MIN_APOD_DATE = `1995-6-16`;
export const DELAY_FOR_HD_LOAD = 1500;
Expand All @@ -27,6 +27,7 @@ export const TODAY_COUNT = 'todayCount';
export const TODAY_LIMIT = 'todayLimit';
export const IS_TODAY_LIMIT_ON = 'isTodayLimitOn';
export const RANDOM_APODS = 'randomApods';
export const USER_ID = 'userId';

export const DRAWER_EXPLANATION = 'explanation';
export const DRAWER_FAVORITES = 'favorites';
Expand All @@ -43,6 +44,7 @@ export const APOD_OPTIONS: (keyof TAppOptions)[] = [
SHOW_TOP_SITES,
TODAY_COUNT,
TODAY_LIMIT,
USER_ID,
];

export const KEY_MAP = {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useFetchApod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const useFetchApod = ({ hiResOnly, setDrawerIsOpen }: TFetchApodParams) => {
setErrorMessage(false);

if (response.media_type === 'other') {
console.log(response, 'OTHER REPSONSE');
console.log(response, 'OTHER RESPONSE');
fetchApod({ random: true });
return;
}
Expand Down
7 changes: 5 additions & 2 deletions src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "Displays the Astronomy Picture of the Day (APOD) and allows you to review similar images of planets, stars, galaxies and nebulas",
"options_page": "popup.html",
"short_name": "APOD by The Trav",
"version": "4.1.4",
"version": "4.2.0",
"background": { "service_worker": "background.bundle.js" },
"action": {
"default_popup": "popup.html",
Expand All @@ -22,6 +22,9 @@
"matches": []
}
],
"host_permissions": ["https://api.nasa.gov/*"],
"host_permissions": [
"https://api.nasa.gov/*",
"https://apod.redundantrobot.com/apod/*"
],
"permissions": ["topSites", "storage"]
}
4 changes: 2 additions & 2 deletions src/pages/Newtab/ApodBody.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ const ApodBody: React.FC<{ options: TAppOptions }> = ({ options }) => {
return <Loading isLoading={isLoading} />;
}

if (apodResponse.errorMessage) {
return <h1 style={{ color: 'white' }}>{apodResponse.errorMessage}</h1>;
if (errorMessage) {
return <h1 style={{ color: 'white' }}>{errorMessage}</h1>;
}

return apodResponse.media_type === 'video' ? (
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Newtab/Drawer/Tabs/Favorites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const Favorites: React.FC<{
filteredItems.map((item: any, idx: number) => {
return (
<GridImage
key={`${item.date}-${idx}`}
key={`${item.date}`}
goToDate={goToApodDate}
removeItem={removeFavorite}
item={item}
Expand Down
1 change: 1 addition & 0 deletions src/pages/Newtab/Drawer/Tabs/GridImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const GridImage: React.FC<{
}}
>
<img
alt={item.title}
src={item.url || item.imgUrl}
style={{ maxWidth: '100%', maxHeight: '100%' }}
/>
Expand Down
17 changes: 14 additions & 3 deletions src/pages/Newtab/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import React, { useEffect, useState } from 'react';
import { render } from 'react-dom';
import { CURRENT_DATE, DEFAULT_OPTIONS, TODAY_COUNT } from '../../constants';
import {
CURRENT_DATE,
DEFAULT_OPTIONS,
TODAY_COUNT,
USER_ID,
} from '../../constants';
import {
formatDate,
generateUUID,
getAllChrome,
getToday,
isDateToday,
Expand Down Expand Up @@ -53,12 +59,17 @@ const App: React.FC<{ options?: TAppOptions }> = ({ options }) => {
};

getAllChrome((options) => {
const userId = options.userId ?? generateUUID();

if (!options[USER_ID]) {
setChrome({ [USER_ID]: userId });
}

render(
<>
<FontStyles />
<App options={options} />
<App options={{ ...options, [USER_ID]: userId }} />
</>,

window.document.querySelector('#app-container')
);
});
6 changes: 3 additions & 3 deletions src/pages/Newtab/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import {
DRAWER_HISTORY,
} from '../../constants';

// @ts-expect-error
import Montserrat from '../../assets/fonts/Montserrat-VariableFont_wght.ttf';

const black = '#111111';
export const lightBlack = 'rgba(0,0,0, 0.5)';
export const gray = 'rgba(51,51,51, 0.8)';
export const activeGray = 'rgba(80,80,80, 0.8)';
export const lightGray = 'rgba(199,199,199, 0.8)';
const highlightBlue = 'rgb(117, 221, 255)';

// @ts-expect-error
import Montserrat from '../../assets/fonts/Montserrat-VariableFont_wght.ttf';

export const FontStyles = createGlobalStyle`
@font-face {
font-family: 'Montserrat';
Expand Down
25 changes: 20 additions & 5 deletions src/pages/Popup/Popup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
IS_TODAY_LIMIT_ON,
DEFAULT_OPTIONS,
APOD_OPTIONS,
TODAY_LIMIT_COUNT,
TODAY_LIMIT,
} from '../../constants';
import { getChrome, setChrome } from '../../utilities';
Expand Down Expand Up @@ -119,22 +118,38 @@ const Popup = () => {
</p>
<SAboutLinks>
<div>
<a target="_blank" href="https://www.redundantrobot.com">
<a
target="_blank"
href="https://www.redundantrobot.com"
rel="noreferrer"
>
RedundantRobot
</a>
</div>
<div>
<a target="_blank" href="https://www.github.com/travisl12">
<a
target="_blank"
href="https://www.github.com/travisl12"
rel="noreferrer"
>
Github
</a>
</div>
<div>
<a target="_blank" href="https://www.twitter.com/travisl12">
<a
target="_blank"
href="https://www.twitter.com/travisl12"
rel="noreferrer"
>
Twitter
</a>
</div>
<div>
<a target="_blank" href="https://codepen.io/TravisL12">
<a
target="_blank"
href="https://codepen.io/TravisL12"
rel="noreferrer"
>
CodePen
</a>
</div>
Expand Down
6 changes: 5 additions & 1 deletion src/pages/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
IS_TODAY_LIMIT_ON,
APOD_HISTORY,
RANDOM_APODS,
USER_ID,
} from '../constants';

export type THistoryItem = {
Expand All @@ -27,7 +28,7 @@ export type TFavoriteItem = {
imgUrl?: string;
};

export type TFavorites = { [date: string]: TFavoriteItem };
export type TFavorites = Record<string, TFavoriteItem>;

export type TAppOptions = {
[APOD_FAVORITES]: TFavorites;
Expand All @@ -41,6 +42,7 @@ export type TAppOptions = {
[TODAY_COUNT]: number;
[TODAY_LIMIT]: number;
[RANDOM_APODS]?: number;
[USER_ID]?: string;
};

export type TApodResponse = {
Expand All @@ -58,6 +60,8 @@ export type TApodResponse = {
isImageHd?: boolean;
error?: any;
errorMessage?: string;
apodLink?: string;
thumbnailLink?: string;
};

export type TUseNavigationProps = {
Expand Down
51 changes: 22 additions & 29 deletions src/utilities/images.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import {
API_KEY,
APOD_API_URL,
RANDOM_APODS,
RANDOM_FETCH_COUNT,
REDUNDANT_RANDOM_URL,
REDUNDANT_URL,
RELOAD_RANDOM_LIMIT,
} from '../constants';
import axios from 'axios';
Expand All @@ -16,14 +15,16 @@ import {

let isReloadingCache = false;
const reloadCache = async () => {
const params = {
api_key: API_KEY,
count: RANDOM_FETCH_COUNT,
};
const resp = await axios.get(APOD_API_URL, { params });
const images = resp.data.map((item: TApodResponse) =>
transformResponse(item)
);
const resp = await axios.get(REDUNDANT_RANDOM_URL);
const images = resp.data.map((item: TApodResponse) => {
const data = transformResponse(item);
return {
date: data.date,
title: data.title,
media_type: data.media_type,
url: data.url,
};
});

getLocalChrome([RANDOM_APODS], (options) => {
const cache = options[RANDOM_APODS];
Expand Down Expand Up @@ -73,35 +74,31 @@ const transformResponse = (data: TApodResponse) => {
preloadImage(data.url);
preloadImage(data.hdurl);
}
data.apodUrl = `https://apod.nasa.gov/apod/ap${linkDateFormat(
data.date
)}.html`;
data.apodUrl =
data.apodLink ||
`https://apod.nasa.gov/apod/ap${linkDateFormat(data.date)}.html`;
data.date = trimDateString(data.date);
data.isToday = isDateToday(data.date);
return data;
};
export const fetchRandomImage = async (): Promise<TApodResponse> => {
const params = {
api_key: API_KEY,
count: RANDOM_FETCH_COUNT,
};
try {
// Look in cache
const cacheResp = await randomCache();
if (cacheResp) {
return cacheResp;
const resp = await fetchImage({ date: cacheResp.date });
return resp;
}

// Otherwise fetch
const resp = await axios.get(APOD_API_URL, { params });
const images = resp.data.map((item: TApodResponse) =>
transformResponse(item)
);
const { data } = await axios.get(REDUNDANT_RANDOM_URL);
const images = data.map((item: TApodResponse) => transformResponse(item));

return new Promise((resolve) => {
setLocalChrome({ [RANDOM_APODS]: images }, async () => {
const response = await randomCache();
resolve(response);
const resp = await fetchImage({ date: response.date });
resolve(resp);
});
});
} catch (error) {
Expand All @@ -113,12 +110,8 @@ export const fetchRandomImage = async (): Promise<TApodResponse> => {
export const fetchImage = async (
fetchOptions: TFetchOptions = {}
): Promise<TApodResponse> => {
const params = {
api_key: API_KEY,
...fetchOptions,
};
try {
const resp = await axios.get(APOD_API_URL, { params });
const resp = await axios.get(REDUNDANT_URL, { params: fetchOptions });
const data = transformResponse(resp.data);
saveToHistory(data);
return data;
Expand Down
8 changes: 8 additions & 0 deletions src/utilities/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,11 @@ export function titleCase(text: string) {
if (!text) return text;
return text[0].toUpperCase() + text.slice(1);
}

export const generateUUID = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
Loading