pstream is dead; long live pstream taciturnaxolotl.github.io/pstream-ng/
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

detect region

Pas d9bd48a6 9b09020a

+73
+4
src/index.tsx
··· 29 29 import { ProgressSyncer } from "@/stores/progress/ProgressSyncer"; 30 30 import { SettingsSyncer } from "@/stores/subtitles/SettingsSyncer"; 31 31 import { ThemeProvider } from "@/stores/theme"; 32 + import { detectRegion, useRegionStore } from "@/utils/detectRegion"; 32 33 33 34 import { 34 35 extensionInfo, ··· 136 137 const status = useAsync(async () => { 137 138 changeAppLanguage(useLanguageStore.getState().language); 138 139 await initializeOldStores(); 140 + 141 + const region = await detectRegion(); 142 + useRegionStore.getState().setRegion(region); 139 143 }, []); 140 144 const { t } = useTranslation(); 141 145
+69
src/utils/detectRegion.tsx
··· 1 + import { create } from "zustand"; 2 + import { persist } from "zustand/middleware"; 3 + 4 + export type Region = 5 + | "us-east" 6 + | "us-west" 7 + | "south-america" 8 + | "asia" 9 + | "europe" 10 + | "unknown"; 11 + 12 + interface RegionStore { 13 + region: Region | null; 14 + lastChecked: number | null; 15 + setRegion: (region: Region) => void; 16 + } 17 + 18 + const TEN_DAYS_MS = 10 * 24 * 60 * 60 * 1000; 19 + 20 + export const useRegionStore = create<RegionStore>()( 21 + persist( 22 + (set) => ({ 23 + region: null, 24 + lastChecked: null, 25 + setRegion: (region) => set({ region, lastChecked: Date.now() }), 26 + }), 27 + { 28 + name: "__MW::region", 29 + }, 30 + ), 31 + ); 32 + 33 + function determineRegion(data: { 34 + latitude: number; 35 + longitude: number; 36 + country_code: string; 37 + }): Region { 38 + const { latitude, longitude, country_code: country } = data; 39 + 40 + if (country === "US") return longitude < -100 ? "us-west" : "us-east"; 41 + if (latitude < 0) return "south-america"; 42 + if (longitude > 60) return "asia"; 43 + if (longitude > -10) return "europe"; 44 + return "us-east"; 45 + } 46 + 47 + export async function detectRegion(): Promise<Region> { 48 + const store = useRegionStore.getState(); 49 + 50 + if ( 51 + store.region && 52 + store.lastChecked && 53 + Date.now() - store.lastChecked < TEN_DAYS_MS 54 + ) { 55 + return store.region; 56 + } 57 + 58 + try { 59 + const response = await fetch("https://ipapi.co/json/"); 60 + const data = await response.json(); 61 + 62 + const detectedRegion = determineRegion(data); 63 + store.setRegion(detectedRegion); // Persist the detected region 64 + return detectedRegion; 65 + } catch (error) { 66 + console.warn("Failed to detect region:", error); 67 + return store.region || "unknown"; 68 + } 69 + }