Skip to content
Merged
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
32 changes: 22 additions & 10 deletions src/app/(app)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { VideoGrid } from '@/components/video-grid';
import { GENRES, SORTS } from '@/lib/hanime1/types';
import { useTranslate } from '@/lib/i18n/utils';
import { networkErrorMessage } from '@/lib/network/errors';
import type { BottomSheetModal } from '@gorhom/bottom-sheet';
import { useFocusEffect } from 'expo-router';
import { useCallback, useEffect, useRef, useState } from 'react';
Expand Down Expand Up @@ -55,16 +56,25 @@ export default function BrowseScreen() {

// Default browse = genre only (no query, no sort), matching the site. Query is
// added only when typing; sort/tags/broad only when set in the filter sheet.
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, refetch, isFetching } =
useSearchVideos({
variables: {
genre,
sort: filter.sortKey ? SORTS[filter.sortKey] : undefined,
query: debounced || undefined,
tags: filter.tags.length > 0 ? filter.tags : undefined,
broad: filter.broad || undefined,
},
});
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
refetch,
isFetching,
isError,
error,
} = useSearchVideos({
variables: {
genre,
sort: filter.sortKey ? SORTS[filter.sortKey] : undefined,
query: debounced || undefined,
tags: filter.tags.length > 0 ? filter.tags : undefined,
broad: filter.broad || undefined,
},
});

useFocusEffect(useCallback(() => {}, []));

Expand Down Expand Up @@ -127,6 +137,8 @@ export default function BrowseScreen() {
isRefreshing={isFetching && !isLoading}
isFetchingNextPage={isFetchingNextPage}
isLoading={isLoading}
errorText={isError ? networkErrorMessage(error, t) : undefined}
onRetry={() => refetch()}
contentContainerStyle={{ paddingBottom: 24 }}
/>

Expand Down
8 changes: 8 additions & 0 deletions src/app/(app)/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Env } from '@env';
// bundles (binding missing at runtime), destructuring after import works.
import * as ApplicationNS from 'expo-application';
import { ActivityAction, startActivityAsync } from 'expo-intent-launcher';
import { Link } from 'expo-router';
import {
ActivityIndicator,
Platform,
Expand Down Expand Up @@ -222,6 +223,13 @@ export default function SettingsScreen() {
<Text className="text-rose-400">{t('common.clear')}</Text>
</Row>
</Pressable>
<Link href="/logs" asChild>
<Pressable android_ripple={{ color: '#00000020' }}>
<Row label={t('settings.errorLog')} description={t('settings.errorLogDescription')}>
<Icon name="chevron-forward" size={18} color="#71717a" />
</Row>
</Pressable>
</Link>

<SectionTitle>{t('settings.about')}</SectionTitle>
<Pressable
Expand Down
10 changes: 10 additions & 0 deletions src/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ export default function RootLayout() {
),
}}
/>
<Stack.Screen
name="logs"
options={{
headerShown: true,
title: '',
header: ({ navigation }) => (
<BackHeader onBack={() => navigation.goBack()} />
),
}}
/>
</Stack>
</APIProvider>
</PrivacyShield>
Expand Down
81 changes: 81 additions & 0 deletions src/app/logs.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { ScreenErrorBoundary } from '@/components/error-boundary';
import { Icon } from '@/components/icon';
import { SafeAreaView } from '@/components/safe-area-view';
import { useTranslate } from '@/lib/i18n/utils';
import { clearErrorLog, readErrorLog } from '@/lib/logs/error-log';
import { useFocusEffect } from 'expo-router';
import { useCallback, useState } from 'react';
import { ActivityIndicator, Pressable, ScrollView, Share, Text, View } from 'react-native';
import { showMessage } from 'react-native-flash-message';

export { ScreenErrorBoundary as ErrorBoundary };

