Skip to content

Commit

Permalink
Merge pull request #2 from anna-murphy/fixes
Browse files Browse the repository at this point in the history
Fixes
  • Loading branch information
anna-murphy authored Apr 12, 2024
2 parents dccb6a9 + a6a99c4 commit 49e7c9e
Show file tree
Hide file tree
Showing 18 changed files with 149 additions and 345 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/firebase-hosting-merge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
steps:
- uses: actions/checkout@v3
- run: echo "REACT_APP_BUILD_TIME=$(date +%s000)" >> ${GITHUB_ENV}
- run: npm ci && npm run build
- run: yarn && yarn build
- uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: "${{ secrets.GITHUB_TOKEN }}"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/firebase-hosting-pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
steps:
- uses: actions/checkout@v3
- run: echo "REACT_APP_BUILD_TIME=$(date +%s000)" >> ${GITHUB_ENV}
- run: npm ci && npm run build
- run: yarn && yarn build
- uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: "${{ secrets.GITHUB_TOKEN }}"
Expand Down
13 changes: 8 additions & 5 deletions firebase.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@
},
"hosting": {
"public": "dist",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"]
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**",
"function": "feeds"
}
]
},
"functions": [
{
Expand All @@ -38,10 +44,7 @@
"firebase-debug.log",
"firebase-debug.*.log"
],
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
]
"predeploy": ["yarn functions:build"]
}
]
}
17 changes: 16 additions & 1 deletion firestore.indexes.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
{
"indexes": [],
"indexes": [
{
"collectionGroup": "rss",
"queryScope": "COLLECTION",
"fields": [
{
"fieldPath": "feed",
"order": "ASCENDING"
},
{
"fieldPath": "timestamp",
"order": "DESCENDING"
}
]
}
],
"fieldOverrides": []
}
1 change: 1 addition & 0 deletions functions/src/api/routes/capesInTheWestMarch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const citwmFeed: Route = {
handler: async function (_req: Request, res: Response) {
try {
const rssFeed = await getMostRecentRss("Capes in the West March");
res.setHeader("content-type", "application/rss+xml ");
res.status(200).send(rssFeed.rss);
} catch (ex) {
res.sendStatus(404);
Expand Down
4 changes: 2 additions & 2 deletions functions/src/rss/rebuildRssFeed.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { onDocumentCreated } from "firebase-functions/v2/firestore";
import { onDocumentWritten } from "firebase-functions/v2/firestore";
import * as logger from "firebase-functions/logger";

import {
Expand All @@ -13,7 +13,7 @@ import { makeRss } from "../utils/makeRss";
/**
* Update the RSS Feed Document with a new episode once it's created.
*/
export const rebuildRssFeed = onDocumentCreated(
export const rebuildRssFeed = onDocumentWritten(
"api/v1/episodes/{episodeId}",
async (event) => {
try {
Expand Down
18 changes: 12 additions & 6 deletions functions/src/utils/firestore.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { initializeApp } from "firebase-admin";
import { Timestamp, getFirestore } from "firebase-admin/firestore";
import {
FirestoreEvent,
QueryDocumentSnapshot,
} from "firebase-functions/v2/firestore";
DocumentSnapshot,
Timestamp,
getFirestore,
} from "firebase-admin/firestore";
import { Change, FirestoreEvent } from "firebase-functions/v2/firestore";
import { PodcastChannel, PodcastEpisode, RssDocument } from "./types";

initializeApp();
Expand Down Expand Up @@ -68,7 +69,12 @@ export async function getMostRecentRss(feed: string) {
* @returns {T | null}
*/
export function getDataFromEvent<T>(
event: FirestoreEvent<QueryDocumentSnapshot | undefined>,
event: FirestoreEvent<Change<DocumentSnapshot> | undefined>,
) {
return event.data ? (event.data.data() as T) : null;
if (event === undefined) return null;
const eventData = event.data; //event.data.after.data();
if (eventData === undefined) return null;
const afterData = eventData.after.data();
if (afterData === undefined) return null;
return afterData as T;
}
18 changes: 12 additions & 6 deletions functions/src/utils/makeRss.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Timestamp } from "firebase-admin/firestore";
import { PodcastChannel, PodcastEpisode } from "./types";
//import { JSDOM } from "jsdom";
//import { logger } from "firebase-functions/v1";

export function makeRss(feed: PodcastChannel, episodes: PodcastEpisode[]) {
return `<?xml version="1.0" encoding="UTF-8"?>
// xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"
const rssString = `<?xml version="1.0" encoding="UTF-8"?>
<rss
version="2.0"
xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
Expand All @@ -11,11 +14,14 @@ export function makeRss(feed: PodcastChannel, episodes: PodcastEpisode[]) {
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:podcast="https://podcastindex.org/namespace/1.0"
xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
>
${makeChannel(feed, episodes.map((episode) => makeItem(episode)).join(""))}
</rss>`;
//const a = new JSDOM(rssString, { contentType: "text/xml" });
//return a.serialize();
//logger.info(a.serialize);
return rssString;
}

function makeChannel(channel: PodcastChannel, items: string) {
Expand All @@ -38,9 +44,9 @@ function makeChannel(channel: PodcastChannel, items: string) {
<atom:link href="${channel.feedUrl}" rel="self" type="application/rss+xml"/>
<docs>${channel.contact.site}</docs>
<podcast:locked>${channel.metadata.locked}</podcast:locked>
<itunes:complete>${channel.metadata.complete}</itunes:complete>
${items}
</channel>`;
</channel>`;
// <itunes:complete>${channel.metadata.complete}</itunes:complete>
}

function formatCategories(
Expand All @@ -62,7 +68,7 @@ function formatCategories(
function makeItem(episodeData: PodcastEpisode) {
return `<item>
<title>${episodeData.title}</title>
<link>${episodeData.fileData.url}</link>
<link><![CDATA[${episodeData.fileData.url}]]></link>
<guid isPermaLink="true"><![CDATA[${episodeData.fileData.url}]]></guid>
<description><![CDATA[${episodeData.description}]]></description>
<pubDate>${new Timestamp(episodeData.publishDate.seconds, episodeData.publishDate.nanoseconds).toDate().toUTCString()}</pubDate>
Expand All @@ -71,7 +77,7 @@ function makeItem(episodeData: PodcastEpisode) {
<itunes:season>${episodeData.metadata.season}</itunes:season>
<itunes:episode>${episodeData.metadata.episode}</itunes:episode>
<itunes:episodeType>${episodeData.metadata.type || "full"}</itunes:episodeType>
<enclosure url="${episodeData.fileData.url}" length="${episodeData.fileData.size}" type="audio/mpeg"/>
<enclosure url="${episodeData.fileData.url.replace("&", "&amp;")}" length="${episodeData.fileData.size}" type="audio/mpeg"/>
</item>`;
}
/*
Expand Down
10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro check && astro build",
"build": "astro build",
"build:strict": "astro check && yarn build",
"preview": "astro preview",
"astro": "astro",
"deploy": "yarn build && firebase deploy",
"lint": "eslint src --ext .astro,.js,.ts,.json",
"format": "prettier --write .",
"functions:build": "cd functions && yarn build",
"functions:deploy": "firebase deploy --only functions",
"emulators": "yarn emulators:start",
"emulators:start": "firebase emulators:start --import .firebaseEmulators",
"emulators:clean": "yarn emulators:clear && firebase emulators:start --export-on-exit --import .firebaseEmulators",
Expand All @@ -20,8 +23,9 @@
"emulators:set": "tsx scripts/set.ts",
"emulators:reset": "yarn emulators:clear && yarn emulators:set",
"emulators:clear": "rm -rf .firebaseEmulators",
"fetch:citwm": "curl https://capes-in-the-dark.web.app/feeds/capes-in-the-west-march/rss.xml",
"fetch:citwm:emulated": "curl localhost:5001/capes-in-the-dark/us-central1/feeds/capes-in-the-west-march/rss.xml"
"fetch": "tsx scripts/ping.ts",
"fetch:ping": "yarn fetch ping",
"fetch:citwm": "yarn fetch citwm"
},
"dependencies": {
"@astrojs/check": "^0.5.6",
Expand Down
66 changes: 66 additions & 0 deletions scripts/ping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const LOCATIONS = {
cf: "https://us-central1-capes-in-the-dark.cloudfunctions.net/",
capes: "https://capes-in-the-dark.web.app/",
local: "localhost:5001/capes-in-the-dark/us-central1/",
} as const;

const ENDPOINTS = {
ping: "ping",
citwm: "capes-in-the-west-march/rss.xml",
} as const;

type LocationKeys = keyof typeof LOCATIONS;
type Locations = (typeof LOCATIONS)[keyof typeof LOCATIONS];
type EndpointKeys = keyof typeof ENDPOINTS;
type Endpoints = (typeof ENDPOINTS)[keyof typeof ENDPOINTS];
type Url = `${Locations}${Endpoints}`;

function help(): void {
if (process.argv.includes("-h") || process.argv.includes("help")) {
console.log(
"Fetch an API endpoint. Specify locations and endpoints via args",
);
console.log(
`\tLocations: [${Object.keys(LOCATIONS).join(", ")}] (default: ${"cf"})`,
);
console.log(
`\tEndpoints: [${Object.keys(ENDPOINTS).join(", ")}] (default: ${"ping"})`,
);
process.exit();
}
}

function validateLocation(): LocationKeys {
const validLocations = Object.keys(LOCATIONS);
for (const arg of process.argv.map((arg) => arg.toLowerCase())) {
if (validLocations.includes(arg)) return arg as LocationKeys;
}
console.log("No valid location argument found - defaulting to cf");
return "cf" as LocationKeys;
}

function validateEndpoint(): EndpointKeys {
const validEndpoints = Object.keys(ENDPOINTS);
for (const arg of process.argv.map((arg) => arg.toLowerCase())) {
if (validEndpoints.includes(arg)) return arg as EndpointKeys;
}
console.log("No valid endpoint argument found - defaulting to ping");
return "ping" as EndpointKeys;
}

async function doFetch(url: Url): Promise<void> {
console.log(`Fetch: ${url}`);
const resp = await fetch(url);
console.log(`Status: ${resp.status}`);
const text = await resp.text();
console.log(text);
}

function main(): void {
help();
void doFetch(
`${LOCATIONS[validateLocation()]}${ENDPOINTS[validateEndpoint()]}`,
);
}

main();
18 changes: 18 additions & 0 deletions scripts/query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { firestore } from "./utils/firebaseProduction";

async function main(): Promise<void> {
const rssDocs = await firestore
.collection("api/v1/rss")
.where("feed", "==", "Capes in the West March")
.orderBy("timestamp", "desc")
.get();
for (const doc of rssDocs.docs) {
console.log(doc.data());
}
}

main()
.then(() => {
console.log("done");
})
.catch(console.error);
2 changes: 0 additions & 2 deletions scripts/utils/firebaseProduction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ admin.initializeApp({
projectId: "capes-in-the-dark",
});

admin.initializeApp({ projectId: "capes-in-the-dark" });

export const firestore = admin.firestore();
export const storage = admin.storage();
export const auth = admin.auth();
8 changes: 5 additions & 3 deletions src/admin-portal/utils/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { initializeApp } from "firebase/app";
import { connectAuthEmulator, getAuth } from "firebase/auth";
import { connectFirestoreEmulator, getFirestore } from "firebase/firestore";
import { connectStorageEmulator, getStorage } from "firebase/storage";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
apiKey: import.meta.env.PUBLIC_FIREBASE_API_KEY,
Expand All @@ -17,9 +17,11 @@ export const firestore = getFirestore(app);
export const storage = getStorage(app);
export const auth = getAuth(app);

/*
if (import.meta.env.PUBLIC_EMULATORS === "true") {
console.log("USING FIREBASE EMULATORS");
connectFirestoreEmulator(firestore, "127.0.0.1", 8080);
connectStorageEmulator(storage, "127.0.0.1", 9199);
connectAuthEmulator(auth, "http://127.0.0.1:9099");
}
*/
1 change: 0 additions & 1 deletion src/admin-portal/views/Upload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ export function Upload(): JSX.Element {
}
*/


import {
FileInput,
NumberInput,
Expand Down
Loading

0 comments on commit 49e7c9e

Please sign in to comment.