Skip to content

Commit

Permalink
add websocket auth and better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kguzek committed Dec 29, 2024
1 parent 215c7d7 commit d403514
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 18 deletions.
37 changes: 28 additions & 9 deletions src/pages/LiveSeries/Base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
} from "../../misc/models";
import { getErrorMessage, compareEpisodes } from "../../misc/util";
import "./Liveseries.css";
import { getAccessToken } from "../../misc/backend";

export type LiveSeriesOutletContext = {
loading: string[];
Expand Down Expand Up @@ -71,7 +72,8 @@ export default function LiveSeriesBase() {
const location = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const data = useContext(TranslationContext);
const { user } = useContext(AuthContext);
const authContext = useContext(AuthContext);
const { user } = authContext;
const { fetchFromAPI } = useFetchContext();
const { setModalInfo, setModalError, setModalChoice } =
useContext(ModalContext);
Expand All @@ -80,7 +82,7 @@ export default function LiveSeriesBase() {
if (!userShows?.likedShows?.length || !userShows?.subscribedShows?.length)
fetchUserShows();
fetchWatchedEpisodes();
if (!user?.admin) return;
if (!user) return;
connectToWebsocket();
return () => {
if (!existingSocket) return;
Expand All @@ -92,42 +94,59 @@ export default function LiveSeriesBase() {

const hasDecentralisedServer = user?.serverUrl?.startsWith("http");

function connectToWebsocket() {
async function connectToWebsocket() {
let socketFailed: boolean | undefined = undefined;
if (existingSocket) return;
if (!hasDecentralisedServer) {
console.warn("No decentralised server URL provided.");
return;
}
const accessToken = await getAccessToken(authContext);
if (!accessToken) return;

let socket: WebSocket;
const websocketUrlBase = user?.serverUrl?.replace("http", "ws");
try {
socket = new WebSocket(
websocketUrlBase + "liveseries/downloaded-episodes/ws"
`${websocketUrlBase}liveseries/downloaded-episodes/ws?access_token=${accessToken}`
);
} catch (error) {
console.error("Connection error:", error);
console.error("Websocket instantiation error:", error);
setModalError(data.liveSeries.websockets.connectionFailed);
return;
}
setExistingSocket(socket);
socket.onerror = (message) => {
// This usually means the server is online but hasn't yet set up the websocket listener
console.error("Unknown error:", message);
setModalError(data.liveSeries.websockets.error);
// If socketFailed has not yet been set to `false`, it means the server is not reachable
console.error(
socketFailed === undefined ? "Connection error" : "Unknown error:",
message
);
setModalError(
socketFailed === undefined
? data.liveSeries.websockets.connectionFailed
: data.liveSeries.websockets.error
);
socketFailed = true;
};
const poll = (data: DownloadedEpisode[]) =>
socket.send(JSON.stringify({ type: "poll", data }));
socket.onopen = () => poll([]);
socket.onopen = () => {
poll([]);
socketFailed = false;
};
socket.onclose = async (evt) => {
if (evt.wasClean) {
// The server URL is probably misconfigured
setModalError(data.liveSeries.websockets.connectionFailed);
return;
}
if (socketFailed) return;
const reconnect = await setModalChoice(
data.liveSeries.websockets.askReconnect
);
if (reconnect) connectToWebsocket();
if (reconnect) await connectToWebsocket();
};
socket.onmessage = (message) => {
const torrentInfo = JSON.parse(message.data).data as DownloadedEpisode[];
Expand Down
16 changes: 8 additions & 8 deletions src/pages/LiveSeries/TvShow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,14 @@ export default function TvShow() {
const isSubscribed = subscribedFlipped
? !isSubscribedOld
: isSubscribedOld ?? false;
console.log({
tvShowDetails,
userShows,
isLikedOld,
isLiked,
isSubscribedOld,
isSubscribed,
});
// console.log({
// tvShowDetails,
// userShows,
// isLikedOld,
// isLiked,
// isSubscribedOld,
// isSubscribed,
// });
const watchedInShow = watchedEpisodes?.[tvShowDetails.id] ?? {};
const isSeasonWatched = (season: string, episodes: EpisodeType[]) =>
watchedInShow[+season]?.length === episodes.length;
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function Profile() {
});
const json = await res.json();
if (res.ok) {
setServerUrl(json.serverUrl);
setServerUrl(newServerUrl);
setModalInfo(data.profile.serverUrlUpdated(newServerUrl));
const newUser = { ...user, serverUrl: newServerUrl };
setUser(newUser);
Expand Down

0 comments on commit d403514

Please sign in to comment.