/**
* Viewer for the plain-text error log (one line per classified network
* failure). The content is a single selectable <Text> — long-press and use
* the system copy menu to copy any range; Share sends the whole file.
*/
export default function ErrorLogScreen() {
const t = useTranslate();
// null = not loaded yet, '' = empty log.
const [log, setLog] = useState<string | null>(null);

useFocusEffect(
useCallback(() => {
void readErrorLog().then(setLog);
}, [])
);

const clear = async () => {
await clearErrorLog();
setLog('');
showMessage({ message: t('logs.cleared'), type: 'success', position: 'top', duration: 1500 });
};

return (
<SafeAreaView className="flex-1 bg-background" edges={['bottom']}>
<View className="flex-row items-center justify-between px-4 pb-2 pt-2">
<Text className="text-xl font-bold text-foreground">{t('logs.title')}</Text>
<View className="flex-row gap-2">
<Pressable
onPress={() => void Share.share({ title: t('logs.title'), message: log ?? '' })}
disabled={!log}
className={`flex-row items-center gap-1.5 rounded-full px-3 py-1.5 ${
log ? 'bg-muted' : 'bg-muted/50'
}`}
>
<Icon name="share-outline" size={14} color="#71717a" />
<Text className="text-foreground">{t('logs.share')}</Text>
</Pressable>
<Pressable
onPress={() => void clear()}
disabled={!log}
className="flex-row items-center rounded-full bg-muted/50 px-3 py-1.5"
>
<Text className="text-rose-400">{t('logs.clear')}</Text>
</Pressable>
</View>
</View>

<Text className="px-4 pb-2 text-xs leading-4 text-muted-foreground">
{t('logs.copyHint')}
</Text>

{log === null ? (
<View className="flex-1 items-center justify-center">
<ActivityIndicator color="#fb7185" />
</View>
) : log === '' ? (
<View className="flex-1 items-center justify-center">
<Text className="text-muted-foreground">{t('logs.empty')}</Text>
</View>
) : (
<ScrollView contentContainerStyle={{ paddingBottom: 32 }}>
<Text selectable className="px-4 text-xs leading-5 text-foreground">
{log}
</Text>
</ScrollView>
)}
</SafeAreaView>
);
}
18 changes: 16 additions & 2 deletions src/app/tag/[name].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,33 @@ import { useSearchVideos } from '@/api/video-queries';
import { ScreenErrorBoundary } from '@/components/error-boundary';
import { SafeAreaView } from '@/components/safe-area-view';
import { VideoGrid } from '@/components/video-grid';
import { useTranslate } from '@/lib/i18n/utils';
import { networkErrorMessage } from '@/lib/network/errors';
import { useLocalSearchParams } from 'expo-router';
import { useMemo } from 'react';
import { Text, View } from 'react-native';

export { ScreenErrorBoundary as ErrorBoundary };

export default function TagScreen() {
const t = useTranslate();
const params = useLocalSearchParams<{ name: string; type?: string }>();
const name = params.name;
// `query` tags (franchise/character, e.g. #絕區零) must be searched as free
// text — the `tags[]` filter knows nothing about them.
const searchTags = params.type === 'query' ? undefined : [name];
const query = params.type === 'query' ? name : undefined;
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, refetch, isFetching } =
useSearchVideos({ variables: { tags: searchTags, query } });
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
refetch,
isFetching,
isError,
error,
} = useSearchVideos({ variables: { tags: searchTags, query } });

const items = useMemo(() => data?.pages.flatMap((p) => p.items) ?? [], [data]);

Expand All @@ -36,6 +48,8 @@ export default function TagScreen() {
isRefreshing={isFetching && !isLoading}
isFetchingNextPage={isFetchingNextPage}
isLoading={isLoading}
errorText={isError ? networkErrorMessage(error, t) : undefined}
onRetry={() => refetch()}
contentContainerStyle={{ paddingBottom: 24 }}
/>
</SafeAreaView>
Expand Down
7 changes: 6 additions & 1 deletion src/app/user/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ import { useUserVideos } from '@/api/video-queries';
import { ScreenErrorBoundary } from '@/components/error-boundary';
import { SafeAreaView } from '@/components/safe-area-view';
import { VideoGrid } from '@/components/video-grid';
import { useTranslate } from '@/lib/i18n/utils';
import { networkErrorMessage } from '@/lib/network/errors';
import { useLocalSearchParams } from 'expo-router';
import { useMemo } from 'react';
import { Text, View } from 'react-native';

export { ScreenErrorBoundary as ErrorBoundary };

export default function UserScreen() {
const t = useTranslate();
const params = useLocalSearchParams<{ id: string; name?: string }>();
const { data, isLoading, refetch, isFetching } = useUserVideos({
const { data, isLoading, refetch, isFetching, isError, error } = useUserVideos({
variables: { id: params.id },
});

Expand All @@ -29,6 +32,8 @@ export default function UserScreen() {
onRefresh={() => refetch()}
isRefreshing={isFetching && !isLoading}
isLoading={isLoading}
errorText={isError ? networkErrorMessage(error, t) : undefined}
onRetry={() => refetch()}
contentContainerStyle={{ paddingBottom: 24 }}
/>
</SafeAreaView>
Expand Down
26 changes: 15 additions & 11 deletions src/app/watch/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import { Icon } from '@/components/icon';
import { StyledVideoView } from '@/components/native-styled';
import { SafeAreaView } from '@/components/safe-area-view';
import { toOfflineDetail } from '@/lib/download/offline-detail';
import { HttpStatusError, buildUrl, endpoints } from '@/lib/hanime1/scraper';
import { buildUrl, endpoints } from '@/lib/hanime1/scraper';
import { haptic, hapticSuccess } from '@/lib/haptics';
import { usePlaybackSettings, useVideoDownload } from '@/lib/hooks';
import { useTranslate } from '@/lib/i18n/utils';
import { AppNetworkError, networkErrorMessage } from '@/lib/network/errors';
import {
useDownloadedStore,
useFavoritesStore,
Expand Down Expand Up @@ -52,8 +53,7 @@ export default function WatchScreen() {
// A 404/410 watch page means the site removed the video. With a local
// download the screen stays open and playable — just notify once; other
// failures (timeouts, bot blocks) stay silent while offline data is shown.
const isRemoved =
isError && error instanceof HttpStatusError && (error.status === 404 || error.status === 410);
const isRemoved = isError && error instanceof AppNetworkError && error.kind === 'notFound';
const removedNotifiedFor = useRef<string | null>(null);
useEffect(() => {
if (!isRemoved || !offlineDetail || removedNotifiedFor.current === id) return;
Expand Down Expand Up @@ -98,11 +98,11 @@ export default function WatchScreen() {

const { autoplay } = usePlaybackSettings();

// Focus guard for the slow-network case: the detail query can resolve long
// after the user has backed out of this screen (it stays mounted in the
// stack). Firing play() then would start a player that was never attached
// to a view — or play audio underneath the previous screen — so autoplay
// must only run while this screen actually has focus.
// Focus guard: a screen stacked under another one (rapid duplicate pushes,
// author→video chains) — or one whose detail query resolves long after the
// user backed out — must never start playing. Its blur-time pause() ran
// before the stream source landed and was a no-op, so a late autoplay would
// layer audio under the focused screen.
const isFocusedRef = useRef(true);

// Start playback automatically when the screen is entered or the source
Expand Down Expand Up @@ -150,9 +150,13 @@ export default function WatchScreen() {

if (!data) {
return (
<View className="flex-1 items-center justify-center bg-background">
<Text className="text-muted-foreground">
{isRemoved ? t('detail.videoRemoved') : t('common.error')}
<View className="flex-1 items-center justify-center bg-background px-8">
<Text className="text-center text-sm leading-5 text-muted-foreground">
{isRemoved
? t('detail.videoRemoved')
: isError
? networkErrorMessage(error, t)
: t('common.error')}
</Text>
<Pressable onPress={() => refetch()} className="mt-3 rounded-full bg-primary px-4 py-2">
<Text className="text-primary-foreground">{t('common.retry')}</Text>
Expand Down
26 changes: 24 additions & 2 deletions src/components/video-grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import { useTranslate } from '@/lib/i18n/utils';
import { FlashList } from '@shopify/flash-list';
import type { ReactElement } from 'react';
import { ActivityIndicator, RefreshControl, ScrollView, Text, View } from 'react-native';
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, Text, View } from 'react-native';

export type VideoGridProps = {
items: TileItem[];
Expand All @@ -18,6 +18,13 @@ export type VideoGridProps = {
isRefreshing?: boolean;
isFetchingNextPage?: boolean;
isLoading?: boolean;
/**
* Classified error message for the failed fetch. When set with no items to
* show, the grid explains the failure (network blocked, offline, …) with a
* retry button — instead of a misleading "no results".
*/
errorText?: string;
onRetry?: () => void;
columns?: number;
/**
* Card form for every tile in the grid. All tiles share one orientation so
Expand All @@ -39,6 +46,8 @@ export function VideoGrid({
isRefreshing,
isFetchingNextPage,
isLoading,
errorText,
onRetry,
columns,
orientation = 'auto',
ListHeaderComponent,
Expand Down Expand Up @@ -113,7 +122,20 @@ export function VideoGrid({
<ScrollView
contentContainerStyle={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}
>
<Text className="text-muted-foreground">{t('common.noResults')}</Text>
{errorText ? (
<>
<Text className="px-8 text-center text-sm leading-5 text-muted-foreground">
{errorText}
</Text>
{onRetry ? (
<Pressable onPress={onRetry} className="mt-4 rounded-full bg-primary px-5 py-2">
<Text className="text-primary-foreground">{t('common.retry')}</Text>
</Pressable>
) : null}
</>
) : (
<Text className="text-muted-foreground">{t('common.noResults')}</Text>
)}
</ScrollView>
}
ListFooterComponent={
Expand Down
11 changes: 8 additions & 3 deletions src/lib/hanime1/scraper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,15 @@ describe('fetchPage', () => {
globalThis.fetch = realFetch;
});

it('throws HttpStatusError carrying the status for non-2xx responses', async () => {
globalThis.fetch = (async () => ({ ok: false, status: 404 })) as unknown as typeof fetch;
it('throws AppNetworkError with kind + status for non-2xx responses', async () => {
globalThis.fetch = (async () => ({
ok: false,
status: 404,
text: async () => '',
})) as unknown as typeof fetch;
await expect(fetchPage('/watch?v=1')).rejects.toMatchObject({
name: 'HttpStatusError',
name: 'AppNetworkError',
kind: 'notFound',
status: 404,
});
});
Expand Down
Loading
Loading